Cotton code
652 lines · 34.4 KB · TypeScriptRaw
/** * COTTON CINEMAS IN THE OBJECT (owner, 5 Nov 2026: Cotton Cinemas, the * definition accepted, iOS first; the film tables may be reshaped and the * owner's films uploaded again). The tables are the cinemas kit's (film, * film_season, film_episode, watch in crates/cotton-core/kits/personal/tables); * these are the acts and the read the object runs for them: * * - `find_film { query } | { film }`: TMDB, asked by the object with the *   Worker's TMDB_API_KEY (never logged, never said in an answer or kept in a *   row). A query takes TMDB's best match (a film or a series) and makes a *   Want to watch film from it, or fills the film already holding that TMDB *   id; `film` fills the named row from TMDB, by its tmdb_id, else by its *   title and year. Only EMPTY columns are filled (TheTVDB's id too, as tvdb_id, when TMDB's *   external ids name one), each fill said in the film's `filled_from` (`{"synopsis": "tmdb"}`); the poster and the *   backdrop are fetched once and kept as the object's media (artwork's *   `picture`). A series also gets its seasons (film_season, matched by *   number) and their episodes (film_episode, matched by season and number), *   made or filled the same way, each episode's still kept once. A server *   with no TMDB key answers `not_connected`; TMDB answering 403 or 429 is *   `lookup_failed` (503, try later), not answering at all `lookup_failed` *   (502), and nothing found `no_film_found` (404). * - `reshape_films`: the owner's one-time move of the film family onto the *   Cinemas shape, keeping every row (see `reshapeFilms`). * - `film_converted { table, id, file, poster? }`: the Mac importer's word *   that a film or an episode waiting for it (needs_mac) now plays: its *   stream is `file`, the upload it converted (`source_file`) goes from R2 *   after the write (see `filmConverted`). * - `GET /v1/films/pending`: what waits for the Mac (see `pending`). * - `GET /v1/films/subtitles/asked`: the films and episodes the phone asked *   subtitles for (see `subtitlesAsked`). * - `GET /v1/films/find?id=<id or prefix>`: one film or episode by its id, or *   the rows an id's prefix names, with the clear columns a Mac plays it from *   (see `findFilm`). * * Looking up is asynchronous and the write is not, so find_film is prepared * before the act's transaction (src/business.ts `filmPrepare`) and written in * it. */import { picture, USER_AGENT, type ArtworkHost, type Fetcher } from "./artwork.ts";import { filling, type Engine, type Outcome } from "./engine.ts";import { derivedId } from "./import/ids.ts";import { isSealedRow } from "./seal.ts";import { refuse, text } from "./http.ts";import type { Data } from "./mcp/context.ts";import { filledFrom } from "./filled_from.ts";import type { Store, StoredRow } from "./store.ts";export const FILM = "film";export const SEASON = "film_season";export const EPISODE = "film_episode";export const WATCH = "watch";/** The tables the Cinemas shape lays whole, in this order. */export const FAMILY = [FILM, SEASON, EPISODE, WATCH] as const;export const CINEMAS_TOOL = "cinemas";/** The tool Cinemas replaced: removed by reshape_films. */export const OLD_TOOL = "films";export const TMDB_API = "https://api.themoviedb.org/3";export const TMDB_IMAGES = "https://image.tmdb.org/t/p";/** The most pictures one find_film fetches: a long series' stills beyond it wait for the next Find details, which fills only what is empty. */export const PICTURES_PER_ACT = 60;/** Where a lookup's fills came from, in `filled_from`. */const TMDB = "tmdb";type Doc = Record<string, unknown>;const blank = (v: unknown): boolean => v === undefined || v === null || (typeof v === "string" && v.trim() === "");const textOf = (v: unknown): string => (typeof v === "string" ? v.trim() : "");const yearOf = (v: unknown): string => (/^(\d{4})-/.exec(textOf(v))?.[1] ?? "");const dayOf = (v: unknown): string => (/^\d{4}-\d{2}-\d{2}$/.test(textOf(v)) ? textOf(v) : "");const positive = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.round(v) : null);const list = (v: unknown): Doc[] => (Array.isArray(v) ? (v as unknown[]).filter((x): x is Doc => !!x && typeof x === "object") : []);/** An id TMDB gives as a number or a string, as a row's text holds it. */const idText = (v: unknown): string => (typeof v === "number" && Number.isInteger(v) && v > 0 ? String(v) : textOf(v));const names = (v: unknown, max = Infinity): string => list(v).map((x) => textOf(x.name)).filter(Boolean).slice(0, max).join(", ");function live(store: Store, table: string, id: unknown, said: string): StoredRow {  if (typeof id !== "string" || !id.trim()) refuse(400, "bad_args", `name the ${said}: its id`);  const row = store.get(table, id.trim());  if (!row || row.deleted) refuse(404, "no_such_record", `no ${said} with id ${id}`);  return row;}// ── find_film: asking TMDB ───────────────────────────────────────────────/** * One TMDB read (v3, the key as its `api_key` parameter), or a refusal: 403 * and 429 are TMDB asked too often, no answer at all is a lookup that * failed. Null when TMDB knows no such thing (404). The URL carries the key, * so no message or log line here ever says it, nor an error that might. */async function tmdb(fetcher: Fetcher, key: string, path: string, params: Record<string, string> = {}): Promise<Doc | null> {  const query = new URLSearchParams(params);  query.set("api_key", key);  let res: Response;  try {    res = await fetcher(`${TMDB_API}${path}?${query}`, { headers: { "user-agent": USER_AGENT, accept: "application/json" } });  } catch {    console.error(`cottondb: find_film: TMDB did not answer ${path}`);    refuse(502, "lookup_failed", "TMDB did not answer; try again later");  }  if (res.status === 403 || res.status === 429) refuse(503, "lookup_failed", `TMDB refused the lookup (${res.status}): asked too often; try again later`);  if (res.status === 401) refuse(503, "lookup_failed", "TMDB turned this server's key away (401): the server's TMDB key needs renewing");  if (res.status === 404) return null;  if (!res.ok) refuse(502, "lookup_failed", `TMDB answered ${res.status}; try again later`);  const answer: unknown = await res.json().catch(() => null);  if (!answer || typeof answer !== "object" || Array.isArray(answer)) refuse(502, "lookup_failed", "TMDB answered with no JSON; try again later");  return answer as Doc;}type Kind = "film" | "series";const pathOf = (kind: Kind): "movie" | "tv" => (kind === "film" ? "movie" : "tv");/** A query's title and the year it ends in, if it does: `Night Ferry (2019)` or `Night Ferry 2019`. */export function queryOf(query: string): { title: string; year: string | null } {  const m = /^(.*\S)\s+\(?((?:19|20)\d{2})\)?$/.exec(query.trim());  return m ? { title: m[1]!, year: m[2]! } : { title: query.trim(), year: null };}/** TMDB's best match for a title: a film or a series (or only `kind`), the one of `year` when one is; null when it knows none. */async function search(fetcher: Fetcher, key: string, title: string, year: string | null, kind: Kind | null): Promise<{ kind: Kind; id: string } | null> {  const params: Record<string, string> = { query: title, include_adult: "false" };  if (kind === "film" && year) params.year = year;  if (kind === "series" && year) params.first_air_date_year = year;  const answer = await tmdb(fetcher, key, kind ? `/search/${pathOf(kind)}` : "/search/multi", params);  const results = list(answer?.results)    .map((r) => ({ kind: (kind ?? (r.media_type === "movie" ? "film" : r.media_type === "tv" ? "series" : null)) as Kind | null, id: r.id, year: yearOf(r.release_date ?? r.first_air_date) }))    .filter((r): r is { kind: Kind; id: number; year: string } => r.kind !== null && typeof r.id === "number");  const best = (year && results.find((r) => r.year === year)) || results[0];  return best ? { kind: best.kind, id: String(best.id) } : null;}/** The first certificate a country gives, India's then the United States'. */function certificate(kind: Kind, details: Doc): string {  for (const country of ["IN", "US"]) {    if (kind === "film") {      const dates = list((details.release_dates as Doc | undefined)?.results).find((r) => r.iso_3166_1 === country);      const given = list(dates?.release_dates).map((d) => textOf(d.certification)).find(Boolean);      if (given) return given;    } else {      const rating = list((details.content_ratings as Doc | undefined)?.results).find((r) => r.iso_3166_1 === country);      if (textOf(rating?.rating)) return textOf(rating?.rating);    }  }  return "";}/** What TMDB says of a film or a series, in the film table's columns; empty ones left out. */function filmColumns(kind: Kind, details: Doc): Data {  const credits = (details.credits as Doc | undefined) ?? {};  const original = textOf(details.original_language);  const spoken = list(details.spoken_languages).find((l) => l.iso_639_1 === original);  const countries = names(details.production_countries) || (Array.isArray(details.origin_country) ? (details.origin_country as unknown[]).filter((c) => typeof c === "string").join(", ") : "");  const runtime = kind === "film" ? positive(details.runtime) : positive(Array.isArray(details.episode_run_time) ? details.episode_run_time[0] : null);  const columns: Data = {    title: textOf(kind === "film" ? details.title : details.name),    year: yearOf(kind === "film" ? details.release_date : details.first_air_date),    synopsis: textOf(details.overview),    genres: names(details.genres),    certificate: certificate(kind, details),    language: textOf(spoken?.english_name) || original,    country: countries,    cast: names(credits.cast, 5),    director: kind === "film" ? names(list(credits.crew).filter((c) => c.job === "Director")) : names(details.created_by),    imdb_id: textOf((details.external_ids as Doc | undefined)?.imdb_id) || textOf(details.imdb_id),    tvdb_id: idText((details.external_ids as Doc | undefined)?.tvdb_id),    tmdb_id: String(details.id),    minutes: runtime,  };  return Object.fromEntries(Object.entries(columns).filter(([, v]) => !blank(v)));}/** A picture's address on TMDB's image host, at the width the phone draws it. */const imageUrl = (path: unknown, width: string): string | null => (textOf(path).startsWith("/") ? `${TMDB_IMAGES}/${width}${textOf(path)}` : null);export interface FoundEpisode {  number: number;  columns: Data;  still: string | null;}export interface FoundSeason {  number: number;  columns: Data;  poster: string | null;  episodes: FoundEpisode[];}/** find_film's lookup, ready to write: the pictures already kept (media keys), only those an empty column wants. */export interface PreparedFilm {  /** The film row the act named; null for a query. */  film: string | null;  kind: Kind;  columns: Data;  /** `poster` and `backdrop`, as media keys. */  pictures: Data;  seasons: FoundSeason[];  /** Pictures left unfetched past PICTURES_PER_ACT: the next Find details fetches them. */  more: boolean;}/** * `find_film`'s lookup, before its write: the match or the named row's * details, a series' seasons and episodes, and every picture an empty column * wants, kept once. A picture that could not be fetched is left empty. */export async function prepareFind(host: Pick<ArtworkHost, "store" | "databaseId" | "keep">, args: Record<string, unknown>, fetcher: Fetcher, key: string | undefined): Promise<PreparedFilm> {  const query = typeof args.query === "string" ? args.query.trim() : "";  const named = args.film;  if (!!query === (named !== undefined)) refuse(400, "bad_args", "find_film takes a query (the film's or the series' name, its year too if you like) or a film (a film row's id), not both");  if (!key) refuse(404, "not_connected", "TMDB is not connected on this server: Find a film looks films up on TMDB, and this server holds no TMDB key");  const row = named !== undefined ? live(host.store, FILM, named, "film") : null;  let match: { kind: Kind; id: string } | null;  if (row) {    const kind: Kind = row.data.kind === "series" ? "series" : "film";    // A sealed film's words are not the object's to read: the phone hands them over for this one look (crates/cotton-ffi object_acts.rs `film_asked`).    const sealed = isSealedRow(row.data);    const said = (column: string): string => (sealed ? (typeof args[column] === "string" ? String(args[column]).trim() : "") : textOf(row.data[column]));    const held = said("tmdb_id");    const title = said("title");    if (!held && !title) refuse(400, "bad_args", "this film has no title to look up; give it one first");    match = held ? { kind, id: held } : await search(fetcher, key, title, said("year") || null, kind);  } else {    const asked = queryOf(query);    match = await search(fetcher, key, asked.title, asked.year, null);  }  const said = row ? `“${(isSealedRow(row.data) ? textOf(args.title) : textOf(row.data.title)) || row.id}”` : `“${query}”`;  if (!match) refuse(404, "no_film_found", `TMDB knows no film or series for ${said}`);  const append = match.kind === "film" ? "release_dates,credits,external_ids" : "content_ratings,credits,external_ids";  const details = await tmdb(fetcher, key, `/${pathOf(match.kind)}/${encodeURIComponent(match.id)}`, { append_to_response: append });  if (!details) refuse(404, "no_film_found", `TMDB knows no film or series for ${said}`);  const columns = filmColumns(match.kind, details);  // The row this lookup lands on, as it stands now: the named one, else the one holding this TMDB id.  const target = row ?? heldByTmdb(host.store, match.kind, String(details.id));  let left = PICTURES_PER_ACT;  let more = false;  const keep = async (url: string | null, wanted: boolean): Promise<string | null> => {    if (!url || !wanted) return null;    if (left <= 0) {      more = true;      return null;    }    left--;    try {      return await picture(host, url, fetcher);    } catch (error) {      console.error(`cottondb: find_film: a picture was not kept (${error instanceof Error ? error.message : String(error)})`);      return null;    }  };  const pictures: Data = {};  const poster = await keep(imageUrl(details.poster_path, "w780"), !target || blank(target.data.poster));  if (poster) pictures.poster = poster;  const backdrop = await keep(imageUrl(details.backdrop_path, "w1280"), !target || blank(target.data.backdrop));  if (backdrop) pictures.backdrop = backdrop;  const seasons: FoundSeason[] = [];  if (match.kind === "series") {    const heldSeasons = target ? host.store.list(SEASON, { column: "film", equals: target.id }) : [];    // Season 0 is TMDB's Specials: no season of the series' own.    for (const s of list(details.seasons).filter((s) => typeof s.season_number === "number" && s.season_number >= 1)) {      const number = s.season_number as number;      const season = await tmdb(fetcher, key, `/tv/${encodeURIComponent(match.id)}/season/${number}`);      if (!season) continue;      const heldSeason = heldSeasons.find((h) => h.data.number === number);      const heldEpisodes = heldSeason ? host.store.list(EPISODE, { column: "season", equals: heldSeason.id }) : [];      const episodes: FoundEpisode[] = [];      for (const e of list(season.episodes).filter((e) => typeof e.episode_number === "number")) {        const heldEpisode = heldEpisodes.find((h) => h.data.number === e.episode_number);        const episodeColumns: Data = { title: textOf(e.name), synopsis: textOf(e.overview), minutes: positive(e.runtime), aired: dayOf(e.air_date), tmdb_id: typeof e.id === "number" ? String(e.id) : "" };        episodes.push({          number: e.episode_number as number,          columns: Object.fromEntries(Object.entries(episodeColumns).filter(([, v]) => !blank(v))),          still: await keep(imageUrl(e.still_path, "w780"), !heldEpisode || blank(heldEpisode.data.still)),        });      }      const seasonColumns: Data = { title: textOf(season.name ?? s.name), year: yearOf(season.air_date ?? s.air_date), tmdb_id: typeof (season.id ?? s.id) === "number" ? String(season.id ?? s.id) : "" };      seasons.push({        number,        columns: Object.fromEntries(Object.entries(seasonColumns).filter(([, v]) => !blank(v))),        poster: await keep(imageUrl(season.poster_path ?? s.poster_path, "w780"), !heldSeason || blank(heldSeason.data.poster)),        episodes,      });    }  }  return { film: row?.id ?? null, kind: match.kind, columns, pictures, seasons, more };}/** The live film holding a TMDB id of this kind, if one does. *//** The id a film found on TMDB is made under: the same work finds it again without reading a sealed column. */function tmdbFilmId(kind: Kind, id: string): string {  return derivedId(FILM, ["tmdb", kind, id]);}function heldByTmdb(store: Store, kind: Kind, id: string): StoredRow | null {  const derived = id ? store.get(FILM, tmdbFilmId(kind, id)) : null;  if (derived && !derived.deleted) return derived;  return store.list(FILM, { column: "tmdb_id", equals: id }).find((r) => (r.data.kind === "series" ? "series" : "film") === kind) ?? null;}/** A change of found details: on a sealed row, a fill patch the phone lays only where the row is empty (src/arrival_seam.ts). */function fillFound(engine: Engine, row: StoredRow, patch: Data, version: number, outcome: Outcome): StoredRow {  const write = () => engine.update(row, patch, version, outcome);  return isSealedRow(row.data) ? filling(engine, write) : write();}/** Of `found`, what an empty column of `row` takes. */function emptyOf(row: StoredRow, found: Data): Data {  return Object.fromEntries(Object.entries(found).filter(([k]) => blank(row.data[k])));}export interface FilmFound {  film: string;  made: boolean;  filled: string[];  seasons: { made: number; filled: number };  episodes: { made: number; filled: number };  more?: true;}/** * `find_film`'s write: a query's film made (Want to watch, added today) or * the film found again filled; a named film filled. Only empty columns are * filled, each said in `filled_from`; a series' seasons and episodes made or * filled the same way. */export function applyFind(engine: Engine, prepared: PreparedFilm, today: string, version: number, outcome: Outcome): FilmFound {  const found: Data = { ...prepared.columns, ...prepared.pictures };  const tmdbId = textOf(prepared.columns.tmdb_id);  let row = prepared.film ? live(engine.store, FILM, prepared.film, "film") : heldByTmdb(engine.store, prepared.kind, tmdbId);  let made = false;  let filled: string[];  if (!row) {    const from = Object.fromEntries(Object.keys(found).map((k) => [k, TMDB]));    row = engine.create(FILM, { ...found, kind: prepared.kind, status: "want_to_watch", added_on: today, filled_from: JSON.stringify(from) }, version, outcome, 0, tmdbId ? { id: tmdbFilmId(prepared.kind, tmdbId) } : {});    outcome.made = row;    made = true;    filled = Object.keys(found);  } else {    const patch = emptyOf(row, found);    filled = Object.keys(patch);    if (filled.length) {      patch.filled_from = filledFrom(row.data.filled_from, Object.fromEntries(filled.map((k) => [k, TMDB])));      row = fillFound(engine, row, patch, version, outcome);    }  }  const seasons = { made: 0, filled: 0 };  const episodes = { made: 0, filled: 0 };  const film = row.id;  const heldSeasons = engine.store.list(SEASON, { column: "film", equals: film });  for (const s of prepared.kind === "series" ? prepared.seasons : []) {    const seasonFound: Data = { ...s.columns, ...(s.poster ? { poster: s.poster } : {}) };    let season = heldSeasons.find((h) => h.data.number === s.number) ?? null;    if (!season) {      season = engine.create(SEASON, { film, number: s.number, ...seasonFound }, version, outcome);      seasons.made++;    } else {      const patch = emptyOf(season, seasonFound);      if (Object.keys(patch).length) {        season = fillFound(engine, season, patch, version, outcome);        seasons.filled++;      }    }    const heldEpisodes = engine.store.list(EPISODE, { column: "season", equals: season.id });    for (const e of s.episodes) {      const episodeFound: Data = { ...e.columns, ...(e.still ? { still: e.still } : {}) };      const episode = heldEpisodes.find((h) => h.data.number === e.number);      if (!episode) {        engine.create(EPISODE, { season: season.id, series: film, number: e.number, ...episodeFound }, version, outcome);        episodes.made++;        continue;      }      const patch = emptyOf(episode, episodeFound);      if (Object.keys(patch).length) {        fillFound(engine, episode, patch, version, outcome);        episodes.filled++;      }    }  }  return { film, made, filled, seasons, episodes, ...(prepared.more ? { more: true as const } : {}) };}// ── reshape_films ────────────────────────────────────────────────────────export interface Reshaped {  /** Rows whose value moved: status watchlist → want_to_watch, notes copied into an empty review, added_on stamped. */  mapped: { status: number; review: number; added_on: number };  laid: string[];  removed: string[];}const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);const columnKeys = (t: Doc | undefined): string[] => (Array.isArray(t?.columns) ? (t.columns as Doc[]).map((c) => String(c.key)) : []);/** * `reshape_films`, in the act's transaction: the owner's one-time move of the * film family onto the Cinemas shape, keeping every row. A kit keep is * add-only (src/kit_keep.ts), so an object whose film table holds rows keeps * the old film's `notes` and `watchlist` beside the new columns; this lays * the kit's film, film_season, film_episode and watch whole, removes the held * Films tool and lays the kit's Cinemas tool. On the old shape (its film * still names `notes` as a column) each film row is carried over: status * `watchlist` becomes `want_to_watch` (`watched` stays), `notes` is copied * into an empty `review` (notes stays stored, retired), and an empty * `added_on` is the day the row was made. Run again it finds nothing to do * and answers zeros. `fresh` is an engine over the definitions as laid; the * caller relinks. */export function reshapeFilms(store: Store, kit: { tables: Doc[]; tools: Doc[] }, fresh: () => Engine, made: (createdAt: string) => string, version: number, outcome: Outcome): Reshaped {  const held = store.definitions("table");  const heldFilm = held.find((t) => t.id === FILM);  if (!heldFilm) refuse(404, "no_films", "this database has no film table");  const oldShape = columnKeys(heldFilm).includes("notes");  const kitTable = (id: string): Doc => {    const doc = kit.tables.find((t) => t.id === id);    if (!doc) throw new Error(`the kit ships no ${id} table`);    return doc;  };  const laid: string[] = [];  const tables = held.map((t) => {    const id = String(t.id);    if (!(FAMILY as readonly string[]).includes(id)) return t;    const doc = kitTable(id);    if (same(doc, t)) return t;    laid.push(id);    return doc;  });  for (const id of FAMILY) {    if (held.some((t) => t.id === id)) continue;    tables.push(kitTable(id));    laid.push(id);  }  if (laid.length) store.replaceDefinitions("table", tables);  const tool = kit.tools.find((t) => t.id === CINEMAS_TOOL);  if (!tool) throw new Error("the kit ships no cinemas tool");  const tools = store.definitions("tool");  const removed = tools.some((t) => t.id === OLD_TOOL) ? [OLD_TOOL] : [];  const heldTool = tools.find((t) => t.id === CINEMAS_TOOL);  if (removed.length || !same(heldTool, tool)) {    store.replaceDefinitions("tool", [...tools.filter((t) => t.id !== OLD_TOOL && t.id !== CINEMAS_TOOL), tool]);    if (!same(heldTool, tool)) laid.push(CINEMAS_TOOL);  }  const mapped = { status: 0, review: 0, added_on: 0 };  const engine = fresh();  for (const row of [...store.scan(FILM)]) {    const patch: Data = {};    if (row.data.status === "watchlist") {      patch.status = "want_to_watch";      mapped.status++;    }    if (oldShape && !blank(row.data.notes) && blank(row.data.review)) {      patch.review = row.data.notes;      mapped.review++;    }    if (oldShape && blank(row.data.added_on)) {      patch.added_on = made(row.created_at);      mapped.added_on++;    }    if (Object.keys(patch).length) engine.update(row, patch, version, outcome);  }  return { mapped, laid: [...FAMILY, CINEMAS_TOOL].filter((id) => laid.includes(id)), removed };}// ── what waits for the Mac ───────────────────────────────────────────────export interface PendingFilm {  table: typeof FILM | typeof EPISODE;  id: string;  title: string;  source_file: string | null;  series?: string;  series_title?: string;  season_number?: number;  number?: number;}/** * `GET /v1/films/pending`: every film and episode an upload waits on the Mac * for — needs_mac true and no stream yet — oldest first: the Mac importer * fetches each one's source_file, converts it and says film_converted. */export function pending(store: Store, defines: (table: string) => boolean): PendingFilm[] {  const waiting = [{ sql: `json_extract(data, '$."needs_mac"') = 1 AND COALESCE(json_extract(data, '$."file"'), '') = ''`, args: [] }];  const out: PendingFilm[] = [];  if (defines(FILM)) {    for (const row of store.scan(FILM, waiting)) out.push({ table: FILM, id: row.id, title: textOf(row.data.title), source_file: textOf(row.data.source_file) || null });  }  if (defines(EPISODE)) {    for (const row of store.scan(EPISODE, waiting)) {      const series = typeof row.data.series === "string" ? store.get(FILM, row.data.series) : null;      const season = typeof row.data.season === "string" ? store.get(SEASON, row.data.season) : null;      out.push({        table: EPISODE,        id: row.id,        title: textOf(row.data.title),        source_file: textOf(row.data.source_file) || null,        ...(series ? { series: series.id, series_title: textOf(series.data.title) } : {}),        ...(typeof season?.data.number === "number" ? { season_number: season.data.number } : {}),        ...(typeof row.data.number === "number" ? { number: row.data.number } : {}),      });    }  }  return out;}/** One ask for subtitles: which row, and what was asked. Ids and the ask only, never a title. */export interface SubtitleAsk {  table: typeof FILM | typeof EPISODE;  id: string;  /** `file`: the owner gave a subtitle file on the phone (Give subtitles), kept sealed as the row's `subtitle_given`. */  ask: "find" | "generate" | "file";  asked_at: string;  /** The row's version: the Mac opens it alone by reading the table from just before it (`seal-files row --since`). */  version: number;}/** * `GET /v1/films/subtitles/asked`: every film and episode whose * `subtitle_work` the phone set to `find` (Find subtitles) or `generate` * (Make subtitles) or `file` (Give subtitles: a file the owner picked, which * the Mac lays, SUBTITLE FILE 25 Nov 2026), the longest waiting first. `subtitle_work` is a clear * column of both sealed tables, so this is one read of what the object * already holds in the clear; the Mac then opens only the rows named * (17 Nov 2026: an ask waited 10 to 20 minutes while * `film:subtitles --queue` opened both whole tables to find it). */export function subtitlesAsked(store: Store, defines: (table: string) => boolean, now: Date = new Date()): SubtitleAsk[] {  const asked = [{ sql: `json_extract(data, '$."subtitle_work"') IN ('find', 'generate', 'file')`, args: [] }];  // A run that died where it stood (the Mac switched off mid-way) leaves its row finding, generating or translating,  // and the phone offers no ask while it does: once quiet STALE_RUN_HOURS it is listed again as the ask it ran  // (FILMS TRUE, 25 Nov 2026). A run still going writes its progress far more often than that.  const quiet = new Date(now.getTime() - STALE_RUN_HOURS * 3600_000).toISOString();  const stale = [{ sql: `json_extract(data, '$."subtitle_work"') IN ('finding', 'generating', 'translating') AND updated_at < ?`, args: [quiet] }];  const out: SubtitleAsk[] = [];  for (const table of [FILM, EPISODE] as const) {    if (!defines(table)) continue;    for (const row of store.scan(table, asked)) out.push({ table, id: row.id, ask: row.data.subtitle_work === "generate" ? "generate" : row.data.subtitle_work === "file" ? "file" : "find", asked_at: row.updated_at, version: row.version });    for (const row of store.scan(table, stale)) out.push({ table, id: row.id, ask: staleAsk(row.data), asked_at: row.updated_at, version: row.version });  }  return out.sort((a, b) => (a.asked_at < b.asked_at ? -1 : a.asked_at > b.asked_at ? 1 : 0));}/** How long a running subtitle ask may stand without a change before it is listed again (the subtitle run's STALE_HOURS). */export const STALE_RUN_HOURS = 6;/** The ask a run that died was running: finding was a find; generating a make; translating a make, or the owner's own file when the row was given one. */function staleAsk(data: Data): SubtitleAsk["ask"] {  if (data.subtitle_work === "finding") return "find";  if (data.subtitle_work === "translating" && typeof data.subtitle_given === "string" && data.subtitle_given !== "") return "file";  return "generate";}/** A film or episode as `GET /v1/films/find` answers it: its id, its version and the clear columns it plays from; never a title. */export interface FoundFilm {  table: typeof FILM | typeof EPISODE;  id: string;  /** The row's version: the Mac opens it alone by reading the table from just before it (`seal-files row --since`). */  version: number;  kind: string | null;  file: string | null;  /** The kept original's key, when the row keeps one in the clear. */  original: string | null;}/** At most this many rows answer a prefix: enough to say it names more than one. */export const FIND_MOST = 10;/** * `GET /v1/films/find?id=<id or prefix>`: the live film or episode whose id is * `id`, else every one whose id starts with it (at most FIND_MOST, by id), with * the clear columns `pnpm film:open` plays it from. Both film tables are * sealed but their file, kind and original are clear, so this is one * indexed read of what the object holds in the clear, never a title; the Mac * opens only the row it names (owner, 17 Nov 2026: `withFile` opened the whole * sealed table, 6.5 minutes, to find one film). */export function findFilm(store: Store, defines: (table: string) => boolean, id: string): FoundFilm[] {  const found = (table: typeof FILM | typeof EPISODE, row: StoredRow): FoundFilm => ({    table,    id: row.id,    version: row.version,    kind: typeof row.data.kind === "string" ? row.data.kind : table === EPISODE ? "episode" : null,    file: textOf(row.data.file) || null,    original: textOf(row.data.original) || null,  });  const tables = ([FILM, EPISODE] as const).filter(defines);  for (const table of tables) {    const row = store.get(table, id);    if (row && !row.deleted) return [found(table, row)];  }  const out: FoundFilm[] = [];  for (const table of tables) {    for (const row of store.select(table, [{ sql: "id >= ? AND id < ?", args: [id, `${id}\uffff`] }], "id", FIND_MOST)) out.push(found(table, row));  }  return out.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).slice(0, FIND_MOST);}// ── film_converted ───────────────────────────────────────────────────────/** A stream the Mac or the phone lays in a film's folder: the HLS master, or a whole file the phone plays as it is. */const STREAM_FILE = /^(master\.m3u8|whole\.(mp4|m4v|mov))$/;/** An upload waiting for the Mac, in whichever folder of `films/` it was laid. */const SOURCE_FILE = /^[^/]+\/films\/[^/]+\/source\.[a-z0-9]+$/;export interface Converted {  table: string;  id: string;  /** The film's or episode's folder, `<database id>/films/<id>/`. */  folder: string;  /** Every film's folder of this database, `<database id>/films/`. */  databaseFilms: string;  file: string;  poster: string | null;}/** film_converted's arguments, checked: a film or an episode, its stream and its poster in its own folder. */export function convertedArgs(store: Store, args: Record<string, unknown>, databaseId: string): Converted {  const table = text(args.table, "table");  if (table !== FILM && table !== EPISODE) refuse(400, "bad_args", "film_converted names a film or a film_episode row");  const row = live(store, table, args.id, table === FILM ? "film" : "episode");  const folder = `${databaseId}/films/${row.id}/`;  const file = text(args.file, "file");  if (!file.startsWith(folder) || !STREAM_FILE.test(file.slice(folder.length))) refuse(400, "bad_file", `the stream is ${folder}master.m3u8 or ${folder}whole.<mp4|m4v|mov>`);  const poster = args.poster === undefined || args.poster === null ? null : text(args.poster, "poster");  if (poster !== null && (!poster.startsWith(folder) || poster.slice(folder.length).includes("/"))) refuse(400, "bad_file", `the poster is a file in ${folder}`);  return { table, id: row.id, folder, databaseFilms: `${databaseId}/films/`, file, poster };}/** * `film_converted`'s write: the stream becomes the row's file, it no longer * waits for the Mac, its upload is no longer held, and an empty poster (an * episode's still) takes the converted one. The upload's object goes from R2 * once the write commits (src/business.ts `dropMedia`), only when it is an * upload's key of this database (`<db>/films/<folder>/source.<ext>`: the * phone may lay one in a fresh folder, never the record's id) and not the * stream itself. */export function filmConverted(engine: Engine, converted: Converted, version: number, outcome: Outcome): { table: string; id: string; file: string; dropped: string | null } {  const row = live(engine.store, converted.table, converted.id, converted.table === FILM ? "film" : "episode");  const source = textOf(row.data.source_file);  const patch: Data = { file: converted.file, needs_mac: false, source_file: null };  const pictured = converted.table === FILM ? "poster" : "still";  if (converted.poster && blank(row.data[pictured])) patch[pictured] = converted.poster;  engine.update(row, patch, version, outcome);  const dropped = SOURCE_FILE.test(source) && source.startsWith(converted.databaseFilms) && source !== converted.file ? source : null;  if (dropped) engine.store.dropMediaLater(dropped);  return { table: row.table, id: row.id, file: converted.file, dropped };}