Archilyzer · Source

archilyzer

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

commit 0dade54debb2788f4c3f5f39af2b62b6e0434e5d
parent 250d748575d7b9d2de454cc52aa8d2c00028e16c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 23:44:06 -0400

editor: the bulk CLI-only rows get buttons — channel-wide attach from a local archive and playable copies on the Cleanup stage, Save these videos (persist-videos) on Saved videos

"Media for the whole channel" (Cleanup stage): attach-media over the whole
archive (only names matching, create records, replace) and prepare-playable
(trackers, folder), each previewed first — the run armed by a preview of the
same settings — and the job's `summary:` line said in plain words with the job
linked. "Save these videos" (/saved-videos): one video per line (slug/id or a
video page link), quality and replace; Preview answers with the plan's buckets,
Save starts one persist-videos job per channel and links each.

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

Diffstat:
Aeditor/app/channels/[slug]/components/ChannelMediaTools.tsx | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/stages/CleanupStage.tsx | 2++
Aeditor/app/channels/[slug]/lib/mediaToolsWords.test.ts | 39+++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/lib/mediaToolsWords.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/saved-videos/components/PersistVideoListControl.tsx | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/saved-videos/lib/videoList.test.ts | 35+++++++++++++++++++++++++++++++++++
Aeditor/app/saved-videos/lib/videoList.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/saved-videos/page.tsx | 3+++
Aeditor/app/saved-videos/persistListAction.ts | 43+++++++++++++++++++++++++++++++++++++++++++
9 files changed, 595 insertions(+), 0 deletions(-)

