Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit e25b68a7e7dc0a21e7d012b11c05daf3de47f0b4
parent ee2f8413b1cfab0df7447876a89bdb79a1ca842e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 06:23:26 -0500

ops: the Local media page's twins -- local-media-configure, -preview, -prepare, -import, -link

Review should-fix (no pnpm ops / CLI twin). Five routes under /api/ops, each
the page's control over the same controller: configure (initial opt-in through
patchChannelConfig, playback never set), preview (writes nothing), prepare
(details for a recording with no .info.json, writes nothing), import (the
import-local-media job; "allNew": true takes a fresh preview and selects every
new candidate) and link (verify-and-link, with a dry run). Usage paragraphs and
examples in scripts/archilyzer-ops.mjs; COMMANDS.md regenerated (--check
clean). A route test drives all five over a temp corpus and a synthetic
library, the library left untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 5+++++
Aeditor/app/api/ops/local-media-configure/route.ts | 26++++++++++++++++++++++++++
Aeditor/app/api/ops/local-media-import/route.test.ts | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/local-media-import/route.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/local-media-link/route.ts | 30++++++++++++++++++++++++++++++
Aeditor/app/api/ops/local-media-prepare/route.ts | 40++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/local-media-preview/route.ts | 25+++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.test.mjs | 14++++++++++++++
9 files changed, 391 insertions(+), 0 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -143,6 +143,11 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(&lt;id&gt;)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` | | `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.&lt;fmt&gt;, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` | | `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/&lt;channel&gt;" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'` | +| `local-media-configure` | local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {"slug", "sourceId", "directory"} — a stable lowercase id and an absolute directory on the editor server whose recordings stay where they are (never copied, moved or deleted). Written through the channel config; a channel that already has one is refused, and so is queued or running channel work. Playback is not set. Synchronous. | `pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'` | +| `local-media-preview` | local-media-preview scans the library and writes nothing: {"slug"} -&gt; {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the directory (not its subdirectories) with its same-named .info.json and .vtt (or .srt) is "new", "existing" (its record is held) or "issue" (with issues). The sourceToken and a candidate's fingerprint (or preparationFingerprint, when it has no .info.json) are what the other local-media actions take. An unreachable library is an error, never an empty preview. | `pnpm ops local-media-preview --json '{"slug":"demo-local"}'` | +| `local-media-prepare` | local-media-prepare reviews details for a recording with no .info.json and writes nothing: {"slug", "sourceToken", "media", "sourceFingerprint" (the candidate's preparationFingerprint), "details": {"mode": "inspect" \| "manual", "title", "recordedDate"? (YYYY-MM-DD), "durationSeconds"? (manual)}} -&gt; {review: {metadata, fingerprint}}. "inspect" measures the duration with ffprobe. Import it with local-media-import, the review's fingerprint and "preparation": {"sourceFingerprint", "details"}. | `pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'` | +| `local-media-import` | local-media-import imports library recordings as one job on the channel's queue: {"slug", "sourceToken", "selected": \[{"media", "fingerprint", "preparation"?}\]} from a preview, or {"slug", "allNew": true} for every "new" candidate of a fresh preview. Each record gets metadata.info.json, transcript.en.vtt and external-media.json; the video stays in the library. Every selection is re-checked first (a changed file is stale; a held record is left unchanged). Drainable between recordings; searchable after the next index build. | `pnpm ops local-media-import --json '{"slug":"demo-local","allNew":true}' --wait` | +| `local-media-link` | local-media-link links a record the channel already holds to its library original: {"slug", "sourceToken", "media", "fingerprint", "dryRun"?} for an "existing" candidate. Only when the library's .info.json and transcript match the record's byte for byte is external-media.json written ("attached"; "already-linked"; "conflict" keeps a different one). Nothing else changes, and no playback is granted. "dryRun" answers "ready" without writing. | `pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}'` | | `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, &lt;id&gt;-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/&lt;id&gt;/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` | | `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (&lt;id&gt;-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` | | `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | | diff --git a/editor/app/api/ops/local-media-configure/route.ts b/editor/app/api/ops/local-media-configure/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { configureLocalMedia } from "yt-dlp-transcript-common/controller/configureLocalMedia"; +import { ops, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, sourceId, directory } -> { ok: true, localMedia } +// +// A LOCAL MEDIA LIBRARY for a video channel (controller/configureLocalMedia.ts; +// the Local media page's Save library): `localMedia` = {sourceId, directory} +// written through patchChannelConfig, the channel config lock and the schema. +// Initial opt-in only — a channel that already has a library is refused (the +// same names could identify different recordings), as are a social channel, +// queued or running channel work, a relocation, a directory that does not +// exist or overlaps the channel. Playback is never set here. Nothing is +// scanned or imported. Synchronous; no job. +export async function POST(request: Request) { + return ops(request, ["slug", "sourceId", "directory"], async (body) => { + const localMedia = await configureLocalMedia(getPaths(), reqSlug(body, "slug"), { + sourceId: reqString(body, "sourceId"), + directory: reqString(body, "directory"), + }); + return NextResponse.json({ ok: true, localMedia }); + }); +} diff --git a/editor/app/api/ops/local-media-import/route.test.ts b/editor/app/api/ops/local-media-import/route.test.ts @@ -0,0 +1,144 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/local-media-import/route.test.ts" +// +// The Local media page's five ops twins, end to end over a temp corpus and a +// synthetic library: configure, preview (writes nothing), prepare (writes +// nothing), import (one job), and link (dry run, then apply). The library's +// files are never changed. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "local-media-ops-")); +// Set before the routes (and getPaths, which caches) are first imported. +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +const routes = { + "local-media-configure": (await import("../local-media-configure/route")).POST, + "local-media-preview": (await import("../local-media-preview/route")).POST, + "local-media-prepare": (await import("../local-media-prepare/route")).POST, + "local-media-import": (await import("./route")).POST, + "local-media-link": (await import("../local-media-link/route")).POST, +}; +const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const CH = path.join(ROOT, "transcripts", "channels"); +const LIB = path.join(ROOT, "library"); +const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nA library cue\n"; +const info = (id: string) => JSON.stringify({ + id, title: `Title ${id}`, webpage_url: `https://www.youtube.com/watch?v=${id}`, + upload_date: "20200102", duration: 12, extractor_key: "Youtube", +}); +await mkdir(path.join(CH, "lib"), { recursive: true }); +await writeFile(path.join(CH, "lib", "config.json"), JSON.stringify({ handling: "youtube", name: "lib" })); +await mkdir(LIB, { recursive: true }); +for (const id of ["aaaaaaaaaaa", "bbbbbbbbbbb"]) { + await writeFile(path.join(LIB, `${id}.mp4`), `mp4 ${id}`); + await writeFile(path.join(LIB, `${id}.info.json`), info(id)); + await writeFile(path.join(LIB, `${id}.vtt`), VTT); +} +// No .info.json: a recording for Prepare details. +await writeFile(path.join(LIB, "talk.mp4"), "mp4 talk"); +await writeFile(path.join(LIB, "talk.vtt"), VTT); +// Held already, with the library's exact bytes: for Verify and link. +await mkdir(path.join(CH, "lib", "data", "bbbbbbbbbbb"), { recursive: true }); +await writeFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "metadata.info.json"), info("bbbbbbbbbbb")); +await writeFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "transcript.en.vtt"), VTT); + +type Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any +async function post(action: keyof typeof routes, body: Record<string, unknown>): Promise<{ status: number; json: Json }> { + const res = await routes[action]( + new Request(`http://localhost/api/ops/${action}`, { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Json }; +} +async function waitJob(id: string): Promise<string | undefined> { + for (let i = 0; i < 200; i++) { + const status = getRegistry().get(id)?.status; + if (status === "done" || status === "failed") return status; + await new Promise((res) => setTimeout(res, 50)); + } + return getRegistry().get(id)?.status; +} + +test("refusals: unknown keys, a missing slug, no library yet, a bad directory", async () => { + assert.match((await post("local-media-preview", { slug: "lib", force: true })).json.error, /unknown key\(s\): force/); + assert.match((await post("local-media-configure", { sourceId: "x", directory: LIB })).json.error, /"slug" is required/); + assert.match((await post("local-media-preview", { slug: "lib" })).json.error, /no valid local media source/); + assert.match((await post("local-media-import", { slug: "lib", allNew: true })).json.error, /no valid local media source/); + const rel = await post("local-media-configure", { slug: "lib", sourceId: "library-1", directory: "relative" }); + assert.equal(rel.json.ok, false); + assert.equal(JSON.parse(await readFile(path.join(CH, "lib", "config.json"), "utf8")).localMedia, undefined); +}); + +test("configure, preview, prepare, import and link, the library untouched", async () => { + const before = (await readdir(LIB)).sort(); + const configured = await post("local-media-configure", { slug: "lib", sourceId: "library-1", directory: LIB }); + assert.equal(configured.status, 200, JSON.stringify(configured.json)); + assert.deepEqual(configured.json.localMedia, { sourceId: "library-1", directory: LIB }); + assert.match((await post("local-media-configure", { slug: "lib", sourceId: "library-2", directory: LIB })).json.error, /already has a library/); + + const previewed = await post("local-media-preview", { slug: "lib" }); + assert.equal(previewed.status, 200, JSON.stringify(previewed.json)); + const { preview } = previewed.json; + assert.deepEqual(preview.counts, { discovered: 3, new: 1, existing: 1, issues: 1 }); + const byMedia = Object.fromEntries(preview.candidates.map((c: Json) => [c.media, c])); + assert.equal(byMedia["aaaaaaaaaaa.mp4"].status, "new"); + assert.equal(byMedia["bbbbbbbbbbb.mp4"].status, "existing"); + assert.ok(byMedia["talk.mp4"].preparationFingerprint); + assert.deepEqual(await readdir(path.join(CH, "lib", "data")), ["bbbbbbbbbbb"]); + + const prepared = await post("local-media-prepare", { + slug: "lib", sourceToken: preview.sourceToken, media: "talk.mp4", + sourceFingerprint: byMedia["talk.mp4"].preparationFingerprint, + details: { mode: "manual", title: "A talk", recordedDate: "2021-03-04" }, + }); + assert.equal(prepared.status, 200, JSON.stringify(prepared.json)); + assert.equal(prepared.json.review.metadata.title, "A talk"); + assert.equal(prepared.json.review.metadata.recorded_date, "20210304"); + assert.match((await post("local-media-prepare", { slug: "lib", sourceToken: preview.sourceToken, media: "talk.mp4", + sourceFingerprint: "x", details: { mode: "nope" } })).json.error, /"details"/); + + const dry = await post("local-media-link", { slug: "lib", sourceToken: preview.sourceToken, media: "bbbbbbbbbbb.mp4", + fingerprint: byMedia["bbbbbbbbbbb.mp4"].fingerprint, dryRun: true }); + assert.equal(dry.json.status, "ready", JSON.stringify(dry.json)); + assert.deepEqual((await readdir(path.join(CH, "lib", "data", "bbbbbbbbbbb"))).sort(), ["metadata.info.json", "transcript.en.vtt"]); + const linked = await post("local-media-link", { slug: "lib", sourceToken: preview.sourceToken, media: "bbbbbbbbbbb.mp4", + fingerprint: byMedia["bbbbbbbbbbb.mp4"].fingerprint }); + assert.equal(linked.json.status, "attached", JSON.stringify(linked.json)); + assert.deepEqual(JSON.parse(await readFile(path.join(CH, "lib", "data", "bbbbbbbbbbb", "external-media.json"), "utf8")), + { version: 1, kind: "external", sourceId: "library-1", relativePath: "bbbbbbbbbbb.mp4" }); + + const started = await post("local-media-import", { + slug: "lib", sourceToken: preview.sourceToken, + selected: [ + { media: "aaaaaaaaaaa.mp4", fingerprint: byMedia["aaaaaaaaaaa.mp4"].fingerprint }, + { media: "talk.mp4", fingerprint: prepared.json.review.fingerprint, + preparation: { sourceFingerprint: byMedia["talk.mp4"].preparationFingerprint, + details: { mode: "manual", title: "A talk", recordedDate: "2021-03-04" } } }, + ], + }); + assert.equal(started.status, 200, JSON.stringify(started.json)); + assert.equal(await waitJob(started.json.jobId), "done"); + const data = (await readdir(path.join(CH, "lib", "data"))).sort(); + assert.equal(data.length, 3); + assert.ok(data.includes("aaaaaaaaaaa")); + const local = data.find((d) => d.startsWith("local-"))!; + assert.equal(JSON.parse(await readFile(path.join(CH, "lib", "data", local, "metadata.info.json"), "utf8")).title, "A talk"); + assert.deepEqual((await readdir(path.join(CH, "lib", "data", "aaaaaaaaaaa"))).sort(), + ["external-media.json", "metadata.info.json", "transcript.en.vtt"]); + + // Nothing new left: allNew says so rather than starting an empty job. + assert.match((await post("local-media-import", { slug: "lib", allNew: true })).json.error, /no new recording/); + assert.match((await post("local-media-import", { slug: "lib", allNew: true, selected: [] })).json.error, /takes no/); + assert.deepEqual((await readdir(LIB)).sort(), before); +}); diff --git a/editor/app/api/ops/local-media-import/route.ts b/editor/app/api/ops/local-media-import/route.ts @@ -0,0 +1,51 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport"; +import { startLocalMediaImportJob, type LocalMediaJobRequest } from "yt-dlp-transcript-common/jobs/localMediaImportJob"; +import { OpsInputError, jobResponse, ops, optBool, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, sourceToken, selected: [{ media, fingerprint, preparation? }] } +// | { slug, allNew: true } +// -> { ok: true, jobId } +// +// LOCAL LIBRARY RECORDINGS IMPORTED (jobs/localMediaImportJob.ts; the Local +// media page's Import selected): one `import-local-media` job on the channel's +// queue writes each selected recording's metadata.info.json, transcript.en.vtt +// (an .srt converted) and external-media.json into data/<id>/. The video file +// stays where it is and is never copied. `selected` is what a +// local-media-preview answered (its `sourceToken`, each candidate's `media` +// and `fingerprint`; a prepared one adds `preparation: {sourceFingerprint, +// details}` with the prepare's fingerprint). `allNew: true` takes a fresh +// preview here and selects every "new" candidate in it. Every selection is +// re-checked before its record is written: a changed file is "stale", an +// occupied record is left unchanged. Drainable between recordings. The +// imported records are searchable after the next index build. +export async function POST(request: Request) { + return ops(request, ["slug", "sourceToken", "selected", "allNew"], async (body) => { + const slug = reqSlug(body, "slug"); + const paths = getPaths(); + let req: LocalMediaJobRequest; + if (optBool(body, "allNew") === true) { + if (body.sourceToken !== undefined || body.selected !== undefined) { + throw new OpsInputError('"allNew" takes no "sourceToken" or "selected"'); + } + const preview = await previewLocalMedia(paths, slug); + const selected = preview.candidates + .filter((c) => c.status === "new" && c.fingerprint) + .map((c) => ({ media: c.media, fingerprint: c.fingerprint! })); + if (selected.length === 0) throw new OpsInputError("the library has no new recording to import"); + req = { sourceToken: preview.sourceToken, selected }; + } else { + if (typeof body.sourceToken !== "string" || !Array.isArray(body.selected)) { + throw new OpsInputError('"sourceToken" and "selected" (from local-media-preview) are required, or "allNew": true'); + } + req = { sourceToken: body.sourceToken, selected: body.selected as LocalMediaJobRequest["selected"] }; + } + try { + return jobResponse(await startLocalMediaImportJob(paths, slug, req)); + } catch (e) { + throw new OpsInputError((e as Error).message); + } + }); +} diff --git a/editor/app/api/ops/local-media-link/route.ts b/editor/app/api/ops/local-media-link/route.ts @@ -0,0 +1,30 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { adoptLocalMediaReference } from "yt-dlp-transcript-common/controller/adoptLocalMediaReference"; +import { ops, optBool, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, sourceToken, media, fingerprint, dryRun? } +// -> { ok: true, status: "attached" | "already-linked" | "conflict" | "ready" } +// +// VERIFY AND LINK one record the channel already holds to its local original +// (controller/adoptLocalMediaReference.ts; the Local media page's Verify and +// link): for a preview candidate that is "existing", the library's +// .info.json and transcript are compared BYTE FOR BYTE with the record's +// metadata.info.json and transcript.en.vtt (an .srt converted first), and +// only on a match is external-media.json written beside them — never over one +// already there ("conflict" keeps it). Nothing else in the record changes; +// linking grants no playback. `dryRun` verifies and answers "ready" (or +// "already-linked" / "conflict") without writing. Refused while the channel has +// queued or running work. Synchronous; no job. +export async function POST(request: Request) { + return ops(request, ["slug", "sourceToken", "media", "fingerprint", "dryRun"], async (body) => { + const result = await adoptLocalMediaReference(getPaths(), reqSlug(body, "slug"), { + sourceToken: reqString(body, "sourceToken"), + media: reqString(body, "media"), + fingerprint: reqString(body, "fingerprint"), + }, { apply: optBool(body, "dryRun") !== true }); + return NextResponse.json({ ok: true, ...result }); + }); +} diff --git a/editor/app/api/ops/local-media-prepare/route.ts b/editor/app/api/ops/local-media-prepare/route.ts @@ -0,0 +1,40 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { channelWriters } from "yt-dlp-transcript-common/controller/channelWriters"; +import { prepareLocalMediaRecording } from "yt-dlp-transcript-common/controller/localMediaImport"; +import { parseLocalRecordingDetails } from "yt-dlp-transcript-common/lib/localRecordingDetails"; +import { OpsInputError, ops, opsFail, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, sourceToken, media, sourceFingerprint, +// details: { mode: "inspect" | "manual", title, recordedDate?, durationSeconds? } } +// -> { ok: true, review: { metadata, fingerprint } } +// +// LOCAL RECORDING DETAILS for a library recording with no .info.json +// (controller/localMediaImport.ts prepareLocalMediaRecording; the Local media +// page's Prepare details): a title, an optional recording date (YYYY-MM-DD) +// and, by "inspect", the duration ffprobe measures, or by "manual" the one +// given (or none). Writes nothing: the `review.fingerprint` is the +// `fingerprint` local-media-import takes, with `preparation: {sourceFingerprint, +// details}`, to import it. `sourceFingerprint` is the preview's +// `preparationFingerprint`. Refused while the channel has queued or running +// work. Synchronous; no job. +export async function POST(request: Request) { + return ops(request, ["slug", "sourceToken", "media", "sourceFingerprint", "details"], async (body) => { + const slug = reqSlug(body, "slug"); + let details; + try { details = parseLocalRecordingDetails(body.details); } + catch (e) { throw new OpsInputError(`"details": ${(e as Error).message}`); } + if (channelWriters(slug, { includeQueued: true }).length) { + return opsFail("wait for this channel's queued or running work to finish", 409); + } + const review = await prepareLocalMediaRecording(getPaths(), slug, { + sourceToken: reqString(body, "sourceToken"), + media: reqString(body, "media"), + sourceFingerprint: reqString(body, "sourceFingerprint"), + details, + }); + return NextResponse.json({ ok: true, review }); + }); +} diff --git a/editor/app/api/ops/local-media-preview/route.ts b/editor/app/api/ops/local-media-preview/route.ts @@ -0,0 +1,25 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { previewLocalMedia } from "yt-dlp-transcript-common/controller/localMediaImport"; +import { ops, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug } -> { ok: true, preview: { sourceToken, counts, candidates } } +// +// The channel's local media library SCANNED, writing nothing +// (controller/localMediaImport.ts previewLocalMedia; the Local media page's +// Preview library): every .mp4 directly in `localMedia.directory` (not its +// subdirectories) with its same-named .info.json and .vtt/.srt, each a +// candidate "new", "existing" (its record's directory is occupied) or "issue" +// (with `issues`). A candidate's `fingerprint` (import, link) or +// `preparationFingerprint` (prepare, for one with no .info.json) and the +// preview's `sourceToken` are what the other local-media actions take; a +// changed file or config makes them stale. An unreachable library is an +// error, never an empty preview. Synchronous; no job. +export async function POST(request: Request) { + return ops(request, ["slug"], async (body) => { + const preview = await previewLocalMedia(getPaths(), reqSlug(body, "slug")); + return NextResponse.json({ ok: true, preview }); + }); +} diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -53,6 +53,11 @@ // pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait // pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait // pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait +// pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}' +// pnpm ops local-media-preview --json '{"slug":"demo-local"}' +// pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}' +// pnpm ops local-media-import --json '{"slug":"demo-local","allNew":true}' --wait +// pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}' // pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}' // pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}' // pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}' @@ -434,6 +439,16 @@ const ACTIONS = [ // job; both land through the same code. "import-media", "record-live", + // A LOCAL MEDIA LIBRARY (controller/localMediaImport.ts): a directory of + // recordings that stay where they are, the channel's `localMedia`. Its + // config ({slug, sourceId, directory}), a scan writing nothing ({slug}), + // details for a recording with no .info.json, the import job, and the link + // of a record already held to its original. The local media page's twins. + "local-media-configure", + "local-media-preview", + "local-media-prepare", + "local-media-import", + "local-media-link", // LIVE PRE-CLIP (plans/live-preclip.md): a recording in progress transcribed // and mined while it records ({slug, id, action?: start | stop | status | // finalize, everyMinutes?, maxChunkMinutes?, overlapSeconds?, scan?, mine?, @@ -1741,6 +1756,47 @@ export function usage() { ' "dryRun": true says what it would do and writes nothing. A directory, a', ' .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only).', "", + "local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {\"slug\",", + " \"sourceId\", \"directory\"} — a stable lowercase id and an absolute directory", + " on the editor server whose recordings stay where they are (never copied,", + " moved or deleted). Written through the channel config; a channel that", + " already has one is refused, and so is queued or running channel work.", + " Playback is not set. Synchronous.", + "", + "local-media-preview scans the library and writes nothing: {\"slug\"} ->", + " {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the", + " directory (not its subdirectories) with its same-named .info.json and", + " .vtt (or .srt) is \"new\", \"existing\" (its record is held) or \"issue\" (with", + " issues). The sourceToken and a candidate's fingerprint (or", + " preparationFingerprint, when it has no .info.json) are what the other", + " local-media actions take. An unreachable library is an error, never an", + " empty preview.", + "", + "local-media-prepare reviews details for a recording with no .info.json and", + " writes nothing: {\"slug\", \"sourceToken\", \"media\", \"sourceFingerprint\"", + " (the candidate's preparationFingerprint), \"details\": {\"mode\": \"inspect\"", + " | \"manual\", \"title\", \"recordedDate\"? (YYYY-MM-DD), \"durationSeconds\"?", + " (manual)}} -> {review: {metadata, fingerprint}}. \"inspect\" measures the", + " duration with ffprobe. Import it with local-media-import, the review's", + " fingerprint and \"preparation\": {\"sourceFingerprint\", \"details\"}.", + "", + "local-media-import imports library recordings as one job on the channel's", + " queue: {\"slug\", \"sourceToken\", \"selected\": [{\"media\", \"fingerprint\",", + " \"preparation\"?}]} from a preview, or {\"slug\", \"allNew\": true} for every", + " \"new\" candidate of a fresh preview. Each record gets metadata.info.json,", + " transcript.en.vtt and external-media.json; the video stays in the", + " library. Every selection is re-checked first (a changed file is stale; a", + " held record is left unchanged). Drainable between recordings; searchable", + " after the next index build.", + "", + "local-media-link links a record the channel already holds to its library", + " original: {\"slug\", \"sourceToken\", \"media\", \"fingerprint\", \"dryRun\"?} for", + " an \"existing\" candidate. Only when the library's .info.json and", + " transcript match the record's byte for byte is external-media.json", + " written (\"attached\"; \"already-linked\"; \"conflict\" keeps a different one).", + " Nothing else changes, and no playback is granted. \"dryRun\" answers", + " \"ready\" without writing.", + "", 'record-live records a live stream until it ends, then lands it as', ' import-media lands a file: {"slug", "url"} (or "id" of a record here),', ' "fromStart"? (true: yt-dlp --live-from-start — Rumble\'s DVR playlist', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -1084,3 +1084,17 @@ test("archive-lookup is a POST to its route; import-page passes source through; assert.match(usage(), /archive-lookup answers the copies of a page each archive source holds/); assert.match(usage(), /excluded from the Wayback Machine \(cause/); }); + +// Local media libraries (lane/local-media slice 1): the Local media page's +// five twins are POSTs to their own routes, each named in the usage. +test("the local-media actions are POSTs to their routes, named in the usage", () => { + for (const action of ["local-media-configure", "local-media-preview", "local-media-prepare", "local-media-import", "local-media-link"]) { + const p = parseArgs([action, "--json", '{"slug":"demo-local"}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, `/api/ops/${action}`); + assert.deepEqual(p.body, { slug: "demo-local" }); + assert.match(usage(), new RegExp(`\\n${action} `)); + } + assert.equal(parseArgs(["local-media-import", "--json", '{"slug":"demo-local","allNew":true}', "--wait"]).wait, true); + assert.match(usage(), /Actions:.*record-live, local-media-configure, local-media-preview, local-media-prepare, local-media-import, local-media-link/); +});