Files
arr/web/src/views/Movie.tsx
T
Miguel PalhasandClaude Opus 5.5 a4aa423b3a refactor(web): the row primitive as utilities
Rows, slots, trays, notes, skeletons, scores and the release cells.
The linked-row pointer rules key on the row knowing it is a link, not
on :has().

Refs #280

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 18:16:32 +00:00

590 lines
19 KiB
TypeScript

// 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 (
<Row
kind="file"
title={fileName(file.path)}
titleStyle="readout"
meta={
<>
<WaiverChip waiver={file.waiver} say={say} />
{subs.chip}
{probedAttributeTags(file.probed).map((attribute) => (
<Chip key={attribute}>{attribute}</Chip>
))}
<Chip>{formatSize(file.size)}</Chip>
</>
}
// the full path is evidence, a tap away rather than a hover away
afterSub={<Expandable className={SUB}>{file.path}</Expandable>}
note={note}
tray={subs.panel}
/>
);
}
export function MovieView({ movieId, toReleases }: { movieId: number; toReleases: boolean }) {
const nav = useNav();
const [movie, setMovie] = useState<LibraryMovie | null>(null);
const [roots, setRoots] = useState<Root[]>([]);
const [files, setFiles] = useState<FilesOutcome | null>(null);
const [subtitles, setSubtitles] = useState(new Map<number, SubtitleStatus>());
const [metadata, setMetadata] = useState<MovieMetadata | null>(null);
const [heroNote, heroSay] = useNote();
const [status, setStatus] = useStatus();
const [releaseStatus, setReleaseStatus] = useStatus();
const [deck, setDeck] = useState<DeckState>({ 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<HTMLButtonElement>(null);
const releasesSection = useRef<HTMLElement>(null);
// guards a stale fetch or poll from painting over a newer one
const sequence = useRef(0);
const pollTimer = useRef<number | undefined>(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<RemoveSubject | null>(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 (
<Deck detail label="movie detail">
<Hero
title={movie?.title ?? ""}
year={movie?.year ?? null}
detail={metadata}
note={heroNote}
onBack={nav.close}
chips={
movie !== null && (
<>
<Chip>{audienceOf(roots, movie.root_id)}</Chip>
<MediaStateChip state={movie.state} wanted={movie.wanted} />
<WaiverChip waiver={movie.waiver} say={heroSay} />
{!movie.wanted && <Chip>not wanted</Chip>}
{movie.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
{/* §9.8: the hero is the row that owns the item, same as the library row */}
<DownloadChip targetKind="movie" targetId={movie.id} say={heroSay} />
</>
)
}
/>
<div className="actionbar">
<button type="button" className={control()} disabled={sweeping} onClick={sweep}>
search indexers
</button>
<span className="actionbar-links">
{/* the trailer resolves from the metadata's own key — no second call.
Hidden when absent rather than shown dead (§9.6). */}
{metadata?.trailer && (
<TrailerLink href={youtubeLink(metadata.trailer.youtube_key)} title={title} />
)}
</span>
<IconControl
glyph="more"
label="library settings for this title"
className="ml-auto"
aria-expanded={moreOpen}
aria-controls="movie-more-panel"
onClick={() => setMoreOpen(!moreOpen)}
/>
</div>
<div className="more-panel" id="movie-more-panel" hidden={!moreOpen}>
<div className="more-links">
{metadata !== null && (
<>
<ProviderLink
mark="tmdb"
label={`open ${title} on TMDB`}
href={tmdbMovieLink(metadata.tmdb_id)}
/>
{metadata.imdb_id !== null && (
<ProviderLink
mark="imdb"
label={`open ${title} on IMDb`}
href={imdbLink(metadata.imdb_id)}
/>
)}
{movie !== null && (
<ProviderLink
mark="rt"
label={`search Rotten Tomatoes for ${movie.title}`}
href={rottenTomatoesSearch(movie.title, movie.year)}
/>
)}
</>
)}
</div>
<div className="more-toggles">
<LampToggle
fill
label="wanted"
pressed={movie?.wanted ?? false}
disabled={busy === "wanted"}
onClick={() => toggle("wanted", "wanted")}
/>
<LampToggle
fill
label="targeted search"
pressed={!(movie?.blocked ?? false)}
// the accessible name carries what the label cannot, at rest and on
aria-description={BLOCKED_EFFECT}
disabled={busy === "blocked"}
onClick={() => toggle("blocked", "targeted search change")}
/>
</div>
{/* §6.3 is the whole point of the flag and a bare toggle hides it: the
note appears when the flag is on, which is when the RSS half is the
thing that surprises. At rest the label and the title carry it. */}
<p className="control-note readout" hidden={!movie?.blocked}>
Targeted search is off. RSS still matches this title, so a release can still arrive.
</p>
<label className="field more-field">
<span className="field-label" id="movie-root-label">
root
</span>
<select
className="form-input"
aria-labelledby="movie-root-label"
value={movie === null ? "" : String(movie.root_id)}
disabled={busy === "root"}
onChange={(event) => changeRoot(Number(event.target.value))}
>
{movieRoots.map((root) => (
<option key={root.id} value={String(root.id)}>
{`${root.audience} · ${root.policy_name}`}
</option>
))}
{/* a root list that does not carry the title's own root still shows
it — a select lying by omission would make the next change move
it blindly */}
{movie !== null && !rootListed && (
<option value={String(movie.root_id)}>{`root ${movie.root_id}`}</option>
)}
</select>
</label>
<button
type="button"
className={control({ look: "quiet", fill: true, danger: true })}
data-kind="delete"
ref={removeButton}
aria-expanded={removeOpen}
aria-controls="remove-panel"
aria-label={movie === null ? undefined : `remove ${movie.title} from the library`}
onClick={() => (removeOpen ? closeRemove() : setRemoveOpen(true))}
>
remove from library
</button>
<div className="remove-panel" id="remove-panel" hidden={!removeOpen}>
{removeOpen && subject.current !== null && (
<RemovePanel
subject={subject.current}
onCancel={closeRemove}
onRemoved={() => {
setRemoveOpen(false);
nav.removed();
}}
/>
)}
</div>
</div>
<StatusSlot status={status} variant="deck" />
<Section labelledBy="label-disk">
<DeckHead
label="on disk"
labelId="label-disk"
titled="section"
count={files?.kind === "files" ? files.files.length : ""}
/>
<Rows>
{files === null && <SkeletonRows count={1} withLead={false} />}
{files?.kind === "error" && (
<EmptyRow text={`files unreadable — ${files.detail}`} tone="fault" />
)}
{files?.kind === "files" && files.files.length === 0 && (
<EmptyRow text="nothing on disk yet — imports land here" />
)}
{files?.kind === "files" &&
files.files.map((file) => (
<FileRow
key={file.id}
file={file}
status={subtitles.get(file.id)}
refresh={refreshSubtitles}
/>
))}
</Rows>
</Section>
<Section labelledBy="label-releases" ref={releasesSection}>
<DeckHead label="releases" labelId="label-releases" titled="section" />
<StatusSlot status={releaseStatus} variant="deck" />
<Buckets state={deck} actions={actions} />
</Section>
</Deck>
);
}