// The tv release deck: §9.3 for season packs and single episodes, opened // over the series page. import { useEffect, useRef, useState } from "react"; import { Buckets, type DeckState, type ReleaseActions } from "../buckets"; import { LAYER, type TvDeckRequest, useEscape, useNav } from "../context"; import { blacklistAdvice, blacklistClass, blacklistReasonLabel, formatRetryWait, formatSweepAge, type ImportFailure, type MovieRelease, type PackStateOutcome, type SeasonPackState, } from "../releases"; import { waiveAndGrabTv } from "../series"; import { Deck, IconControl, type Status, StatusSlot } from "../ui"; /** §6.2: the sweep runs on the daemon's cadence. Poll modestly, give up softly. */ const TV_SWEEP_POLL_MS = 5000; const TV_SWEEP_WAIT_MS = 150_000; export function TvDeckView({ request }: { request: TvDeckRequest }) { const nav = useNav(); const [status, setStatusState] = useState(null); const [deck, setDeck] = useState({ kind: "skeleton" }); const [failure, setFailure] = useState(null); const [sweeping, setSweepingState] = useState(false); const sweepingRef = useRef(false); const setSweeping = (on: boolean) => { sweepingRef.current = on; setSweepingState(on); }; const back = useRef(null); // guards a stale fetch from painting over a newer view const sequence = useRef(0); const pollTimer = useRef(undefined); const live = useRef(true); const paints = useRef(0); const { target } = request; useEffect(() => { live.current = true; back.current?.focus({ preventScroll: true }); window.scrollTo({ top: 0 }); return () => { live.current = false; sequence.current += 1; window.clearTimeout(pollTimer.current); }; }, []); useEscape(LAYER.tvDeck, true, nav.close); const current = (ticket: number) => live.current && ticket === sequence.current; const setStatus = (text: string | null, tone?: "fault", busy = false) => { setStatusState(text === null ? null : { text, tone, busy }); }; /** * A status that carries its own way out. A season held off the pack lane * cannot be helped by the head's re-search alone (#181, #182), so the * sentence that explains the wait also offers the retry that ends it. */ const setStatusAction = (text: string, label: string, run: () => void) => { setStatusState({ text, action: { label, run } }); }; const paint = (releases: MovieRelease[]) => { paints.current += 1; setDeck({ kind: "releases", releases, paint: paints.current }); }; const actions: ReleaseActions = { reload: () => load(), notify: (text, tone) => setStatus(text, tone), grab: (release, bucket) => { if (bucket !== "eligible") { return waiveAndGrabTv(request.seriesId, target, release.id, release.rejected_rule); } return target .grab(release.id) .then((outcome) => outcome.kind === "done" ? { kind: "done" as const, overrideWritten: false } : { kind: "error" as const, detail: outcome.detail, overrideWritten: false }, ); }, }; async function load(sweepIfEmpty = false) { sequence.current += 1; const ticket = sequence.current; window.clearTimeout(pollTimer.current); setStatus("reading releases…", undefined, true); const outcome = await target.releases(); if (!current(ticket)) { return; } if (outcome.kind === "error") { setDeck({ kind: "none" }); setStatus(`releases unavailable — ${outcome.detail}`, "fault"); return; } const painted = outcome.releases.length > 0; if (painted) { setSweeping(false); paint(outcome.releases); } // One read of the season's state, shared by the notice and the empty // verdict below — they answer two questions from the same row. const pack = await target.packState?.(); if (!current(ticket)) { return; } setFailure(pack?.kind === "state" ? pack.state.import_failure : null); if (!painted) { setDeck({ kind: "none" }); await emptyVerdict(ticket, sweepIfEmpty, pack); return; } setStatus(null); } /** * An empty season deck is three different truths (#182), and until the * season could say which, it blamed backoff for all three: a pack sweep * still running, a pack sweep that ran and found nothing, and a season on * the per-episode lane, where no pack sweep is coming at all. The lane * answers the third; `last_pack_search_at` separates the first two, the * same way a movie's `last_searched_at` does (#177). */ async function emptyVerdict(ticket: number, sweepIfEmpty: boolean, known?: PackStateOutcome) { // An episode deck has no pack lane, so none of what follows applies to // it: its own row carries the stamp that separates a sweep in flight // from a sweep that came back empty. const episode = await target.searchState?.(); if (!current(ticket)) { return; } if (episode?.kind === "state") { setSweeping(false); if (episode.episode.last_searched_at !== null) { setStatus( `no releases found — indexers last swept ${formatSweepAge(episode.episode.last_searched_at)}; search indexers runs a new one`, ); return; } if (sweepIfEmpty) { void startSweep(); return; } setStatus("no releases indexed yet — search indexers queues a targeted sweep"); return; } const outcome = known ?? (await target.packState?.()); if (!current(ticket)) { return; } if (outcome?.kind === "state" && outcome.state.lane === "per_episode") { setSweeping(false); describePerEpisode(outcome.state); return; } if (outcome?.kind === "state" && outcome.state.last_pack_search_at !== null) { setSweeping(false); setStatus( `no season pack found — indexers last swept ${formatSweepAge(outcome.state.last_pack_search_at)}; search indexers runs a new one`, ); return; } // issue 167: an empty deck sweeps on open instead of describing a sweep if (sweepIfEmpty) { void startSweep(outcome?.kind === "state" ? outcome.state : null); return; } setStatus("no releases indexed yet — search indexers queues a targeted sweep"); } /** * Name the lane instead of the backoff. A season grabbing episode by * episode has no pack to show and never will while the reason holds, so * the deck says which reason it is and where the releases actually are. */ function describePerEpisode(state: SeasonPackState) { const elsewhere = "open an episode for its releases"; if (state.reason === "no_episodes") { setStatus( "no episodes known for this season yet — a metadata refresh has to find them before anything can be searched", ); return; } if (state.reason === "still_airing") { setStatus( `season still airing — a pack is only searched once every episode has aired, so this one is grabbed episode by episode; ${elsewhere}`, ); return; } if (state.reason === "episodes_on_disk") { setStatus( `episodes already on disk — a pack would re-import them, so the rest is grabbed episode by episode; ${elsewhere}`, ); return; } const failures = state.pack_failures === 1 ? "1 failed pack grab" : `${state.pack_failures} failed pack grabs`; const quiet = state.pack_retry_at === null ? "pack search is quiet until its backoff elapses" : `pack search is quiet for another ${formatRetryWait(state.pack_retry_at)}, then retries on its own`; setStatusAction( `${failures} — ${quiet}. episodes are grabbed one at a time meanwhile.`, "retry the pack now", () => { void startSweep(state); }, ); } /** * A sweep is done when its releases appear, or when the season stamps the * pack search it just finished. `baseline` is that stamp as it read before * the sweep was queued: once it moves, an empty deck is a settled answer * rather than a pending one, and `load` says so. */ function watchSweep(baseline: string | null, ticket: number) { setSweeping(true); setStatus("sweeping indexers…", undefined, true); const deadline = Date.now() + TV_SWEEP_WAIT_MS; const again = () => { pollTimer.current = window.setTimeout(() => void tick(), TV_SWEEP_POLL_MS); }; const tick = async () => { if (!current(ticket)) { return; } const outcome = await target.releases(); if (!current(ticket)) { return; } if (outcome.kind === "results" && outcome.releases.length > 0) { setSweeping(false); paint(outcome.releases); setStatus(null); return; } const episode = await target.searchState?.(); if (!current(ticket)) { return; } if (episode?.kind === "state") { if (episode.episode.last_searched_at !== baseline) { setSweeping(false); await emptyVerdict(ticket, false); } else { again(); } return; } const state = await target.packState?.(); if (!current(ticket)) { return; } if (state?.kind === "state") { setFailure(state.state.import_failure); } if (state?.kind === "state" && state.state.last_pack_search_at !== baseline) { setSweeping(false); await emptyVerdict(ticket, false); return; } if (Date.now() >= deadline) { setSweeping(false); setStatus( "sweep has not landed yet — nothing has come back from the indexers; results appear here when it does", ); return; } again(); }; again(); } /** * Queue a targeted sweep, then watch for it to land (§6.2). `known` is the * lane as it read a moment ago, so the watch is only entered when a pack * sweep is actually expected: on the per-episode lane the sweep searches * episodes, and waiting for a pack that is not coming is the lie #182 is * about. A failed pack is the exception — a manual search waives its * window and does try a pack (#181). */ async function startSweep(known?: SeasonPackState | null) { // the status line's retry stays clickable until the watch replaces it if (sweepingRef.current) { return; } sweepingRef.current = true; setSweeping(true); // The stamp the watch below waits to move. An episode stamps its own // row; reading it before the search is queued is what keeps the finished // sweep from being mistaken for the new one. const episodeBefore = await target .searchState?.() .then((it) => (it.kind === "state" ? it.episode.last_searched_at : null)); const before = known === undefined ? await target.packState?.().then((it) => (it.kind === "state" ? it.state : null)) : known; if (!live.current) { return; } const outcome = await target.search(); if (!live.current) { return; } sequence.current += 1; window.clearTimeout(pollTimer.current); if (outcome.kind === "error") { setSweeping(false); setStatus(`search failed — ${outcome.detail}`, "fault"); return; } if (before && before.lane === "per_episode" && before.reason !== "pack_backoff") { setSweeping(false); setStatus("searching the season's episodes — open an episode for its releases"); return; } watchSweep( target.searchState ? (episodeBefore ?? null) : (before?.last_pack_search_at ?? null), sequence.current, ); } // biome-ignore lint/correctness/useExhaustiveDependencies: one read per deck; the deck is keyed by its target useEffect(() => { void load(true); }, []); // #227: the season's own history, above the candidates. A pack that // downloaded in full and was condemned at import (§5.7) blacklists the // release and puts every episode back to `missing`, which leaves the season // reading `0/10` as though nothing had ever been tried. It sits outside the // status line because it is a fact about the season, not about the request // in flight, and it has to survive a sweep that repaints the status. let failureWhat = ""; if (failure !== null) { // A rule name reads as a preposition — "condemned on size"; a reason // written as a sentence has to be quoted, not conjugated. const on = blacklistClass(failure.reason) === "policy" ? ` on ${blacklistReasonLabel(failure.reason)}` : ""; const said = blacklistClass(failure.reason) === "release" ? `${failure.reason}. ` : ""; failureWhat = `downloaded in full, then condemned at import${on} — ${said}every episode went back to missing and the release is blacklisted.`; } return ( {/* a detail page without a hero still gives its head room under the rail */}

{request.title}

{request.sub ?? ""}
); }