import { create } from 'zustand'; import * as api from '../plex/api'; import { parseItem } from '../plex/parse'; import type { Item } from '../plex/types'; import { appInfo, invoke, isNative, listen } from '../platform/native'; import { useSession } from '../app/session'; import { useSettings } from '../app/settings'; import { isWatched } from '../app/format'; import { toast, toastError } from '../ui/overlays'; export type DownloadStatus = 'queued' | 'downloading' | 'paused' | 'completed' | 'failed'; export interface DownloadMeta { serverId: string; serverName: string; ratingKey: string; partKey: string; raw: any; localAssets?: Record; } export interface Download { id: string; filePath: string; total: number; received: number; status: DownloadStatus; error?: string | null; meta: DownloadMeta; createdAt: number; speed: number; } interface DownloadsState { items: Download[]; ready: boolean; dir: string; init(): Promise; idFor(ratingKey: string, serverId?: string): string; localFileFor(ratingKey: string): string | null; start(item: Item): Promise; startAll(item: Item): Promise; pause(id: string): void; resume(id: string): Promise; remove(id: string): Promise; resumeInterrupted(): void; setDir(dir: string): Promise; itemOf(d: Download): Item; } function sanitize(s: string) { return s.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim() || 'Untitled'; } /** Trims metadata kept for offline display: no extras, related hubs or raw blobs. */ function slim(raw: any) { const { Extras, Related, OnDeck, ...rest } = raw ?? {}; void Extras; void Related; void OnDeck; return rest; } export const useDownloads = create((set, get) => ({ items: [], ready: false, dir: '', async init() { if (!isNative || get().ready) return; const info = await appInfo(); const dir = useSettings.getState().downloadDir || info.defaultDownloadDir; await invoke('download_set_dir', { dir }).catch(() => {}); const items = await invoke('download_list'); set({ items, ready: true, dir }); listen('download', (d) => { const prev = get().items.find((x) => x.id === d.id); set({ items: prev ? get().items.map((x) => (x.id === d.id ? d : x)) : [d, ...get().items] }); if (d.status === 'completed' && prev && prev.status !== 'completed') toast(`Downloaded “${d.meta.raw?.title ?? 'title'}”`, 'success'); if (d.status === 'failed' && prev?.status !== 'failed' && d.error) toast(d.error, 'error'); }); listen('download-removed', (id) => set({ items: get().items.filter((x) => x.id !== id) })); }, idFor(ratingKey, serverId) { const sid = serverId ?? useSession.getState().server?.machineId ?? 'offline'; return `${sid}-${ratingKey}`; }, localFileFor(ratingKey) { const d = get().items.find((x) => x.meta.ratingKey === ratingKey && x.status === 'completed'); return d?.filePath ?? null; }, async start(input) { const server = useSession.getState().server; if (!isNative) { toast('Downloads are available in the Kaleido desktop app.', 'error'); return; } if (!server) return; try { await get().init(); const item = await api.metadata(server, input.id); const media = item.media[0]; const part = media?.parts[0]; if (!part) throw new Error('This title has no downloadable file.'); const id = get().idFor(item.id); if (get().items.some((d) => d.id === id && d.status !== 'failed')) { toast('This title is already in Downloads.'); return; } const ext = part.file.split('.').pop() || part.container || media.container || 'mkv'; const baseName = part.file.split(/[\\/]/).pop() || `${item.title}.${ext}`; const folder = item.type === 'episode' ? `${sanitize(item.grandparentTitle)}/Season ${item.parentIndex}` : sanitize(item.year ? `${item.title} (${item.year})` : item.title); const assets: Record = {}; const poster = item.type === 'episode' ? item.grandparentThumb : item.thumb; if (poster) assets.poster = server.image(poster, 360, 540); if (item.type === 'episode' && item.thumb) assets.still = server.image(item.thumb, 640, 360); const backdrop = item.type === 'episode' ? item.grandparentArt : item.art; if (backdrop) assets.art = server.image(backdrop, 1280, 720); if (item.logo) assets.logo = server.image(item.logo, 600, 200, { format: 'png' }); await invoke('download_start', { request: { id, url: server.signed(part.key, { download: 1 }), folder, fileName: sanitize(baseName), meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw) } satisfies DownloadMeta, assets, }, }); toast(`Downloading “${item.type === 'episode' ? `${item.grandparentTitle} · ${item.title}` : item.title}”`, 'success'); } catch (e) { toastError(e); } }, async startAll(item) { const server = useSession.getState().server; if (!server) return; try { const leaves = await api.allLeaves(server, item.id); const percent = useSettings.getState().watchedPercent; const todo = leaves.filter((e) => !isWatched(e, percent)); const list = todo.length ? todo : leaves; toast(`Queued ${list.length} episode${list.length === 1 ? '' : 's'} for download`, 'success'); for (const e of list) await get().start(e); } catch (e) { toastError(e); } }, pause(id) { invoke('download_pause', { id }).catch(toastError); }, async resume(id) { const d = get().items.find((x) => x.id === id); const server = useSession.getState().server; if (!d || !server) return; if (server.machineId !== d.meta.serverId) { toast(`Connect to ${d.meta.serverName} to resume this download.`, 'error'); return; } await invoke('download_resume', { id, url: server.signed(d.meta.partKey, { download: 1 }) }).catch(toastError); }, async remove(id) { await invoke('download_remove', { id, deleteFiles: true }).catch(toastError); }, resumeInterrupted() { const server = useSession.getState().server; if (!server) return; for (const d of get().items) if (d.status === 'paused' && d.error === 'interrupted' && d.meta.serverId === server.machineId) get().resume(d.id); }, async setDir(dir) { await invoke('download_set_dir', { dir }); useSettings.getState().set('downloadDir', dir); set({ dir }); }, itemOf(d) { return parseItem(d.meta.raw ?? {}); }, }));