Archilyzer · Source

archilyzer

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

commit 482fd974595a6dbb2e0881494b2d627cb4236b61
parent 15e239ba42d935eefc70f3f0b8b6ce38ec52c2df
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 23:17:33 -0400

attach-media: ISO "Published on 2019-10-31" dates read; fillDates dates a held attach-media record with no upload_date from its description.txt, through the metadata history

publishedDateFromText reads YYYY-MM-DD and YYYY/MM/DD beside the month-name
spellings, and a date not on the calendar is no date. "fillDates": true
(--fill-dates) patches upload_date into a held record whose saved-video.json
origin is local-archive and that has none, by patchMetadataInfo as
"local-archive"; a dated record, or one attach-media did not make, is never
touched. "dated"/"undated" in the log and summary; dryRun lists them only.
COMMANDS.md regenerated.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 4++--
Mcommon/bin/archilyzer.ts | 4+++-
Mcommon/bin/media-attach.ts | 4+++-
Mcommon/controller/attachMedia.test.ts | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/attachMedia.ts | 89++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/attachMediaPlan.test.ts | 14++++++++++++++
Mcommon/lib/attachMediaPlan.ts | 26++++++++++++++++++++------
Meditor/app/api/ops/attach-media/route.test.ts | 5++++-
Meditor/app/api/ops/attach-media/route.ts | 11++++++++---
Meditor/app/channels/[slug]/attachMediaActions.ts | 10+++++++---
Mscripts/archilyzer-ops.mjs | 14++++++++++----
11 files changed, 286 insertions(+), 22 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -61,7 +61,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer archive lookup` | `<url> [--source wayback\|archive.today] [--limit N]` | the copies of a page each archive source holds (the Wayback Machine's CDX, archive.today's timemap), oldest first, at most N per source (50): read only, each source through its own paced client. A source that refuses says why (excluded from the Wayback Machine, a check, a 429). While an editor runs, `pnpm ops archive-lookup` shares its clients | | `archilyzer wayback pages reextract` | `<slug> [--dry-run]` | re-derive a Wayback pages channel's records from the raw captures it stores (no request): every capture read by the extractor it goes to now, the records replaced when anything differs; --dry-run counts. Writes the channel's posts — with the editor stopped, or use `pnpm ops reextract-pages` | | `archilyzer feeds backfill-metadata` | `<slug> [--feed <url>] [--dry-run]` | complete a podcast channel's records (title, date, description, duration) from its RSS feed: one fetch of the feed (default: the channel's url), no media; --dry-run counts matched / unmatched / already complete and writes nothing | -| `archilyzer media attach` | `<slug> <source> [--items <json\|@file>] [--match <regex>] [--create-records] [--replace] [--dry-run]` | give a channel's held videos their media from a LOCAL archive (a directory, a .zip read in place, a .7z) into the saved-video store, provenance recorded (archive, entry, sha256); the id from the folder's "(&lt;id&gt;)" or the file's yt-dlp suffix; --create-records writes a record for a video not held; --dry-run lists each folder's class and writes nothing; offline, nothing fetched | +| `archilyzer media attach` | `<slug> <source> [--items <json\|@file>] [--match <regex>] [--create-records] [--replace] [--fill-dates] [--dry-run]` | give a channel's held videos their media from a LOCAL archive (a directory, a .zip read in place, a .7z) into the saved-video store, provenance recorded (archive, entry, sha256); the id from the folder's "(&lt;id&gt;)" or the file's yt-dlp suffix; --create-records writes a record for a video not held; --fill-dates gives a held record attach-media made that has no upload\_date the date from its folder's description.txt (a dated record, or one not made by attach-media, is never touched); --dry-run lists each folder's class and writes nothing; offline, nothing fetched | | `archilyzer media playable` | `<slug> [--ids <a,b>] [--trackers <url,url>] [--root <dir>] [--dry-run]` | remux a channel's saved containers losslessly (-c copy) into browser-playable mp4 (+faststart) or webm, one single-file torrent each (no web seed; --trackers is the announce list, outside the infohash), under playable/ beside the saved-video store; keyed by the source's sha256, so a re-run is a no-op; offline | | `archilyzer seed` | | the home seeder of last resort: seed the playable torrents of settings.seeder.sites, each only while no other seeder has it (standby otherwise, with hysteresis), TCP + WebRTC, no DHT; runs until interrupted — behind the VPN (docker compose profile `seeder`, docker-compose.seeder.yml) | | `archilyzer tracker` | `[--host 127.0.0.1] [--port 8000]` | the self-hosted tracker (HTTP + WebSocket, no UDP) for the seeder's torrents only — any other infohash is refused; runs until interrupted | @@ -117,7 +117,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `import-video` | import-video imports one video by URL into a channel: {"slug", "url"}. An archive.org URL becomes its canonical item or file (an item of several media files is refused — see import-archive-org); a BitChute or Odysee URL runs on that platform's queue at its pace, refused while it is held or cooling down, and refused when already on disk; a Wayback capture is named by what it copies. | `pnpm ops import-video --json '{"slug":"demo-archive","url":"https://archive.org/details/example-item"}'` | | `import-archive-org` | import-archive-org imports archive.org media into a channel, as one job on archive.org's queue: {"slug", "item", "files": \[...\] \| "match": "&lt;regex&gt;"} for one item; {"slug", "items": \["&lt;id&gt;" \| {"item", "files"? \| "match"?}, ...\]} for many (a bare id takes "match", else every media original); or {"slug", "query": "&lt;archive.org search&gt;", "limit"?: 100} for the first items a search finds (at most 500). One file at a time, a jittered pause between files and between items; a record already held (on disk, or in the saved-video store) is skipped. "dryRun": true lists each file as held, RESTRICTED (archive.org marks it not for download: a fetch would answer 401/403) or would get, and fetches nothing. A 401/403 skips the rest of its item; three such items in a row, a 429 or three failures in a row stop the job. The log ends with a summary: line; a re-run resumes. | `pnpm ops import-archive-org --json '{"slug":"demo-archive","item":"example-item","match":"\\.mp4$"}' --wait`<br>`pnpm ops import-archive-org --json '{"slug":"demo-archive","query":"collection:example-collection","dryRun":true}' --wait` | | `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | | -| `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. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | | +| `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), "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; the longest part wins. Refused for a stream that is not live. | `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"}'` | | `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/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -776,12 +776,13 @@ export const COMMANDS: Command[] = [ { path: ["media", "attach"], usage: - "<slug> <source> [--items <json|@file>] [--match <regex>] [--create-records] [--replace] [--dry-run] give a channel's held videos their media from a LOCAL archive (a directory, a .zip read in place, a .7z) into the saved-video store, provenance recorded (archive, entry, sha256); the id from the folder's \"(<id>)\" or the file's yt-dlp suffix; --create-records writes a record for a video not held; --dry-run lists each folder's class and writes nothing; offline, nothing fetched", + "<slug> <source> [--items <json|@file>] [--match <regex>] [--create-records] [--replace] [--fill-dates] [--dry-run] give a channel's held videos their media from a LOCAL archive (a directory, a .zip read in place, a .7z) into the saved-video store, provenance recorded (archive, entry, sha256); the id from the folder's \"(<id>)\" or the file's yt-dlp suffix; --create-records writes a record for a video not held; --fill-dates gives a held record attach-media made that has no upload_date the date from its folder's description.txt (a dated record, or one not made by attach-media, is never touched); --dry-run lists each folder's class and writes nothing; offline, nothing fetched", flags: { items: "string", match: "string", "create-records": "boolean", replace: "boolean", + "fill-dates": "boolean", "dry-run": "boolean", }, maxPositionals: 2, @@ -798,6 +799,7 @@ export const COMMANDS: Command[] = [ ...(typeof flags.match === "string" ? { match: flags.match } : {}), createRecords: flags["create-records"] === true, replace: flags.replace === true, + fillDates: flags["fill-dates"] === true, dryRun: flags["dry-run"] === true, signal: interrupted(), }); diff --git a/common/bin/media-attach.ts b/common/bin/media-attach.ts @@ -1,5 +1,5 @@ // `archilyzer media attach <slug> <source> [--items <json>] [--match <re>] -// [--create-records] [--replace] [--dry-run]` — a channel's held videos given +// [--create-records] [--replace] [--fill-dates] [--dry-run]` — a channel's held videos given // their media from a local archive, offline. The work and its rules are // controller/attachMedia.ts; the editor runs the same function as the // `attach-media` job (`POST /api/ops/attach-media`). @@ -35,6 +35,7 @@ export async function main(opts: { match?: string; createRecords: boolean; replace: boolean; + fillDates?: boolean; dryRun: boolean; signal?: AbortSignal; }): Promise<number> { @@ -64,6 +65,7 @@ export async function main(opts: { ...(opts.match !== undefined ? { match: opts.match } : {}), ...(opts.createRecords ? { createRecords: true } : {}), ...(opts.replace ? { replace: true } : {}), + ...(opts.fillDates ? { fillDates: true } : {}), ...(opts.dryRun ? { dryRun: true } : {}), onLog: (line) => console.log(line.replace(/\n$/, "")), ...(opts.signal ? { signal: opts.signal } : {}), diff --git a/common/controller/attachMedia.test.ts b/common/controller/attachMedia.test.ts @@ -289,6 +289,133 @@ test("the disk margin: a store disk without the video plus 2 GiB free stops the }); }); +// FILL DATES: records attach-media made before the parser read ISO dates. +// eeeeeeeee: made by attach-media, no upload_date, an ISO date → dated. +// fffffffff: made by attach-media, HAS a date → untouched. +// ggggggggg: attached over a download (origin not local-archive), no date → untouched. +// iiiiiiiii: made by attach-media, no date, description.txt names none → undated. +// jjjjjjjjj: made by attach-media, no date, no description.txt at all → undated. +const E = bytes(20_000, 17); +const F = bytes(21_000, 19); +const G = bytes(22_000, 23); +const I = bytes(23_000, 29); +const J = bytes(24_000, 31); +const DATE_ENTRIES: ZipFixtureEntry[] = [ + { name: "YouTube/064 - Deadspin, Halloween & More! - (eeeeeeeeeee)/eeeeeeeeeee.mp4", data: E }, + { name: "YouTube/064 - Deadspin, Halloween & More! - (eeeeeeeeeee)/description.txt", data: "Published on 2019-10-31\n\nCategory: Comedy" }, + { name: "YouTube/065 - Dated - (fffffffffff)/fffffffffff.mp4", data: F }, + { name: "YouTube/065 - Dated - (fffffffffff)/description.txt", data: "Published on 2019-10-31\n\nCategory: Comedy" }, + { name: "YouTube/066 - Downloaded - (ggggggggggg)/ggggggggggg.mp4", data: G }, + { name: "YouTube/066 - Downloaded - (ggggggggggg)/description.txt", data: "Published on 2024/06/21\n\nLive" }, + { name: "YouTube/067 - No date - (iiiiiiiiiii)/iiiiiiiiiii.mp4", data: I }, + { name: "YouTube/067 - No date - (iiiiiiiiiii)/description.txt", data: "Published on 2019-02-30\n\nNot a day" }, + { name: "YouTube/068 - No text - (jjjjjjjjjjj)/jjjjjjjjjjj.mp4", data: J }, +]; + +// The corpus as the old parser left it: e/f/i/j created by attach-media (f +// with a date its description did not give), e/i/j then stripped of the date +// they lack in the field; g a download's record with a pointer of its own. +async function seedOldRecords(ctx: Ctx): Promise<void> { + const { paths, opts } = ctx; + const made = await attachMedia(opts({ createRecords: true, match: "eeeeeeeeeee|fffffffffff|iiiiiiiiiii|jjjjjjjjjjj" })); + assert.deepEqual(made.created.sort(), ["eeeeeeeeeee", "fffffffffff", "iiiiiiiiiii", "jjjjjjjjjjj"]); + for (const id of ["eeeeeeeeeee", "fffffffffff", "iiiiiiiiiii", "jjjjjjjjjjj"]) { + const file = path.join(videoDir(paths, id), "metadata.info.json"); + const info = JSON.parse(await readFile(file, "utf8")) as Record<string, unknown>; + delete info.upload_date; + if (id === "fffffffffff") info.upload_date = "20100101"; + await writeFile(file, JSON.stringify(info)); + } + const gDir = videoDir(paths, "ggggggggggg"); + const gStore = path.join(paths.savedVideosDir, SLUG, "ggggggggggg"); + await mkdir(gDir, { recursive: true }); + await mkdir(gStore, { recursive: true }); + await writeFile(path.join(gDir, "metadata.info.json"), JSON.stringify({ id: "ggggggggggg", title: "Downloaded" })); + await writeFile(path.join(gStore, "source-media.mp4"), G); + await writeFile( + path.join(gDir, "saved-video.json"), + JSON.stringify({ storedAt: "x", dir: gStore, file: "source-media.mp4", bytes: G.length, keepReason: "override" }), + ); +} + +const infoOf = async (paths: Paths, id: string) => + JSON.parse(await readFile(path.join(videoDir(paths, id), "metadata.info.json"), "utf8")) as Record<string, unknown>; +const filesOf = async (paths: Paths, id: string) => (await readdir(videoDir(paths, id))).sort(); + +test("fillDates: dry run lists the dated and the undated, and writes nothing", async () => { + await withFixture(async (ctx) => { + const { paths, opts, lines } = ctx; + await seedOldRecords(ctx); + const before = Object.fromEntries( + await Promise.all(["eeeeeeeeeee", "fffffffffff", "ggggggggggg"].map(async (id) => [id, await readFile(path.join(videoDir(paths, id), "metadata.info.json"))])), + ); + lines.length = 0; + const r = await attachMedia(opts({ fillDates: true, dryRun: true })); + assert.deepEqual(r.dated, ["eeeeeeeeeee"]); + assert.deepEqual(r.undated, ["iiiiiiiiiii", "jjjjjjjjjjj"]); + assert.ok(lines.some((l) => /^dated\s+eeeeeeeeeee ← upload_date 20191031 \(YouTube\/064 .*description\.txt\)/.test(l)), lines.join("")); + const summary = JSON.parse(lines.find((l) => l.startsWith("summary: "))!.slice("summary: ".length)); + assert.deepEqual(summary.dated, ["eeeeeeeeeee"]); + assert.deepEqual(summary.undated, ["iiiiiiiiiii", "jjjjjjjjjjj"]); + for (const [id, bytes] of Object.entries(before)) { + assert.deepEqual(await readFile(path.join(videoDir(paths, id), "metadata.info.json")), bytes, id); + } + assert.ok(!(await filesOf(paths, "eeeeeeeeeee")).includes("metadata.history.json")); + }, DATE_ENTRIES); +}); + +test("fillDates: dates an attach-media record with none, through the metadata history; never one with a date or one it did not make", async () => { + await withFixture(async (ctx) => { + const { paths, opts } = ctx; + await seedOldRecords(ctx); + const fBefore = await readFile(path.join(videoDir(paths, "fffffffffff"), "metadata.info.json")); + const gBefore = await readFile(path.join(videoDir(paths, "ggggggggggg"), "metadata.info.json")); + const eBefore = await infoOf(paths, "eeeeeeeeeee"); + + const r = await attachMedia(opts({ fillDates: true })); + assert.deepEqual(r.dated, ["eeeeeeeeeee"]); + assert.deepEqual(r.attached, [], "every folder is attached already"); + assert.deepEqual(r.failed, []); + + // Dated: only upload_date added, at the tail; everything else as it was. + const e = await infoOf(paths, "eeeeeeeeeee"); + assert.deepEqual(e, { ...eBefore, upload_date: "20191031" }); + assert.equal(Object.keys(e).at(-1), "upload_date"); + const history = JSON.parse(await readFile(path.join(videoDir(paths, "eeeeeeeeeee"), "metadata.history.json"), "utf8")); + assert.equal(history.entries.length, 1); + assert.equal(history.entries[0].by, "local-archive"); + assert.equal(history.entries[0].requestedBy, "attach-media"); + assert.deepEqual(history.entries[0].added, { upload_date: "20191031" }); + + // Has a date: untouched (byte for byte, no history). + assert.deepEqual(await readFile(path.join(videoDir(paths, "fffffffffff"), "metadata.info.json")), fBefore); + assert.ok(!(await filesOf(paths, "fffffffffff")).includes("metadata.history.json")); + // Not made by attach-media: untouched although its description has a date. + assert.deepEqual(await readFile(path.join(videoDir(paths, "ggggggggggg"), "metadata.info.json")), gBefore); + assert.ok(!(await filesOf(paths, "ggggggggggg")).includes("metadata.history.json")); + // No date to read: untouched, listed. + assert.deepEqual(r.undated, ["iiiiiiiiiii", "jjjjjjjjjjj"]); + assert.equal((await infoOf(paths, "iiiiiiiiiii")).upload_date, undefined); + + // A re-run has nothing left to date. + const again = await attachMedia(opts({ fillDates: true })); + assert.deepEqual(again.dated, []); + assert.equal(JSON.parse(await readFile(path.join(videoDir(paths, "eeeeeeeeeee"), "metadata.history.json"), "utf8")).entries.length, 1); + + // Without fillDates nothing is dated and the summary does not mention it. + const plain = await attachMedia(opts()); + assert.equal(plain.dated, null); + }, DATE_ENTRIES); +}); + +test("createRecords reads an ISO date from description.txt", async () => { + await withFixture(async ({ paths, opts }) => { + await attachMedia(opts({ createRecords: true, match: "eeeeeeeeeee" })); + assert.equal((await infoOf(paths, "eeeeeeeeeee")).upload_date, "20191031"); + assert.equal((await infoOf(paths, "eeeeeeeeeee")).description, "Category: Comedy"); + }, DATE_ENTRIES); +}); + test("drain stops before the next video", async () => { await withFixture(async ({ opts }) => { const drain = new AbortController(); diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts @@ -31,6 +31,17 @@ // metadata history, and the channel's `archive` file gains its line, as a // download would. Transcribing it is a separate step. // +// FILL DATES (`fillDates`). A record created here whose description.txt +// spelled its date in a way the parser did not read then has no +// `upload_date`, and the index skips it. With `fillDates` a re-run gives a +// HELD record the date from its folder's description.txt, merged into +// metadata.info.json by `patchMetadataInfo` (the history records it, by +// "local-archive") — only when all three hold: the record's saved-video.json +// origin is "local-archive" (attach-media made it), its metadata.info.json has +// no `upload_date`, and the folder's description.txt yields a real date. +// Nothing else in the record is touched. "dated" in the log and the summary; +// `dryRun` lists them and writes nothing. +// // GUARDED: the job kind declares `needsMedia` (runManagedFunction asks the // channel's media guard), every store write asks // `assertSavedVideosStoreWritable`, the store's root must exist (an unmounted @@ -59,7 +70,7 @@ import { import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { writeJsonAtomic } from "../lib/jsonFile-server"; -import { withMetadataHistory } from "../lib/metadataHistory-server"; +import { patchMetadataInfo, withMetadataHistory } from "../lib/metadataHistory-server"; import { getFreeBytes } from "../lib/diskSpace"; import { formatBytes } from "../lib/format"; import { probeMediaDurationSec } from "../ytdlp/ffprobeDuration"; @@ -68,6 +79,7 @@ import { countAttachRows, groupArchiveFolders, planAttach, + publishedDateFromText, type AttachItem, type AttachPlan, type AttachRow, @@ -237,6 +249,9 @@ export type AttachMediaOptions = { match?: string; createRecords?: boolean; replace?: boolean; + // Give a held, attach-media-made record with no upload_date the date from + // its folder's description.txt (FILL DATES above). + fillDates?: boolean; dryRun?: boolean; onLog: (line: string) => void; signal?: AbortSignal; @@ -262,6 +277,10 @@ export type AttachMediaResult = { ambiguous: string[]; alreadyAttached: string[]; heldWithoutMedia: string[] | null; + // fillDates only (null without it): the records given a date (or, dry, that + // would be), and the candidates whose description.txt gave none. + dated: string[] | null; + undated: string[] | null; stopped?: string; dryRun: boolean; }; @@ -321,6 +340,66 @@ async function recordInfo( }); } +// FILL DATES: every held row with a folder, whose record attach-media made and +// lacks an upload_date, given the date its description.txt names. +async function fillDates( + source: ArchiveSource, + plan: AttachPlan, + pointers: ReadonlyMap<string, Awaited<ReturnType<typeof loadSavedVideo>>>, + dataDir: string, + opts: AttachMediaOptions, + result: AttachMediaResult, + onLog: (s: string) => void, +): Promise<void> { + const dated: string[] = []; + const undated: string[] = []; + result.dated = dated; + result.undated = undated; + for (const row of plan.rows) { + if (opts.signal?.aborted || opts.drainSignal?.aborted) { + result.stopped = opts.signal?.aborted ? "cancelled" : "drained"; + return; + } + const id = row.id; + const folder = row.source; + if (!id || !folder) continue; + if (pointers.get(id)?.origin?.kind !== "local-archive") continue; + const videoDir = path.join(dataDir, id); + let info: unknown; + try { + info = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")); + } catch { + continue; + } + if (!info || typeof info !== "object" || Array.isArray(info)) continue; + const have = (info as Record<string, unknown>).upload_date; + if (have !== undefined && have !== null && have !== "") continue; + const text = folder.descriptionTxt ? await source.readText(folder.descriptionTxt).catch(() => null) : null; + const date = text === null ? null : publishedDateFromText(text); + if (!date) { + undated.push(id); + onLog(`${"undated".padEnd(16)} ${id} ${folder.descriptionTxt ? `${folder.descriptionTxt.path}: no date read` : `${folder.folder}: no description.txt`}`); + continue; + } + onLog(`${"dated".padEnd(16)} ${id} ← upload_date ${date} (${folder.descriptionTxt!.path})`); + if (opts.dryRun) { + dated.push(id); + continue; + } + try { + await patchMetadataInfo(videoDir, { upload_date: date }, { + by: "local-archive", + requestedBy: ATTACH_MEDIA_REQUESTER, + onLog, + }); + dated.push(id); + } catch (err) { + result.failed.push({ id, error: (err as Error).message }); + onLog(`${id}: FAILED to date — ${(err as Error).message}`); + } + } +} + function logPlan(plan: AttachPlan, onLog: (s: string) => void): void { for (const r of plan.rows) { const what = r.media ? ` ← ${r.media.path} (${formatBytes(r.media.size)})` : ""; @@ -384,8 +463,14 @@ export async function attachMedia(opts: AttachMediaOptions): Promise<AttachMedia ambiguous: ids("ambiguous"), alreadyAttached: ids("already-attached"), heldWithoutMedia: plan.heldWithoutMedia, + dated: null, + undated: null, dryRun: !!opts.dryRun, }; + if (opts.fillDates) { + await fillDates(source, plan, pointers, dataDir, opts, result, onLog); + onLog(`${result.dated!.length} dated from description.txt${result.undated!.length ? `, ${result.undated!.length} with no date to read` : ""}`); + } const work = plan.rows.filter((r) => r.class === "attach" || r.class === "create"); const total = work.reduce((s, r) => s + (r.media?.size ?? 0), 0); onLog(`${work.length} to attach (${formatBytes(total)}): ${result.counts.attach} held, ${result.counts.create} new records`); @@ -501,6 +586,8 @@ export function summaryOf(r: AttachMediaResult): Record<string, unknown> { ambiguous: r.ambiguous, alreadyAttached: r.alreadyAttached.length, heldWithoutMedia: r.heldWithoutMedia, + ...(r.dated ? { dated: r.dated } : {}), + ...(r.undated?.length ? { undated: r.undated } : {}), ...(r.stopped ? { stopped: r.stopped } : {}), }; } diff --git a/common/lib/attachMediaPlan.test.ts b/common/lib/attachMediaPlan.test.ts @@ -148,6 +148,20 @@ test("records: title from the folder name, date and description from description assert.equal(publishedDateFromText("Published on July 13th 2018\n\nTips"), "20180713"); assert.equal(publishedDateFromText("Published on March 1, 2019"), "20190301"); assert.equal(publishedDateFromText("no date"), null); + // ISO, as later folders write it, and its slashed spelling. + assert.equal(publishedDateFromText("Published on 2019-10-31\n\nCategory: Comedy"), "20191031"); + assert.equal(publishedDateFromText("Published on 2024/06/21\n\nLive from Rumble Studio"), "20240621"); + assert.equal(publishedDateFromText("Published on 2024-6-1"), "20240601"); + // A date that does not exist is no date, in either spelling. + assert.equal(publishedDateFromText("Published on 2019-02-30"), null); + assert.equal(publishedDateFromText("Published on 2019-13-01"), null); + assert.equal(publishedDateFromText("Published on 2019-10-00"), null); + assert.equal(publishedDateFromText("Published on 2019-10/31"), null, "mixed separators"); + assert.equal(publishedDateFromText("Published on 2019-10-310"), null); + assert.equal(publishedDateFromText("Published on February 30th 2019"), null); + assert.equal(publishedDateFromText("Published on Smarch 3 2019"), null); + assert.equal(publishedDateFromText("Published on February 29th 2020"), "20200229"); + assert.equal(descriptionFromText("Published on 2024-06-21\n\nLive from Rumble Studio\n\nCategory: Entertainment"), "Live from Rumble Studio\n\nCategory: Entertainment"); assert.equal(descriptionFromText("Published on July 13th 2018\n\nTips & comments\nCategory: X"), "Tips & comments\nCategory: X"); const info = archiveFolderInfoJson({ diff --git a/common/lib/attachMediaPlan.ts b/common/lib/attachMediaPlan.ts @@ -151,14 +151,27 @@ const MONTHS = [ "july", "august", "september", "october", "november", "december", ]; -// "Published on July 13th 2018" (the archive's description.txt) → "20180713". +// A calendar date as yt-dlp's `upload_date` ("YYYYMMDD"), or null when the +// month or day does not exist (2019-02-30, 2019-13-01). +function ymd(year: number, month: number, day: number): string | null { + if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day)) return null; + if (year < 1900 || year > 9999 || month < 1 || month > 12 || day < 1) return null; + const last = new Date(Date.UTC(year, month, 0)).getUTCDate(); + if (day > last) return null; + return `${year}${String(month).padStart(2, "0")}${String(day).padStart(2, "0")}`; +} + +// The archive's description.txt "Published on …" line → "YYYYMMDD". Three +// spellings: "July 13th 2018", "March 1, 2019", and ISO "2019-10-31" (or +// "2019/10/31"), which later folders use. export function publishedDateFromText(text: string): string | null { + const iso = /published\s+on\s+(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?!\d)/i.exec(text); + if (iso) return ymd(Number(iso[1]), Number(iso[3]), Number(iso[4])); const m = /published\s+on\s+([A-Za-z]+)\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})/i.exec(text); if (!m) return null; const month = MONTHS.indexOf(m[1].toLowerCase()); - const day = Number(m[2]); - if (month < 0 || day < 1 || day > 31) return null; - return `${m[3]}${String(month + 1).padStart(2, "0")}${String(day).padStart(2, "0")}`; + if (month < 0) return null; + return ymd(Number(m[3]), month + 1, Number(m[2])); } // The description a record gets from description.txt: the text without the @@ -228,7 +241,8 @@ export type AttachRow = { // The file to copy ("attach"/"create"), or the candidates ("ambiguous"). media?: SourceFile; candidates?: SourceFile[]; - // The folder, for createRecords. + // The folder, for createRecords (and fillDates, which reads its + // description.txt for a held record). source?: ArchiveFolder; // `attach` over an existing pointer (replace: true). replacing?: boolean; @@ -258,7 +272,7 @@ export function planAttach(opts: { const classify = (id: string, media: SourceFile, folder: string, source?: ArchiveFolder): AttachRow => { if (opts.held.has(id)) { if (opts.attached.has(id) && !opts.replace) { - return { class: "already-attached", id, folder, media }; + return { class: "already-attached", id, folder, media, ...(source ? { source } : {}) }; } return { class: "attach", diff --git a/editor/app/api/ops/attach-media/route.test.ts b/editor/app/api/ops/attach-media/route.test.ts @@ -61,6 +61,7 @@ test("refusals before any job: keys, slug, source, items, match, channel", async [{ slug: "tism", source: ZIP, items: [{ id: "a", path: "x" }], match: "x" }, /"items" or "match", not both/], [{ slug: "tism", source: ZIP, match: "(" }, /not a valid regex/], [{ slug: "tism", source: ZIP, dryRun: "yes" }, /"dryRun" must be a boolean/], + [{ slug: "tism", source: ZIP, fillDates: "yes" }, /"fillDates" must be a boolean/], [{ slug: "no-such", source: ZIP }, /Channel "no-such" not found/], ]; for (const [body, re] of cases) { @@ -72,7 +73,7 @@ test("refusals before any job: keys, slug, source, items, match, channel", async }); test("a dry run is a job whose log classifies the archive and writes nothing", async () => { - const r = await post({ slug: "tism", source: ZIP, dryRun: true }); + const r = await post({ slug: "tism", source: ZIP, fillDates: true, dryRun: true }); assert.equal(r.status, 200, JSON.stringify(r.json)); assert.ok(r.json.jobId); for (let i = 0; i < 100; i++) { @@ -87,5 +88,7 @@ test("a dry run is a job whose log classifies the archive and writes nothing", a assert.equal(summary.counts.attach, 1); assert.deepEqual(summary.notHeld, ["ccccccccccc"]); assert.equal(summary.lost, 1); + // fillDates passed through: nothing here was made by attach-media, so nothing to date. + assert.deepEqual(summary.dated, []); assert.deepEqual(await readdir(path.join(CH, "tism", "data", "aaaaaaaaaaa")), ["metadata.info.json"]); }); diff --git a/editor/app/api/ops/attach-media/route.ts b/editor/app/api/ops/attach-media/route.ts @@ -13,7 +13,7 @@ import { export const dynamic = "force-dynamic"; -// POST { slug, source, items?: [{id, path}], match?, createRecords?, replace?, dryRun? } +// POST { slug, source, items?: [{id, path}], match?, createRecords?, replace?, fillDates?, dryRun? } // -> { ok: true, jobId } // // Local media attached to a channel's held videos (release 21 D1): each @@ -24,7 +24,11 @@ export const dynamic = "force-dynamic"; // suffix; `items` names exact files instead (each `path` is the entry's path // inside the source), `match` narrows the folders by a case-insensitive regex. // `createRecords` writes a record for a video the channel does not hold; -// `replace` re-attaches over an existing saved container. `dryRun` logs what +// `replace` re-attaches over an existing saved container. `fillDates` gives a +// held record attach-media made (its saved-video.json origin "local-archive") +// that has no upload_date the date from its folder's description.txt, through +// the metadata history; a record with a date, or one attach-media did not +// make, is never touched. `dryRun` logs what // each folder is (attach, not held, already attached, [LOST], no media, // unmatched, ambiguous) and the held videos the archive has no media for, and // writes nothing. The job's log ends with a `summary: {…}` line. @@ -54,7 +58,7 @@ function optItems(body: OpsBody): { id: string; path: string }[] | undefined { export async function POST(request: Request) { return ops( request, - ["slug", "source", "items", "match", "createRecords", "replace", "dryRun"], + ["slug", "source", "items", "match", "createRecords", "replace", "fillDates", "dryRun"], async (body) => jobResponse( await attachMediaAction(reqSlug(body, "slug"), { @@ -63,6 +67,7 @@ export async function POST(request: Request) { match: optString(body, "match"), createRecords: optBool(body, "createRecords"), replace: optBool(body, "replace"), + fillDates: optBool(body, "fillDates"), dryRun: optBool(body, "dryRun"), }), ), diff --git a/editor/app/channels/[slug]/attachMediaActions.ts b/editor/app/channels/[slug]/attachMediaActions.ts @@ -32,6 +32,7 @@ export async function attachMediaAction( match?: string; createRecords?: boolean; replace?: boolean; + fillDates?: boolean; dryRun?: boolean; }, ): Promise<StreamActionResult> { @@ -69,6 +70,7 @@ export async function attachMediaAction( ...(opts.match !== undefined ? { match: opts.match } : {}), ...(opts.createRecords ? { createRecords: true } : {}), ...(opts.replace ? { replace: true } : {}), + ...(opts.fillDates ? { fillDates: true } : {}), ...(opts.dryRun ? { dryRun: true } : {}), onLog, signal, @@ -78,12 +80,14 @@ export async function attachMediaAction( safeRevalidate([ `/channels/${slug}`, "/channels", - ...result.attached.map((id) => `/channels/${slug}/videos/${id}`), + ...[...new Set([...result.attached, ...(result.dated ?? [])])].map( + (id) => `/channels/${slug}/videos/${id}`, + ), ]); } - if (result.failed.length > 0 && result.attached.length === 0) { + if (result.failed.length > 0 && result.attached.length === 0 && !result.dated?.length) { throw new Error( - `${result.failed.length} failed, none attached: ${JSON.stringify(summaryOf(result).failed)}`, + `${result.failed.length} failed, none attached or dated: ${JSON.stringify(summaryOf(result).failed)}`, ); } if (result.stopped && result.stopped !== "drained" && result.stopped !== "cancelled") { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -44,6 +44,7 @@ // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait // 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 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 keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}' @@ -1382,10 +1383,15 @@ export function usage() { ' 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. "dryRun": true logs each folder\'s', - " class (attach, not-held, already-attached, lost, no-media, unmatched,", - " ambiguous) and the held videos with no media in it, and writes nothing.", - " The log ends with a summary: line; a re-run resumes.", + ' 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.", "", 'import-media makes ONE file from outside the archive a normal transcribed', ' item: {"slug", "path"} (absolute) and which record — "url" (the source',