diff --git a/editor/app/channels/[slug]/components/ChannelMediaTools.tsx b/editor/app/channels/[slug]/components/ChannelMediaTools.tsx @@ -0,0 +1,213 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { attachMediaAction } from "../attachMediaActions"; +import { preparePlayableAction } from "../playableActions"; +import { readResultMarker } from "../../../lib/resultMarker"; +import { + MEDIA_SUMMARY_MARKER, + attachSummaryWords, + playableSummaryWords, + type AttachSummary, + type PlayableSummary, +} from "../lib/mediaToolsWords"; + +// The channel-wide media operations that were CLI-only (release 32 R6), beside +// the saved-video store they write into: +// +// Attach media from a local archive `archilyzer media attach <slug> +// <source>` — every held video's file out of a directory, a .zip or a +// .7z into the store (`--match`, `--create-records`, `--replace`) +// Playable copies `archilyzer media playable <slug>` — +// every saved container remuxed to a browser-playable copy with its +// torrent (`--trackers`, `--root`) +// +// Each previews first (the job's dry run, which writes nothing) and the run is +// armed by a preview of the same settings. Both jobs end their log with a +// `summary: {json}` line: the result is said from it in plain words, and the +// job is linked. + +function Outcome({ label, jobId, lines }: { label: string; jobId: string | null; lines: string[] | null }) { + return ( + <div role="status" aria-label={label} className="flex flex-col gap-0.5 text-sm"> + {lines ? lines.map((l) => <p key={l}>{l}</p>) : <p className="text-muted-foreground">The job left no summary; see its log.</p>} + {jobId && ( + <p className="text-xs text-muted-foreground"> + <Link href={`/jobs/${jobId}`} className="underline font-mono"> + job {jobId} + </Link> + </p> + )} + </div> + ); +} + +export function ChannelMediaTools({ slug }: { slug: string }) { + return ( + <details aria-label="channel media tools" className="rounded border border-border p-3"> + <summary className="cursor-pointer text-sm font-semibold">Media for the whole channel</summary> + <div className="mt-3 flex flex-col gap-5"> + <AttachArchive slug={slug} /> + <PlayableCopies slug={slug} /> + </div> + </details> + ); +} + +function AttachArchive({ slug }: { slug: string }) { + const [source, setSource] = useState(""); + const [match, setMatch] = useState(""); + const [createRecords, setCreateRecords] = useState(false); + const [replace, setReplace] = useState(false); + const key = JSON.stringify([source.trim(), match.trim(), createRecords, replace]); + const [previewed, setPreviewed] = useState<string | null>(null); + const [out, setOut] = useState<{ what: "preview" | "run"; jobId: string | null; lines: string[] | null } | null>(null); + const opts = (dryRun: boolean) => ({ + source: source.trim(), + ...(match.trim() ? { match: match.trim() } : {}), + ...(createRecords ? { createRecords: true } : {}), + ...(replace ? { replace: true } : {}), + ...(dryRun ? { dryRun: true } : {}), + }); + const settle = (what: "preview" | "run") => (started: boolean, o: { log: string; jobId: string | null }) => { + if (!started) return; + const s = readResultMarker<AttachSummary>(o.log, MEDIA_SUMMARY_MARKER); + setOut({ what, jobId: o.jobId, lines: s ? attachSummaryWords(s) : null }); + if (what === "preview") setPreviewed(key); + }; + return ( + <div className="flex flex-col gap-2" aria-label="attach media from a local archive"> + <h4 className="text-sm font-semibold">Attach media from a local archive</h4> + <p className="text-xs text-muted-foreground"> + Every video this channel holds gets its file from the archive — matched by the id in the folder or file name — + copied into the saved-video store with where it came from. Nothing is downloaded. + </p> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Archive (absolute path: a folder, a .zip or a .7z)</span> + <input + value={source} + onChange={(e) => setSource(e.target.value)} + aria-label="archive path" + placeholder="/mnt/archive/channel-backup.zip" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-96 max-w-full" + /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Only names matching (optional regex)</span> + <input + value={match} + onChange={(e) => setMatch(e.target.value)} + aria-label="attach files matching" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-56 max-w-full" + /> + </label> + </div> + <div className="flex flex-wrap gap-4 text-sm"> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={createRecords} onChange={(e) => setCreateRecords(e.target.checked)} /> + Create records for videos the channel does not hold + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} /> + Replace files already saved + </label> + </div> + <StreamActionLog + trigger={() => attachMediaAction(slug, opts(true))} + cancelAction={cancelJobAction} + buttonLabel="Preview attach" + runningLabel="Reading the archive…" + label={`Preview attach into ${slug}`} + disabled={!source.trim()} + onSettled={settle("preview")} + /> + <StreamActionLog + trigger={() => attachMediaAction(slug, opts(false))} + cancelAction={cancelJobAction} + buttonLabel="Attach" + runningLabel="Attaching…" + label={`Attach media into ${slug}`} + disabled={previewed !== key} + onSettled={settle("run")} + /> + {previewed !== key && <p className="text-xs text-muted-foreground">Preview these settings first.</p>} + {out && <Outcome label={out.what === "preview" ? "attach preview" : "attach result"} jobId={out.jobId} lines={out.lines} />} + </div> + ); +} + +function PlayableCopies({ slug }: { slug: string }) { + const [trackers, setTrackers] = useState(""); + const [root, setRoot] = useState(""); + const trackerList = trackers + .split(/[\s,]+/) + .map((t) => t.trim()) + .filter(Boolean); + const key = JSON.stringify([trackerList, root.trim()]); + const [previewed, setPreviewed] = useState<string | null>(null); + const [out, setOut] = useState<{ what: "preview" | "run"; jobId: string | null; lines: string[] | null } | null>(null); + const opts = (dryRun: boolean) => ({ + ...(trackerList.length > 0 ? { trackers: trackerList } : {}), + ...(root.trim() ? { root: root.trim() } : {}), + ...(dryRun ? { dryRun: true } : {}), + }); + const settle = (what: "preview" | "run") => (started: boolean, o: { log: string; jobId: string | null }) => { + if (!started) return; + const s = readResultMarker<PlayableSummary>(o.log, MEDIA_SUMMARY_MARKER); + setOut({ what, jobId: o.jobId, lines: s ? playableSummaryWords(s) : null }); + if (what === "preview") setPreviewed(key); + }; + return ( + <div className="flex flex-col gap-2" aria-label="playable copies"> + <h4 className="text-sm font-semibold">Playable copies</h4> + <p className="text-xs text-muted-foreground"> + Every saved container is copied, without re-encoding, into a file a browser can play (mp4 or webm), each with + a torrent. A copy already made from the same file is skipped. + </p> + <div className="flex flex-wrap gap-3 text-sm"> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Trackers (optional, comma or space separated)</span> + <input + value={trackers} + onChange={(e) => setTrackers(e.target.value)} + aria-label="torrent trackers" + placeholder="wss://tracker.example/announce" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-96 max-w-full" + /> + </label> + <label className="flex flex-col gap-0.5"> + <span className="text-xs text-muted-foreground">Folder (optional absolute path; default beside the store)</span> + <input + value={root} + onChange={(e) => setRoot(e.target.value)} + aria-label="playable folder" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono w-72 max-w-full" + /> + </label> + </div> + <StreamActionLog + trigger={() => preparePlayableAction(slug, opts(true))} + cancelAction={cancelJobAction} + buttonLabel="Preview playable copies" + runningLabel="Checking…" + label={`Preview playable copies of ${slug}`} + onSettled={settle("preview")} + /> + <StreamActionLog + trigger={() => preparePlayableAction(slug, opts(false))} + cancelAction={cancelJobAction} + buttonLabel="Make playable copies" + runningLabel="Remuxing…" + label={`Playable copies of ${slug}`} + disabled={previewed !== key} + onSettled={settle("run")} + /> + {previewed !== key && <p className="text-xs text-muted-foreground">Preview these settings first.</p>} + {out && <Outcome label={out.what === "preview" ? "playable preview" : "playable result"} jobId={out.jobId} lines={out.lines} />} + </div> + ); +} diff --git a/editor/app/channels/[slug]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { KeepMatchingControl } from "../KeepMatchingControl"; +import { ChannelMediaTools } from "../ChannelMediaTools"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { QueueControl } from "../../../../components/QueueControl"; @@ -82,6 +83,7 @@ export function CleanupStage({ defaultQueueKey={defaultQueueKey} /> )} + <ChannelMediaTools slug={slug} /> {diarizationEnabled && ( <div className="flex flex-col gap-2"> <Heading diff --git a/editor/app/channels/[slug]/lib/mediaToolsWords.test.ts b/editor/app/channels/[slug]/lib/mediaToolsWords.test.ts @@ -0,0 +1,39 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { attachSummaryWords, playableSummaryWords } from "./mediaToolsWords"; + +// Run with: pnpm -C editor exec tsx --test "app/channels/*/lib/mediaToolsWords.test.ts" + +const attach = { + dryRun: true, + counts: { attach: 2, create: 1 }, + attached: 0, + created: [], + failed: [], + notHeld: ["x9"], + lost: 0, + unmatched: [], + ambiguous: [], + alreadyAttached: 1, + heldWithoutMedia: [], +}; + +test("an attach preview and run, said in plain words", () => { + assert.deepEqual(attachSummaryWords(attach), [ + "Would attach 2 held videos and write 1 new record.", + "1 video already had a saved file (left alone; tick Replace to swap).", + "1 file for videos this channel does not hold (tick Create records to add them).", + ]); + const run = attachSummaryWords({ ...attach, dryRun: false, attached: 1, created: [], alreadyAttached: 0, notHeld: [], failed: [{ id: "a1", error: "disk" }], stopped: "low-disk" }); + assert.deepEqual(run, ["Attached 1 video.", "1 video failed: a1 (disk).", "Stopped (low-disk): run it again to continue."]); +}); + +test("a playable preview and run, said in plain words", () => { + const s = { dryRun: true, root: "/store/playable", prepared: 1, unchanged: 2, unplayable: [{ id: "v1", reason: "hevc in webm" }], noContainer: [], failed: [] }; + assert.deepEqual(playableSummaryWords(s), [ + "Would make 1 playable copy; 2 already up to date.", + "Under /store/playable.", + "1 video cannot be made playable without re-encoding: v1 (hevc in webm).", + ]); + assert.match(playableSummaryWords({ ...s, dryRun: false, prepared: 3, unplayable: [] })[0]!, /^Made 3 playable copies with their torrents/); +}); diff --git a/editor/app/channels/[slug]/lib/mediaToolsWords.ts b/editor/app/channels/[slug]/lib/mediaToolsWords.ts @@ -0,0 +1,75 @@ +// The channel media tools' results in plain words (release 32 R6, +// components/ChannelMediaTools.tsx): an attach-media or prepare-playable job's +// `summary: {json}` line, said as sentences. Client-safe and pure. + +// The last line of an attach-media and a prepare-playable job's log +// (controller/attachMedia.ts summaryOf, controller/preparePlayable.ts). +export const MEDIA_SUMMARY_MARKER = "summary: "; + +export type AttachSummary = { + dryRun: boolean; + counts: Record<string, number>; + attached: number; + created: string[]; + failed: { id: string; error: string }[]; + notHeld: string[]; + lost: number; + unmatched: string[]; + ambiguous: string[]; + alreadyAttached: number; + heldWithoutMedia: string[] | null; + stopped?: string; +}; + +export type PlayableSummary = { + dryRun: boolean; + root: string; + prepared: number; + unchanged: number; + unplayable: { id: string; reason: string }[]; + noContainer: string[]; + failed: { id: string; error: string }[]; + stopped?: string; +}; + +const n = (k: number, one: string, many = `${one}s`) => `${k} ${k === 1 ? one : many}`; + +export function attachSummaryWords(s: AttachSummary): string[] { + const c = s.counts ?? {}; + const lines: string[] = []; + if (s.dryRun) { + lines.push( + `Would attach ${n(c.attach ?? 0, "held video")}` + + ((c.create ?? 0) > 0 ? ` and write ${n(c.create ?? 0, "new record")}` : "") + + ".", + ); + } else { + lines.push( + `Attached ${n(s.attached, "video")}` + (s.created.length > 0 ? ` (${n(s.created.length, "new record")})` : "") + ".", + ); + } + if (s.alreadyAttached > 0) lines.push(`${n(s.alreadyAttached, "video")} already had a saved file (left alone; tick Replace to swap).`); + if (s.notHeld.length > 0) lines.push(`${n(s.notHeld.length, "file")} for videos this channel does not hold (tick Create records to add them).`); + if (s.unmatched.length > 0) lines.push(`${n(s.unmatched.length, "file")} with no video id in the name.`); + if (s.ambiguous.length > 0) lines.push(`${n(s.ambiguous.length, "video")} with more than one candidate file: ${s.ambiguous.slice(0, 5).join(", ")}${s.ambiguous.length > 5 ? "…" : ""}.`); + if (s.lost > 0) lines.push(`${n(s.lost, "folder")} marked lost (never attached).`); + if (s.heldWithoutMedia && s.heldWithoutMedia.length > 0) lines.push(`${n(s.heldWithoutMedia.length, "held video")} with no file in the archive.`); + if (s.failed.length > 0) lines.push(`${n(s.failed.length, "video")} failed: ${s.failed.slice(0, 3).map((f) => `${f.id} (${f.error})`).join("; ")}.`); + if (s.stopped) lines.push(`Stopped (${s.stopped}): run it again to continue.`); + return lines; +} + +export function playableSummaryWords(s: PlayableSummary): string[] { + const lines = [ + s.dryRun + ? `Would make ${n(s.prepared, "playable copy", "playable copies")}; ${s.unchanged} already up to date.` + : `Made ${n(s.prepared, "playable copy", "playable copies")} with their torrents; ${s.unchanged} already up to date.`, + `Under ${s.root}.`, + ]; + if (s.unplayable.length > 0) lines.push(`${n(s.unplayable.length, "video")} cannot be made playable without re-encoding: ${s.unplayable.slice(0, 3).map((u) => `${u.id} (${u.reason})`).join("; ")}.`); + if (s.noContainer.length > 0) lines.push(`${n(s.noContainer.length, "video")} with no saved container.`); + if (s.failed.length > 0) lines.push(`${n(s.failed.length, "video")} failed: ${s.failed.slice(0, 3).map((f) => `${f.id} (${f.error})`).join("; ")}.`); + if (s.stopped) lines.push(`Stopped (${s.stopped}): run it again to continue.`); + return lines; +} + diff --git a/editor/app/saved-videos/components/PersistVideoListControl.tsx b/editor/app/saved-videos/components/PersistVideoListControl.tsx @@ -0,0 +1,136 @@ +"use client"; + +import Link from "next/link"; +import { useState, useTransition } from "react"; +import { Button } from "yt-dlp-transcript-common/components/ui/button"; +import { SOURCE_VIDEO_QUALITY_LABELS } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; +import type { PersistVideosActionResult } from "../../channels/[slug]/persistActions"; +import { persistVideoListAction } from "../persistListAction"; + +// "Save these videos" (release 32 R6): `pnpm ops persist-videos` from the UI — +// a list of videos across channels saved to this store. Preview says what a run +// would do with each (the plan's buckets) and starts nothing; Save is armed by +// a preview of the same list and settings, and links the job per channel. + +type Format = "" | "original" | "video_720"; + +const sameKey = (text: string, format: Format, replace: boolean) => JSON.stringify([text.trim(), format, replace]); + +export function PersistVideoListControl() { + const [text, setText] = useState(""); + const [format, setFormat] = useState<Format>(""); + const [replace, setReplace] = useState(false); + const [previewed, setPreviewed] = useState<string | null>(null); + const [result, setResult] = useState<PersistVideosActionResult | null>(null); + const [pending, start] = useTransition(); + const key = sameKey(text, format, replace); + const run = (dryRun: boolean) => + start(async () => { + const r = await persistVideoListAction({ + text, + ...(format ? { format } : {}), + ...(replace ? { replace: "above-height" as const } : {}), + dryRun, + }); + setResult(r); + if (dryRun && r.ok) setPreviewed(key); + }); + return ( + <section aria-label="save these videos" className="flex flex-col gap-2 rounded border border-border p-3"> + <h2 className="text-base font-semibold">Save these videos</h2> + <p className="text-xs text-muted-foreground"> + One per line: <span className="font-mono">channel/video-id</span>, or a video page&apos;s link. Each channel&apos;s + videos are downloaded whole into the store, paced like any download; a video already saved is skipped. + </p> + <textarea + value={text} + onChange={(e) => setText(e.target.value)} + aria-label="videos to save" + rows={5} + placeholder={"demo-channel/dQw4w9WgXcQ\nother-channel/abc123"} + className="rounded border border-border bg-card px-2 py-1 font-mono text-sm" + /> + <div className="flex flex-wrap items-center gap-4 text-sm"> + <label className="flex items-center gap-2"> + <span className="text-muted-foreground">Quality</span> + <select + value={format} + onChange={(e) => setFormat(e.target.value as Format)} + aria-label="quality to save" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="">each channel&apos;s own</option> + <option value="original">{SOURCE_VIDEO_QUALITY_LABELS.original}</option> + <option value="video_720">{SOURCE_VIDEO_QUALITY_LABELS.video_720}</option> + </select> + </label> + <label className="flex items-center gap-2"> + <input type="checkbox" checked={replace} onChange={(e) => setReplace(e.target.checked)} /> + Also replace a saved one taller than that quality, or of unknown height + </label> + </div> + <div className="flex flex-wrap items-center gap-2"> + <Button type="button" variant="outline" disabled={pending || !text.trim()} onClick={() => run(true)}> + Preview + </Button> + <Button type="button" disabled={pending || previewed !== key} onClick={() => run(false)}> + {pending ? "Working…" : "Save videos"} + </Button> + {previewed !== key && <span className="text-xs text-muted-foreground">Preview this list first.</span>} + </div> + {result && <PersistOutcome result={result} />} + </section> + ); +} + +const BUCKETS: { key: "saved" | "toFetch" | "wrongHeight" | "noUrl" | "unknown"; words: string }[] = [ + { key: "toFetch", words: "to download" }, + { key: "saved", words: "already saved" }, + { key: "wrongHeight", words: "saved, but taller than asked or of unknown height" }, + { key: "noUrl", words: "with no source address to download from" }, + { key: "unknown", words: "not found (no such channel or video)" }, +]; + +function PersistOutcome({ result }: { result: PersistVideosActionResult }) { + if (!result.ok) { + return ( + <p role="alert" className="text-sm text-destructive"> + {result.error} + </p> + ); + } + const plan = result.plan; + return ( + <div role="status" aria-label={result.dryRun ? "save preview" : "save result"} className="flex flex-col gap-1 text-sm"> + <p> + {result.dryRun ? "A run would download " : "Downloading "} + {plan.willFetch} video{plan.willFetch === 1 ? "" : "s"}. + </p> + <ul className="list-disc pl-5 text-muted-foreground"> + {BUCKETS.filter((b) => plan[b.key].count > 0).map((b) => ( + <li key={b.key} data-bucket={b.key}> + {plan[b.key].count} {b.words} + {plan[b.key].count <= 8 && ( + <span className="font-mono text-xs"> — {plan[b.key].items.map((i) => `${i.slug}/${i.id}`).join(", ")}</span> + )} + </li> + ))} + </ul> + {!result.dryRun && + result.jobs.map((j) => ( + <p key={j.jobId}> + {j.slug}:{" "} + <Link href={`/jobs/${j.jobId}`} className="font-mono underline"> + job {j.jobId} + </Link> + </p> + ))} + {!result.dryRun && + result.skipped.map((s) => ( + <p key={s.slug} className="text-destructive"> + {s.slug}: not started — {s.reason} + </p> + ))} + </div> + ); +} diff --git a/editor/app/saved-videos/lib/videoList.test.ts b/editor/app/saved-videos/lib/videoList.test.ts @@ -0,0 +1,35 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { parseVideoList } from "./videoList"; + +// Run with: pnpm -C editor exec tsx --test "app/saved-videos/lib/videoList.test.ts" + +test("slug/id, slug id, slug,id and an editor video link; blanks and # comments skipped; repeats once", () => { + const r = parseVideoList( + [ + "demo-channel/dQw4w9WgXcQ", + " other-chan abc_123 ", + "", + "# a comment", + "third,v-1.2", + "http://localhost:3001/channels/demo-channel/videos/dQw4w9WgXcQ?tab=x", + "https://editor.example/channels/fourth/videos/zz9", + ].join("\n"), + ); + assert.deepEqual(r.items, [ + { slug: "demo-channel", id: "dQw4w9WgXcQ" }, + { slug: "other-chan", id: "abc_123" }, + { slug: "third", id: "v-1.2" }, + { slug: "fourth", id: "zz9" }, + ]); + assert.deepEqual(r.bad, []); +}); + +test("a line that names no channel and video is reported with its line number", () => { + const r = parseVideoList("ok/one\njust-one-word\na b c\n../etc passwd\nhttps://youtube.com/watch?v=x"); + assert.deepEqual(r.items, [{ slug: "ok", id: "one" }]); + assert.deepEqual( + r.bad.map((b) => b.line), + [2, 3, 4, 5], + ); +}); diff --git a/editor/app/saved-videos/lib/videoList.ts b/editor/app/saved-videos/lib/videoList.ts @@ -0,0 +1,49 @@ +// A LIST OF VIDEOS, typed or pasted (release 32 R6: the Saved videos page's +// "Save these videos", `pnpm ops persist-videos` from the UI). One video per +// line, any of: +// +// <slug>/<id> demo-channel/dQw4w9WgXcQ +// <slug> <id> <slug>,<id> (space, tab or comma between) +// an editor video link http://localhost:3001/channels/demo-channel/videos/dQw4w9WgXcQ +// +// Blank lines and lines starting with # are skipped; a repeat is listed once. +// Pure: the action checks the channels and the records. + +export type ListedVideo = { slug: string; id: string }; +export type VideoListParse = { items: ListedVideo[]; bad: { line: number; text: string }[] }; + +const NAME = /^[\w.-]+$/; +const ok = (v: string) => NAME.test(v) && v !== "." && v !== ".."; + +function one(raw: string): ListedVideo | null { + const link = /\/channels\/([^/\s?#]+)\/videos\/([^/\s?#]+)/.exec(raw); + if (link) { + const slug = decodeURIComponent(link[1]!); + const id = decodeURIComponent(link[2]!); + return ok(slug) && ok(id) ? { slug, id } : null; + } + const parts = raw.split(/[\s,/]+/).filter(Boolean); + if (parts.length !== 2) return null; + const [slug, id] = parts as [string, string]; + return ok(slug) && ok(id) ? { slug, id } : null; +} + +export function parseVideoList(text: string): VideoListParse { + const items: ListedVideo[] = []; + const bad: { line: number; text: string }[] = []; + const seen = new Set<string>(); + text.split(/\r?\n/).forEach((l, i) => { + const raw = l.trim(); + if (!raw || raw.startsWith("#")) return; + const v = one(raw); + if (!v) { + bad.push({ line: i + 1, text: raw }); + return; + } + const key = `${v.slug}/${v.id}`; + if (seen.has(key)) return; + seen.add(key); + items.push(v); + }); + return { items, bad }; +} diff --git a/editor/app/saved-videos/page.tsx b/editor/app/saved-videos/page.tsx @@ -6,6 +6,7 @@ import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { listSavedVideos } from "yt-dlp-transcript-common/controller/savedVideoInventory"; import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState"; import { SavedVideosControls } from "./components/SavedVideosControls"; +import { PersistVideoListControl } from "./components/PersistVideoListControl"; export const dynamic = "force-dynamic"; @@ -95,6 +96,8 @@ export default async function SavedVideosPage() { </div> </section> + <PersistVideoListControl /> + <section aria-label="per-channel saved videos" className="flex flex-col gap-2"> <h2 className="text-base font-semibold">By channel</h2> {notAnswering.length > 0 && ( diff --git a/editor/app/saved-videos/persistListAction.ts b/editor/app/saved-videos/persistListAction.ts @@ -0,0 +1,43 @@ +"use server"; + +import { persistVideosAction, type PersistVideosActionResult } from "../channels/[slug]/persistActions"; +import type { PersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; +import { isSourceVideoQuality, type SourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; +import { parseVideoList } from "./lib/videoList"; + +// "Save these videos" on the Saved videos page (release 32 R6): `pnpm ops +// persist-videos` from the UI. The typed list is read (lib/videoList.ts) and +// handed to persistVideosAction as the ops route hands it: a preview answers +// with the plan's buckets and starts nothing; a run starts one persist-videos +// job per channel with something to fetch. +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +export async function persistVideoListAction(input: { + text: string; + format?: string; + replace?: PersistReplacePolicy; + dryRun: boolean; +}): Promise<PersistVideosActionResult> { + const { items, bad } = parseVideoList(input.text); + if (bad.length > 0) { + return { + ok: false, + error: + `${bad.length} line(s) name no channel and video (slug/id, or a video page link): ` + + bad + .slice(0, 5) + .map((b) => `line ${b.line} "${b.text.slice(0, 60)}"`) + .join(", ") + + (bad.length > 5 ? "…" : ""), + }; + } + if (items.length === 0) return { ok: false, error: "No videos listed." }; + const format: SourceVideoQuality | undefined = isSourceVideoQuality(input.format) ? input.format : undefined; + return persistVideosAction({ + items, + dryRun: input.dryRun, + ...(format ? { format } : {}), + ...(input.replace === "above-height" ? { replace: "above-height" as const } : {}), + }); +}