// The movie page (§9.6, issue #149): what the film is, its library // controls, what is on disk, then the §9.3 release deck. import { useCallback, useEffect, useRef, useState } from "react"; import { Buckets, type DeckState, type ReleaseActions } from "../buckets"; import { LAYER, useEscape, useNav } from "../context"; import { Hero, ProviderLink, RemovePanel, type RemoveSubject, TrailerLink } from "../detail"; import { control, SUB } from "../look"; import { fileName, imdbLink, type MovieMetadata, movieMetadata, rottenTomatoesSearch, tmdbMovieLink, updateMovie, youtubeLink, } from "../movie"; import { audienceOf, BLOCKED_EFFECT, DownloadChip, MediaStateChip, NO_TARGETED_SEARCH, WaiverChip, } from "../parts"; import { type FilesOutcome, formatSize, formatSweepAge, grabRelease, libraryFolder, type MovieFile, type MovieRelease, movieFiles, movieReleases, movieSearchState, probedAttributeTags, queueSearch, removeMovie, sweepExpected, waiveAndGrab, } from "../releases"; import { allRoots, fetchMovie, type LibraryMovie, type Root } from "../search"; import { useSubtitleSection } from "../subs-panel"; import { movieSubtitleStatus, type SubtitleStatus } from "../subtitles"; import { Chip, Deck, DeckHead, EmptyRow, Expandable, IconControl, LampToggle, Row, Rows, Section, SkeletonRows, StatusSlot, useNote, useStatus, } from "../ui"; // §6.2: the sweep runs on the daemon's own cadence. Poll modestly, and // stop promising once the backoff window is plausibly in charge. const SWEEP_POLL_MS = 5000; const SWEEP_WAIT_MS = 150_000; /** One imported file: ffprobe truth and honest waivers (§5.6, §5.7). */ function FileRow({ file, status, refresh, }: { file: MovieFile; status: SubtitleStatus | undefined; refresh: () => void; }) { const [note, say] = useNote(); // the languages a file carries belong together: subtitles sit beside // the audio tags `probedAttributeTags` just ended on const subs = useSubtitleSection(status, refresh); return ( {subs.chip} {probedAttributeTags(file.probed).map((attribute) => ( {attribute} ))} {formatSize(file.size)} } // the full path is evidence, a tap away rather than a hover away afterSub={{file.path}} note={note} tray={subs.panel} /> ); } export function MovieView({ movieId, toReleases }: { movieId: number; toReleases: boolean }) { const nav = useNav(); const [movie, setMovie] = useState(null); const [roots, setRoots] = useState([]); const [files, setFiles] = useState(null); const [subtitles, setSubtitles] = useState(new Map()); const [metadata, setMetadata] = useState(null); const [heroNote, heroSay] = useNote(); const [status, setStatus] = useStatus(); const [releaseStatus, setReleaseStatus] = useStatus(); const [deck, setDeck] = useState({ kind: "skeleton" }); const [sweeping, setSweeping] = useState(false); const [moreOpen, setMoreOpen] = useState(false); const [removeOpen, setRemoveOpen] = useState(false); const [busy, setBusy] = useState<"wanted" | "blocked" | "root" | null>(null); const removeButton = useRef(null); const releasesSection = useRef(null); // guards a stale fetch or poll from painting over a newer one const sequence = useRef(0); const pollTimer = useRef(undefined); const live = useRef(true); const paints = useRef(0); useEffect(() => { live.current = true; return () => { live.current = false; sequence.current += 1; window.clearTimeout(pollTimer.current); }; }, []); const current = (ticket: number) => live.current && ticket === sequence.current; const paint = (releases: MovieRelease[]) => { paints.current += 1; setDeck({ kind: "releases", releases, paint: paints.current }); }; const refreshMovie = async () => { const fresh = await fetchMovie(movieId); if (fresh !== null && live.current) { setMovie(fresh); } }; /** Poll the movie until `last_searched_at` moves off `baseline`. */ const watchSweep = (baseline: string | null, ticket: number) => { setSweeping(true); setReleaseStatus("sweeping indexers…", undefined, true); const deadline = Date.now() + SWEEP_WAIT_MS; const tick = async () => { if (!current(ticket)) { return; } const outcome = await movieSearchState(movieId); if (!current(ticket)) { return; } if (outcome.kind === "state" && outcome.movie.last_searched_at !== baseline) { setSweeping(false); await loadReleases(ticket); return; } if (Date.now() >= deadline) { setSweeping(false); setReleaseStatus( "sweep has not landed yet — it may be waiting out its backoff; results appear here once it runs", ); return; } pollTimer.current = window.setTimeout(() => void tick(), SWEEP_POLL_MS); }; pollTimer.current = window.setTimeout(() => void tick(), SWEEP_POLL_MS); }; /** * The empty deck is two different truths (§9.3, issue 101): a sweep that * has not landed yet, or a sweep that landed and found nothing. Only the * movie's `last_searched_at` can tell them apart. */ const emptyVerdict = async (ticket: number) => { const outcome = await movieSearchState(movieId); if (!current(ticket)) { return; } if (outcome.kind === "state" && outcome.movie.last_searched_at !== null) { setReleaseStatus( `no releases found — sweep finished ${formatSweepAge(outcome.movie.last_searched_at)}; search indexers runs a new one`, ); return; } if (outcome.kind === "state" && sweepExpected(outcome.movie)) { // first sweep still in flight — visibly different from "nothing found" watchSweep(null, ticket); return; } setReleaseStatus("no releases indexed for this title — search indexers runs a sweep now"); }; const loadReleases = async (ticket: number) => { window.clearTimeout(pollTimer.current); setReleaseStatus("reading releases…", undefined, true); const outcome = await movieReleases(movieId); if (!current(ticket)) { return; } if (outcome.kind === "error") { setDeck({ kind: "none" }); setReleaseStatus(`releases unavailable — ${outcome.detail}`, "fault"); return; } if (outcome.releases.length === 0) { setDeck({ kind: "none" }); await emptyVerdict(ticket); return; } paint(outcome.releases); setReleaseStatus(null); }; /** Refetch verdicts only — the reload an override-written grab triggers. */ const reloadReleases = async () => { sequence.current += 1; const ticket = sequence.current; // a sweep being watched ends here; the verdicts below are the newer answer window.clearTimeout(pollTimer.current); setSweeping(false); const outcome = await movieReleases(movieId); if (!current(ticket)) { return; } if (outcome.kind === "results") { if (outcome.releases.length === 0) { setDeck({ kind: "none" }); } else { paint(outcome.releases); } } }; const actions: ReleaseActions = { reload: reloadReleases, notify: (text, tone) => setReleaseStatus(text, tone), grab: async (release, bucket) => { if (bucket !== "eligible") { return waiveAndGrab(movieId, release.id, release.rejected_rule); } const outcome = await grabRelease(movieId, release.id); return outcome.kind === "done" ? { kind: "done", overrideWritten: false } : { kind: "error", detail: outcome.detail, overrideWritten: false }; }, }; /** * Re-read this movie's subtitle status after a manual fetch or * translation. The panels stay mounted, so an operator who grabbed from a * search still has the search. */ const refreshSubtitles = useCallback(() => { void movieSubtitleStatus(movieId).then((outcome) => { if (outcome.kind === "error" || !live.current) { return; } setSubtitles(new Map(outcome.statuses.map((one) => [one.media_file_id, one]))); }); }, [movieId]); // biome-ignore lint/correctness/useExhaustiveDependencies: the page loads once per title; it is keyed by id useEffect(() => { sequence.current += 1; const ticket = sequence.current; void (async () => { const [fresh, filesOutcome, subtitleOutcome, fetchedRoots] = await Promise.all([ fetchMovie(movieId), movieFiles(movieId), movieSubtitleStatus(movieId), allRoots().catch(() => [] as Root[]), ]); if (!current(ticket)) { return; } setRoots(fetchedRoots); if (fresh === null) { setStatus("movie unavailable", "fault"); return; } setMovie(fresh); setSubtitles( new Map( subtitleOutcome.kind === "status" ? subtitleOutcome.statuses.map((one) => [one.media_file_id, one]) : [], ), ); setFiles(filesOutcome); void movieMetadata(movieId).then((outcome) => { if (!current(ticket)) { return; } if (outcome.kind === "error") { // the stored identity stands; the hero's note says why the rest is absent heroSay(`metadata unavailable — ${outcome.detail}`, "fault"); return; } setMetadata(outcome.metadata); }); await loadReleases(ticket); })(); }, [movieId]); // `/movies/{id}/releases` keeps resolving (#149): same page, deck section in view useEffect(() => { if (toReleases && movie !== null) { releasesSection.current?.scrollIntoView({ block: "start" }); } }, [toReleases, movie]); const closeRemove = () => { setRemoveOpen(false); removeButton.current?.focus(); }; // capture: one Escape steps back one layer — the confirmation first, then the page useEscape(LAYER.detail, true, nav.close); useEscape(LAYER.confirm, removeOpen, closeRemove); const toggle = (field: "wanted" | "blocked", label: string) => { if (movie === null) { return; } setBusy(field); void updateMovie(movie.id, { [field]: !movie[field] }).then((outcome) => { if (outcome.kind === "error") { setBusy(null); setStatus(`${label} failed — ${outcome.detail}`, "fault"); return; } void refreshMovie().then(() => setBusy(null)); }); }; const changeRoot = (next: number) => { if (movie === null || !Number.isInteger(next) || next === movie.root_id) { return; } setBusy("root"); void updateMovie(movie.id, { root_id: next }).then((outcome) => { setBusy(null); if (outcome.kind === "error") { setStatus(`root change failed — ${outcome.detail}`, "fault"); return; } void refreshMovie(); }); }; const sweep = () => { if (movie === null) { return; } setSweeping(true); void (async () => { // snapshot the last sweep first: its change is the completion signal const before = await movieSearchState(movie.id); if (!live.current) { return; } const baseline = before.kind === "state" ? before.movie.last_searched_at : null; const outcome = await queueSearch(movie.id); if (!live.current) { return; } if (outcome.kind === "error") { setSweeping(false); setReleaseStatus(`search failed — ${outcome.detail}`, "fault"); return; } sequence.current += 1; window.clearTimeout(pollTimer.current); watchSweep(baseline, sequence.current); })(); }; const removeSubject: RemoveSubject | null = movie === null ? null : { title: movie.title, files: () => movieFiles(movie.id), folder: libraryFolder, remove: () => removeMovie(movie.id), seedLine: "the torrent keeps seeding until its tracker rule clears.", }; // one subject per title, so the panel reads the files once const subject = useRef(null); if (subject.current === null && removeSubject !== null) { subject.current = removeSubject; } const title = movie?.title ?? "this movie"; const movieRoots = roots.filter((root) => root.kind === "movie"); const rootListed = movie !== null && movieRoots.some((root) => root.id === movie.root_id); return ( {audienceOf(roots, movie.root_id)} {!movie.wanted && not wanted} {movie.blocked && {NO_TARGETED_SEARCH}} {/* §9.8: the hero is the row that owns the item, same as the library row */} ) } />
{/* the trailer resolves from the metadata's own key — no second call. Hidden when absent rather than shown dead (§9.6). */} {metadata?.trailer && ( )} setMoreOpen(!moreOpen)} />
{files === null && } {files?.kind === "error" && ( )} {files?.kind === "files" && files.files.length === 0 && ( )} {files?.kind === "files" && files.files.map((file) => ( ))}
); }