Files
arr/web/src/releases.ts
T
naps62-yolo 9adbca3acd
ci / web (push) Successful in 42s
e2e / e2e (push) Successful in 2m6s
ci / rust (push) Successful in 2m50s
ci / image (push) Successful in 3m23s
fix(core): waive untagged audio on main roots (#282)
2026-11-15 13:22:29 +00:00

594 lines
18 KiB
TypeScript

// Hand-written mirror of arr-api's /api/movies/{id}/releases, grab and
// override schemas — same reasoning as search.ts: the generated client
// (src/api/) is uncommitted, so CI's tsc cannot see it.
export type Bucket = "eligible" | "waived" | "rejected";
/** What the release name claims (arr-parse `NameClaims`, §5.6). */
export interface ParsedClaims {
resolution?: string | null;
source?: string | null;
codec?: string | null;
hdr?: string[];
languages?: string[];
}
export interface MovieRelease {
id: number;
indexer_id: number;
guid: string;
name: string;
size: number;
seeders: number | null;
publish_date: string | null;
download_url: string;
parsed: ParsedClaims;
score: number | null;
verdict: string | null;
rejected_rule: string | null;
/**
* What the blacklist recorded this release as failing on (#227, §6.3).
* Null on every row the blacklist does not hold, and on a blacklisted row
* whose entry has since gone — `blacklisted` is then all the record has.
*/
blacklist_reason: string | null;
}
export type ReleasesOutcome =
| { kind: "results"; releases: MovieRelease[] }
| { kind: "error"; detail: string };
export async function movieReleases(movieId: number): Promise<ReleasesOutcome> {
try {
const response = await fetch(`/api/movies/${movieId}/releases`);
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "results", releases: (await response.json()) as MovieRelease[] };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
/** The slice of a movie that says whether a sweep ran and whether one is due. */
export interface MovieSearchState {
wanted: boolean;
blocked: boolean;
state: string;
last_searched_at: string | null;
}
export type MovieStateOutcome =
| { kind: "state"; movie: MovieSearchState }
| { kind: "error"; detail: string };
export async function movieSearchState(movieId: number): Promise<MovieStateOutcome> {
try {
const response = await fetch(`/api/movies/${movieId}`);
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "state", movie: (await response.json()) as MovieSearchState };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
/**
* The slice of an episode that says whether a sweep ran. The episode deck
* needs its own settled answer: a season has `last_pack_search_at`, a movie
* has `last_searched_at`, and until this existed the episode deck had
* neither, so an empty deck sat on "sweeping indexers…" until it timed out
* even when the sweep had already come back with nothing.
*/
export interface EpisodeSearchState {
wanted: boolean;
state: string;
last_searched_at: string | null;
}
export type EpisodeStateOutcome =
| { kind: "state"; episode: EpisodeSearchState }
| { kind: "error"; detail: string };
export async function episodeSearchState(episodeId: number): Promise<EpisodeStateOutcome> {
try {
const response = await fetch(`/api/episodes/${episodeId}`);
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "state", episode: (await response.json()) as EpisodeSearchState };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
/**
* Whether the daemon's reconcile loop will sweep this title on its own
* (§6.2 targeted search: wanted, not blocked, nothing on disk or in flight).
*/
export function sweepExpected(movie: MovieSearchState): boolean {
return movie.wanted && !movie.blocked && movie.state === "missing";
}
/** `last_searched_at` as a coarse age — evidence the empty verdict is real. */
export function formatSweepAge(lastSearchedAt: string, now = Date.now()): string {
const swept = Date.parse(lastSearchedAt);
if (Number.isNaN(swept)) {
return "earlier";
}
const minutes = Math.round((now - swept) / 60_000);
if (minutes < 2) {
return "just now";
}
if (minutes < 60) {
return `${minutes} min ago`;
}
if (minutes < 48 * 60) {
return `${Math.round(minutes / 60)} h ago`;
}
return `${Math.round(minutes / (24 * 60))} d ago`;
}
/** Which lane a season's missing episodes take (#182, §6.2). */
export type SeasonLane = "season_pack" | "per_episode";
/** What holds a season off the pack lane (#182). */
export type PackLaneReason = "no_episodes" | "still_airing" | "episodes_on_disk" | "pack_backoff";
/**
* Why the season deck holds what it holds, from
* `/api/series/{id}/seasons/{n}/pack-state`. An empty deck is three states,
* not one: a pack sweep still running, a pack sweep that found nothing, and
* a season on the per-episode lane, where no pack sweep is coming.
*/
export interface SeasonPackState {
lane: SeasonLane;
reason: PackLaneReason | null;
pack_failures: number;
pack_retry_at: string | null;
last_pack_search_at: string | null;
import_failure: ImportFailure | null;
}
/**
* A pack that downloaded in full and was condemned at import (#227, §5.7).
*
* The torrent stays where it is — §7.3 hands that lifecycle to the reaper —
* the release is blacklisted and every episode it covered reopens as a gap.
* Nothing on screen joined those facts, so the season read `0/10` as though
* no grab had ever been tried and the operator found out by opening
* qBittorrent.
*/
export interface ImportFailure {
release: string;
/** A policy rule name, or a sentence about the release. See `blacklistClass`. */
reason: string | null;
failed_at: string | null;
}
export type PackStateOutcome =
| { kind: "state"; state: SeasonPackState }
| { kind: "error"; detail: string };
export async function seasonPackState(
seriesId: number,
seasonNumber: number,
): Promise<PackStateOutcome> {
try {
const response = await fetch(`/api/series/${seriesId}/seasons/${seasonNumber}/pack-state`);
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "state", state: (await response.json()) as SeasonPackState };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
/**
* `pack_retry_at` as a coarse wait. The deck says how long the lane stays
* quiet, so "it retries on its own" is a promise with a date on it.
*/
export function formatRetryWait(retryAt: string, now = Date.now()): string {
const reopens = Date.parse(retryAt);
if (Number.isNaN(reopens)) {
return "later";
}
const minutes = Math.round((reopens - now) / 60_000);
if (minutes < 2) {
return "any moment";
}
if (minutes < 60) {
return `${minutes} min`;
}
if (minutes < 48 * 60) {
return `${Math.round(minutes / 60)} h`;
}
return `${Math.round(minutes / (24 * 60))} d`;
}
/** One library file as `/api/movies/{id}/files` reports it (§5.6, §5.7). */
export interface MovieFile {
id: number;
path: string;
size: number;
probed: unknown;
waiver: string | null;
}
export type FilesOutcome =
| { kind: "files"; files: MovieFile[] }
| { kind: "error"; detail: string };
/**
* What this title actually put on disk. The removal confirmation names it
* rather than promising in the abstract: the service knows only what it
* wrote (§2), so this list is the whole truth about what a files-too remove
* would unlink.
*/
export async function movieFiles(movieId: number): Promise<FilesOutcome> {
try {
const response = await fetch(`/api/movies/${movieId}/files`);
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "files", files: (await response.json()) as MovieFile[] };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
/**
* The §7.4 folder these files share — one folder per title, so a single path
* names everything a files-too remove takes. `null` when the files disagree,
* which the panel then says instead of naming one folder falsely.
*/
export function libraryFolder(files: { path: string }[]): string | null {
const folders = new Set(files.map((file) => file.path.slice(0, file.path.lastIndexOf("/"))));
if (folders.size !== 1) {
return null;
}
const folder = [...folders][0];
return folder === undefined || folder === "" ? null : folder;
}
export function totalSize(files: { size: number }[]): number {
return files.reduce((sum, file) => sum + file.size, 0);
}
export type ActionOutcome = { kind: "done" } | { kind: "error"; detail: string };
/**
* Remove the title from the library. Both the row and its §7.4 folder go.
* The torrent keeps seeding — the reaper owns that lifecycle (§7.3) and a
* hardlinked file loses only its library name.
*/
export async function removeMovie(movieId: number): Promise<ActionOutcome> {
try {
const response = await fetch(`/api/movies/${movieId}`, {
method: "DELETE",
});
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "done" };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
/** §6.2 manual trigger: one targeted sweep, user-initiated. */
export async function queueSearch(movieId: number): Promise<ActionOutcome> {
try {
const response = await fetch(`/api/movies/${movieId}/search`, { method: "POST" });
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "done" };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
export async function grabRelease(movieId: number, releaseId: number): Promise<ActionOutcome> {
try {
const response = await fetch(`/api/movies/${movieId}/releases/${releaseId}/grab`, {
method: "POST",
});
if (!response.ok) {
return { kind: "error", detail: await errorDetail(response) };
}
return { kind: "done" };
} catch {
return { kind: "error", detail: "daemon unreachable" };
}
}
/**
* The per-title override one click on a waived row writes (§5.2, §9.3).
* Mapping a rule name to its override is bookkeeping, not policy — the
* verdict itself always comes from the API.
*
* `size` relaxes §5.5's floor for this title only, and only into a waiver:
* the release stays out of automatic grabbing and imports on the record as
* a §5.7 waiver. No band is right for every title, which is why the
* override exists at all.
*/
export function waiverOverride(rule: string | null): Record<string, unknown> | null {
switch (rule) {
case "required_audio":
return { allow_english_audio: true };
case "resolution":
return { only_4k: false };
case "size":
return { allow_below_floor: true };
default:
return null;
}
}
/** Whether one click on this row has an override to write (§9.3). */
export function overridable(release: { rejected_rule: string | null }): boolean {
return waiverOverride(release.rejected_rule) !== null;
}
export type WaiveOutcome =
| { kind: "done"; overrideWritten: boolean }
| { kind: "error"; detail: string; overrideWritten: boolean };
/** One click on a waived row: write the override, then grab (§9.3). */
export async function waiveAndGrab(
movieId: number,
releaseId: number,
rule: string | null,
): Promise<WaiveOutcome> {
const override = waiverOverride(rule);
let overrideWritten = false;
if (override) {
try {
const current = await fetch(`/api/movies/${movieId}`);
if (!current.ok) {
return { kind: "error", detail: await errorDetail(current), overrideWritten };
}
const movie = (await current.json()) as { overrides: Record<string, unknown> };
const patch = await fetch(`/api/movies/${movieId}`, {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ overrides: { ...movie.overrides, ...override } }),
});
if (!patch.ok) {
return { kind: "error", detail: await errorDetail(patch), overrideWritten };
}
overrideWritten = true;
} catch {
return { kind: "error", detail: "daemon unreachable", overrideWritten };
}
}
const grabbed = await grabRelease(movieId, releaseId);
if (grabbed.kind === "error") {
return { kind: "error", detail: grabbed.detail, overrideWritten };
}
return { kind: "done", overrideWritten };
}
export function bucketOf(release: MovieRelease): Bucket {
if (release.verdict === "eligible") {
return "eligible";
}
if (release.verdict === "waived") {
return "waived";
}
return "rejected";
}
/**
* The probed attributes a file row shows as chips (§5.6, §7.4) — ffprobe
* truth, not name claims. Shared by movie and episode file rows; the probe
* JSON arrives untyped from the API, so the shape is narrowed here.
*
* Audio is reported as the set of languages present, one chip each.
*/
export function probedAttributeTags(probed: unknown): string[] {
if (probed === null || typeof probed !== "object") {
return [];
}
const probe = probed as {
resolution?: string | null;
source?: string | null;
hdr?: string | null;
audio_tracks?: { language?: string | null }[] | null;
};
const tags: string[] = [];
if (probe.resolution) {
tags.push(probe.resolution);
}
if (probe.source) {
tags.push(probe.source);
}
if (probe.hdr && probe.hdr !== "SDR") {
tags.push(probe.hdr);
}
// Set, not push: commentary tracks repeat the feature audio's language,
// and no test catches a row that renders `en` three times.
const languages = new Set<string>();
for (const track of probe.audio_tracks ?? []) {
if (track.language) {
languages.add(track.language);
}
}
tags.push(...languages);
return tags;
}
/* ---- chip formatting: parsed attributes to fixed-width mono values ---- */
const SOURCE_LABEL: Record<string, string> = {
Cam: "cam",
Telesync: "ts",
Telecine: "tc",
Screener: "scr",
Dvd: "dvd",
Hdtv: "hdtv",
WebRip: "webrip",
WebDl: "web-dl",
BluRay: "bluray",
Remux: "remux",
};
const HDR_LABEL: Record<string, string> = {
DolbyVision: "DV",
Hdr10Plus: "HDR10+",
Hdr10: "HDR10",
Hdr: "HDR",
Hlg: "HLG",
Sdr: "SDR",
};
const LANGUAGE_LABEL: Record<string, string> = {
PtBr: "pt-BR",
PtPt: "pt-PT",
Portuguese: "pt",
English: "en",
French: "fr",
German: "de",
Spanish: "es",
Italian: "it",
Multi: "multi",
Dual: "dual",
};
/** §5.7 rule names as short chip words. */
const RULE_LABEL: Record<string, string> = {
required_audio: "audio",
dub_blacklist: "dub",
portuguese_unverified: "pt unverified",
audio_language_untagged: "audio untagged",
dolby_vision_profile: "dv profile",
resolution: "resolution",
source: "source",
size: "size",
};
export function formatScore(score: number | null): string {
return score === null ? "—" : String(Math.round(score));
}
export function formatResolution(parsed: ParsedClaims): string {
return parsed.resolution ?? "—";
}
export function formatSource(parsed: ParsedClaims): string {
if (!parsed.source) {
return "—";
}
return SOURCE_LABEL[parsed.source] ?? parsed.source.toLowerCase();
}
export function formatHdr(parsed: ParsedClaims): string {
const markers = parsed.hdr ?? [];
if (markers.length === 0) {
return "—";
}
return markers.map((marker) => HDR_LABEL[marker] ?? marker).join(" ");
}
export function formatAudio(parsed: ParsedClaims): string {
const markers = parsed.languages ?? [];
if (markers.length === 0) {
return "—";
}
return markers.map((marker) => LANGUAGE_LABEL[marker] ?? marker.toLowerCase()).join(" ");
}
export function formatSize(bytes: number): string {
if (bytes <= 0) {
return "—";
}
const gib = bytes / 2 ** 30;
if (gib >= 100) {
return `${Math.round(gib)}G`;
}
if (gib >= 1) {
return `${gib.toFixed(1)}G`;
}
return `${Math.round(bytes / 2 ** 20)}M`;
}
export function formatSeeders(seeders: number | null): string {
return seeders === null ? "—" : String(seeders);
}
export function ruleLabel(rule: string | null): string {
if (rule === null) {
return "unclassified";
}
return RULE_LABEL[rule] ?? rule.replaceAll("_", " ");
}
/**
* What a blacklisting was: the policy turning a file down, or the release
* itself failing (#227).
*
* The blacklist reason is either a policy rule name — the same vocabulary
* `rejected_rule` uses — or a sentence about the release, written where the
* import gave up before any rule was consulted. The two demand opposite
* decisions: a size rejection is the operator's own floor and they can relax
* it, a corrupt or mismatched pack is not theirs to argue with. `unknown` is
* a row the blacklist no longer answers for; nothing is claimed about it.
*/
export type BlacklistClass = "policy" | "release" | "unknown";
export function blacklistClass(reason: string | null): BlacklistClass {
if (reason === null) {
return "unknown";
}
return reason in RULE_LABEL ? "policy" : "release";
}
/** The reason as a chip word: a rule's short label, or the sentence itself. */
export function blacklistReasonLabel(reason: string | null): string {
return reason === null ? "reason not recorded" : (RULE_LABEL[reason] ?? reason);
}
/**
* What the operator does about it, which is the whole difference between the
* two classes — and the sentence #227 exists to put on screen.
*/
export function blacklistAdvice(reason: string | null): string {
switch (blacklistClass(reason)) {
case "policy":
return waiverOverride(reason) === null
? "policy rejected the file — that rule has no per-title relaxation"
: `policy rejected the file — relax ${ruleLabel(reason)} for this title and the next candidate can pass`;
case "release":
return "the release itself failed at import — a retry downloads the same files";
default:
return "blacklisted before the reason was recorded";
}
}
export async function errorDetail(response: Response): Promise<string> {
try {
const body = (await response.json()) as { error?: string };
return body.error ?? `http ${response.status}`;
} catch {
return `http ${response.status}`;
}
}
/**
* Like {@link errorDetail}, but also surfaces `ErrorBody.code` — the
* machine-readable discriminant a client switches on instead of matching the
* message text (issue #221). `code` is `undefined` on every error that has
* none, which is most of them.
*/
export async function errorBody(response: Response): Promise<{ detail: string; code?: string }> {
try {
const body = (await response.json()) as { error?: string; code?: string };
return { detail: body.error ?? `http ${response.status}`, code: body.code };
} catch {
return { detail: `http ${response.status}` };
}
}