// The series page (§4.1, §4.2, §9.3, issue 129): what the show is, its // library controls, then the season tree with each season's episodes. import { useCallback, useEffect, useRef, useState } from "react"; import { LAYER, type TvDeckRequest, useEscape, useNav } from "../context"; import { Hero, ProviderLink, RemovePanel, type RemoveSubject, TrailerLink } from "../detail"; import { ArmedDeleteIcon } from "../icons"; import { seriesStatusChipRedundant } from "../library"; import { rottenTomatoesSearch, tmdbSeriesLink, tvdbLink, youtubeLink } from "../movie"; import { audienceOf, CountsChip, DownloadChip, EpisodeCountsChip, episodeTag, MediaStateChip, NO_TARGETED_SEARCH, two, WaiverChip, } from "../parts"; import { blacklistAdvice, blacklistClass, blacklistReasonLabel, formatSweepAge } from "../releases"; import { allRoots, type Root } from "../search"; import { type ApiEpisode, type ApiSeason, type ApiSeries, type EpisodeFile, episodeTarget, fetchSeasons, fetchSeries, fetchSeriesFiles, fileAttributeTags, formatAirDate, isUnaired, refreshSeriesMetadata, removeEpisodeFiles, removeSeasonFiles, removeSeries, type SeriesMetadata, seasonCounts, seasonTarget, seriesFolder, seriesMetadata, setEpisodeWanted, setSeasonTracked, updateSeries, } from "../series"; import { useSubtitleSection } from "../subs-panel"; import { type EpisodeSubtitleStatus, seriesSubtitleStatus } from "../subtitles"; import { type ActionSlot, ArmedDeleteWord, Chip, Control, Deck, DeckHead, EmptyRow, IconControl, LampToggle, Row, Rows, Section, SkeletonRows, StatusSlot, useNote, useStatus, } from "../ui"; /** * Issue #177: the on-demand refresh a new series' add sends (#176) lands * within seconds. Poll modestly and give up bounded so a page left open * does not spin forever. */ const SERIES_REFRESH_POLL_MS = 2000; const SERIES_REFRESH_WAIT_MS = 30_000; /** What a season or episode row asks of the page that owns it. */ interface TreeActions { seriesId: number; seriesTitle: string; /** Refetch the tree, then give focus to the control with this `data-focus-id`. */ reload: (focusKey?: string) => void; fail: (text: string) => void; openDeck: (request: TvDeckRequest, origin: HTMLElement) => void; files: Map; subtitles: Map; refreshSubtitles: () => void; } /** A toggle that writes, then repaints the tree from what the API says. */ function WritingToggle({ label, pressed, write, focusId, }: { label: string; pressed: boolean; write: () => Promise; focusId?: string; }) { const [busy, setBusy] = useState(false); return ( { setBusy(true); void write().then(() => setBusy(false)); }} /> ); } function SeasonRow({ season, open, onToggleOpen, tree, }: { season: ApiSeason; open: boolean; onToggleOpen: () => void; tree: TreeActions; }) { const [note, say] = useNote(); // season 0 never counts toward tracking or totals (§4.1, §4.2); say so const name = season.number === 0 ? "specials · s00" : `season ${two(season.number)}`; const short = season.number === 0 ? "specials" : `season ${two(season.number)}`; const counts = seasonCounts(season); const track = () => setSeasonTracked(tree.seriesId, season.number, !season.tracked).then((outcome) => { if (outcome.kind === "error") { tree.fail(`tracking failed — ${outcome.detail}`); return false; } // §4.1: turning tracking on marks revealed episodes wanted; turning // it off withdraws nothing. The refetch paints both truths. tree.reload(`track-${season.number}`); return true; }); // #174: files go, episodes stop being wanted, the season stays listed. // Only offered with files on disk — intent alone is the tracked toggle. const hasFiles = season.episodes.some((episode) => tree.files.has(episode.id)); const removeFiles = () => removeSeasonFiles(tree.seriesId, season.number).then((outcome) => { if (outcome.kind === "error") { tree.fail(`remove failed — ${outcome.detail}`); tree.reload(); return false; } // the delete disappears with the files; the tracked toggle survives tree.reload(`track-${season.number}`); return undefined; }); const deleteLabel = `delete ${short} files from disk`; // #227: the season the operator's report is about read `0/10` with // nothing saying a pack had been grabbed, downloaded in full and thrown // out at import. The counts chip beside this one is exactly the number // that looked like nothing was ever tried. const failure = season.import_failure; const failureKind = failure ? blacklistClass(failure.reason) : null; const told = failure ? `a pack for this season downloaded in full and failed at import${ failure.failed_at === null ? "" : ` ${formatSweepAge(failure.failed_at)}` } — ${failure.release} · ${blacklistAdvice(failure.reason)}` : ""; return ( } title={name} // the season's name expands it too — the chevron stays the accessible control bodyClassName="r-toggle-body" onBodyClick={(event) => { if (event.target instanceof Element && event.target.closest("button, [role=button]")) { return; } onToggleOpen(); }} meta={ <> {counts.total > 0 && ( )} {failure && failureKind && ( {`import failed · ${blacklistReasonLabel(failure.reason)}`} )} {/* the season-level twin of the episode flag: gone upstream while files under it remained */} {season.vanished && vanished} {/* §9.8: a season row aggregates its own pack grab, last on its line */} } actions={[ { node: ( ), width: "toggle", wide: true, }, { node: ( tree.openDeck( { title: tree.seriesTitle, sub: `season ${two(season.number)} · packs`, seriesId: tree.seriesId, target: seasonTarget(tree.seriesId, season.number), route: { kind: "seasonReleases", seriesId: tree.seriesId, seasonNumber: season.number, }, }, event.currentTarget, ) } /> ), width: "icon", }, { node: hasFiles ? ( say(text, "warn")} /> ) : null, width: "icon", wide: true, }, ]} more={ <> {hasFiles && } } note={note} tray={ } /> ); } function EpisodeRow({ seasonNumber, episode, tree, }: { seasonNumber: number; episode: ApiEpisode; tree: TreeActions; }) { const [note, say] = useNote(); const tagText = episodeTag(seasonNumber, episode.number); const aired = !isUnaired(episode.air_date); const onDisk = episode.state === "available"; const status = tree.subtitles.get(episode.id); const subs = useSubtitleSection(status, tree.refreshSubtitles); const file = tree.files.get(episode.id); // #174: the file goes and the episode stops being wanted; the row stays // listed. Same arm-then-confirm as a settings row. const removeFile = () => removeEpisodeFiles(episode.id).then((outcome) => { if (outcome.kind === "error") { tree.fail(`remove failed — ${outcome.detail}`); tree.reload(); return false; } // once missing, the row's want control is what remains to focus tree.reload(`want-${episode.id}`); return undefined; }); const want = () => setEpisodeWanted(episode.id, !episode.wanted).then((outcome) => { if (outcome.kind === "error") { tree.fail(`want failed — ${outcome.detail}`); return false; } tree.reload(`want-${episode.id}`); return true; }); const deleteLabel = `delete the ${tagText} file from disk`; const actions: ActionSlot[] = [ { node: aired && !onDisk ? ( ) : null, width: "toggle", wide: true, }, { node: aired && !onDisk ? ( tree.openDeck( { title: tree.seriesTitle, sub: `${tagText} · ${episode.title}`, seriesId: tree.seriesId, target: episodeTarget(episode.id), route: { kind: "episodeReleases", episodeId: episode.id }, }, event.currentTarget, ) } /> ) : null, width: "icon", }, { node: aired && onDisk ? ( say(text, "warn")} /> ) : null, width: "icon", wide: true, }, ]; const hasMore = aired; if (!hasMore) { actions.push({ node: null, width: "icon", narrow: true }); } // the want toggle only renders for the missing state, so the chip would // just repeat it; an unaired episode says so instead of offering a search const stateChip = !aired ? ( unaired ) : episode.state !== "missing" ? ( ) : null; return ( {`E${two(episode.number)}`}} title={episode.title === "" ? "—" : episode.title} meta={ <> {stateChip} {/* issue 122: gone upstream while its file remained — a conflict, not a state */} {episode.vanished && vanished} {/* subtitles, then the waiver, then the probed attributes — the row reads language first, then what was relaxed to let the file in */} {subs.chip} {file && } {/* §7.4: attribute tags come from ffprobe, so they are true */} {file && fileAttributeTags(file).map((attribute) => ( {attribute} ))} {formatAirDate(episode.air_date)} {/* §9.8: nothing here if the episode is part of a season pack grab — that download is `target_kind: "season"` and shows on the season row */} } actions={actions} more={ hasMore ? ( onDisk ? ( ) : ( ) ) : undefined } note={note} tray={subs.panel} /> ); } export function SeriesView({ seriesId, covered }: { seriesId: number; covered: boolean }) { const nav = useNav(); const view = useRef(null); const [series, setSeries] = useState(null); const [seasons, setSeasons] = useState(null); const [roots, setRoots] = useState([]); const [files, setFiles] = useState(new Map()); const [subtitles, setSubtitles] = useState(new Map()); const [metadata, setMetadata] = useState(null); // which seasons stand open survives the refetch every action triggers const [expanded, setExpanded] = useState(new Set()); const [heroNote, heroSay] = useNote(); const [status, setStatus] = useStatus(); const [moreOpen, setMoreOpen] = useState(false); const [removeOpen, setRemoveOpen] = useState(false); const [rootBusy, setRootBusy] = useState(false); // set once the bounded poll for a pending metadata refresh times out const [refreshGaveUp, setRefreshGaveUp] = useState(false); const [retrying, setRetrying] = useState(false); const removeButton = useRef(null); // the control to refocus once the refetch a click triggered repainted const focusKey = useRef(null); // guards a stale fetch from painting over a newer view const sequence = useRef(0); const live = useRef(true); const refreshPollTimer = useRef(undefined); useEffect(() => { live.current = true; return () => { live.current = false; sequence.current += 1; window.clearTimeout(refreshPollTimer.current); }; }, []); const current = (ticket: number) => live.current && ticket === sequence.current; /** * Poll while a refresh is pending, painting seasons as soon as they land * with no manual reload. Stops on arrival, on the refresh being recorded * done with none, or once `SERIES_REFRESH_WAIT_MS` passes — a page left * open must not poll forever (#177). */ const watchRefresh = (ticket: number) => { window.clearTimeout(refreshPollTimer.current); const deadline = Date.now() + SERIES_REFRESH_WAIT_MS; const tick = async () => { if (!current(ticket)) { return; } const [detail, seasonsOutcome] = await Promise.all([ fetchSeries(seriesId), fetchSeasons(seriesId), ]); if (!current(ticket)) { return; } if (detail && seasonsOutcome.kind === "seasons") { setSeries(detail); setSeasons(seasonsOutcome.seasons); if (detail.metadata_refreshed_at !== null || seasonsOutcome.seasons.length > 0) { return; } } if (Date.now() >= deadline) { setRefreshGaveUp(true); return; } refreshPollTimer.current = window.setTimeout(() => void tick(), SERIES_REFRESH_POLL_MS); }; refreshPollTimer.current = window.setTimeout(() => void tick(), SERIES_REFRESH_POLL_MS); }; // biome-ignore lint/correctness/useExhaustiveDependencies: the page is keyed by series id; its helpers are per-render const load = useCallback( async (focus?: string) => { focusKey.current = focus ?? null; sequence.current += 1; const ticket = sequence.current; window.clearTimeout(refreshPollTimer.current); const [detail, seasonsOutcome, filesOutcome, subtitleOutcome, fetchedRoots] = await Promise.all([ fetchSeries(seriesId), fetchSeasons(seriesId), fetchSeriesFiles(seriesId), seriesSubtitleStatus(seriesId), allRoots().catch(() => [] as Root[]), ]); if (!current(ticket)) { return; } setRoots(fetchedRoots); if (!detail) { setStatus("series unavailable", "fault"); return; } if (seasonsOutcome.kind === "error") { setStatus(`seasons unavailable — ${seasonsOutcome.detail}`, "fault"); return; } setSeries(detail); setSeasons(seasonsOutcome.seasons); setFiles( new Map( filesOutcome.kind === "files" ? filesOutcome.files.map((file) => [file.episode_id, file]) : [], ), ); setSubtitles( new Map( subtitleOutcome.kind === "status" ? subtitleOutcome.statuses.map((one) => [one.episode_id, one]) : [], ), ); setStatus(null); if (detail.metadata_refreshed_at === null && seasonsOutcome.seasons.length === 0) { watchRefresh(ticket); } void seriesMetadata(seriesId).then((outcome) => { if (!current(ticket)) { return; } if (outcome.kind === "error") { // the operational header stands; the hero's note says why the rest is absent heroSay(`metadata unavailable — ${outcome.detail}`, "fault"); return; } setMetadata(outcome.metadata); }); }, [seriesId], ); useEffect(() => { void load(); }, [load]); // A file delete rebuilds the season tree and moves focus to the control // that replaced the delete action. Keep keyboard context without making // the browser scroll the freshly repainted page back to that control. useEffect(() => { if (focusKey.current === null || seasons === null) { return; } view.current ?.querySelector(`[data-focus-id="${focusKey.current}"]`) ?.focus({ preventScroll: true }); focusKey.current = null; }, [seasons]); /** * Re-read the series' subtitle status after a manual fetch or translation * and repaint the chips in place — one call for the whole series (§9.6), * and the open panel survives it. */ const refreshSubtitles = useCallback(() => { void seriesSubtitleStatus(seriesId).then((outcome) => { if (outcome.kind === "error" || !live.current) { return; } setSubtitles(new Map(outcome.statuses.map((one) => [one.episode_id, one]))); }); }, [seriesId]); /** The empty state's retry control: resend the on-demand command by hand. */ const retryRefresh = async () => { const ticket = sequence.current; setRetrying(true); setRefreshGaveUp(false); const outcome = await refreshSeriesMetadata(seriesId); setRetrying(false); if (!current(ticket)) { return; } if (outcome.kind === "error") { setRefreshGaveUp(true); setStatus(`refresh failed — ${outcome.detail}`, "fault"); return; } watchRefresh(ticket); }; const closeRemove = () => { setRemoveOpen(false); removeButton.current?.focus(); }; // one Escape steps back one layer: the confirmation first, then the page useEscape(LAYER.detail, !covered, nav.close); useEscape(LAYER.confirm, removeOpen && !covered, closeRemove); const changeRoot = (next: number) => { if (series === null || !Number.isInteger(next) || next === series.root_id) { return; } setRootBusy(true); void updateSeries(series.id, { root_id: next }).then((outcome) => { setRootBusy(false); if (outcome.kind === "error") { setStatus(`root change failed — ${outcome.detail}`, "fault"); return; } void load("series-root"); }); }; const subject = useRef(null); if (subject.current === null && series !== null) { subject.current = { title: series.title, files: () => fetchSeriesFiles(seriesId), folder: seriesFolder, remove: () => removeSeries(seriesId), seedLine: "torrents keep seeding until their tracker rules clear.", }; } const tree: TreeActions = { seriesId, seriesTitle: series?.title ?? "", reload: (focus) => void load(focus), fail: (text) => setStatus(text, "fault"), openDeck: nav.openTvDeck, files, subtitles, refreshSubtitles, }; /** * A never-refreshed series (`metadata_refreshed_at` null) reads as a * refresh under way, since #176 queues one on add and it lands within * seconds. A refreshed series with no seasons is a settled, if rare, * empty state upstream — the two must not share a message (#177). */ const seasonsEmpty = series !== null && series.metadata_refreshed_at === null ? ( refreshGaveUp ? ( void retryRefresh()} /> ) : (
  • {" refreshing metadata — seasons will appear here"}
  • ) ) : ( ); const title = series?.title ?? "this series"; const tvRoots = roots.filter((root) => root.kind === "tv"); const rootListed = series !== null && tvRoots.some((root) => root.id === series.root_id); return ( ); }