Archilyzer · Source

archilyzer

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

commit e9877855e779c7bce967ee8da72c838a87a5b96c
parent 0322c2868ab9d58a8f1a2fc11023f38e7d186111
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 21:16:41 -0500

Merge lane/editor-gaps: pnpm ops create-site and channel-rank, transcribe-one refuses a live stream's download, subLangs checked at the save, deleting a channel takes it off every site (overnight E2; owed CLI gaps, 25 Oct-9 Nov)

create-site is the New site form over HTTP (private and unlisted by default; "update": true is the site page's Save with
only the given keys changed) -- on 9 Nov an agent had to call writeSite from a script to make efapalyzer. channel-rank
moves one channel in the order the lanes follow, nothing else. transcribe-one refuses the audio download of a video that
is live, upcoming or still processing (captions still fetched), naming record-live and refresh-metadata. A delete drops
the slug from every site's pool and cited scope. Every read-modify-write here holds its file's lock (site, settings).

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

Diffstat:
MCOMMANDS.md | 6++++--
MOPERATING.md | 9++++++++-
Acommon/controller/siteMemberships.test.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/siteMemberships.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 38++++++++++++++++++++++++++++++++++++++
Mcommon/lib/channelPriority.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/channelRank.test.ts | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/liveNow-server.ts | 25+++++++++++++++++++++++++
Acommon/lib/liveNow.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/liveNow.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/site.ts | 16+++++++++++++++-
Acommon/lib/subLangs.test.ts | 22++++++++++++++++++++++
Meditor/CHANGELOG.md | 5+++++
Aeditor/app/api/ops/channel-rank/route.test.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/channel-rank/route.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/create-site/route.test.ts | 221+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/create-site/route.ts | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/delete-channel/route.ts | 12+++++++++++-
Meditor/app/api/ops/transcribe-one/route.test.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 45+++++++++++++++++++++++++++++++--------------
Meditor/app/channels/actions.ts | 238+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Meditor/app/channels/components/parseChannelForm.test.ts | 25+++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 34+++++++++++++++++++++++++++++++---
Meditor/app/settings/saveSettings.test.ts | 25++++++++++++++++++++++++-
Meditor/app/settings/saveSettings.ts | 22+++++++++++++++++++++-
Meditor/app/sites/actions.ts | 311+++----------------------------------------------------------------------------
Aeditor/app/sites/lib/saveSiteForm.ts | 317+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/sites/lib/siteFormData.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/ops-api.spec.ts | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 52++++++++++++++++++++++++++++++++++++++++++++++++++--
30 files changed, 2123 insertions(+), 411 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -123,7 +123,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | action | what it does | example | |---|---|---| | `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` | +| `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": &lt;n&gt; (before any channel holding it) or null (unranked), "top": true, "bottom": true, "before": "&lt;slug&gt;", "after": "&lt;slug&gt;" (a ranked channel; immediately next to it, a tie on its rank included). The channels after it move down only as far as they must. Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` | | `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "&lt;slug&gt;, &lt;slug&gt;"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | +| `create-site` | create-site is the New site form: {"siteId", "siteTitle"} and any of its fields — "headerTitle" (default the title), "siteDescription", "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl", "cloudflareProject", "hubUrl", "audience" ("private" \| "public"; default PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the global default), "groups" (\[{"id", "name", "selectedByDefault"?, "description"?, "inline"?}\]), "defaultGroupId", "channels" (slugs, or {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks" (\[{"label", "url", "svg"}\], null = inherit), "relatedSites". Saved by the form's action (its validation, its sentences). An existing id is refused (409) unless "update": true — the site page's Save with the keys given changed, every other key kept — one read-modify-write under the site's lock. An unknown channel, or a channel's groupId naming no group of the site, is refused. Answers {siteId, created, site}. | `pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'`<br>`pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'` | | `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` | | `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` | | `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` | @@ -131,7 +133,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/&lt;id&gt;/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/&lt;id&gt;/) and compose's staging for it (export/.export-index/sites/&lt;id&gt;/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` | | `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'` | | `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` | -| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | +| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose pool or cited scope names it is rewritten without it (answered as "sitesUpdated"; a site whose write is refused is a "warnings" line). No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | | `metadata-scan` | metadata-scan reads every listed video's title, date and description into the channel's scan file, fetching no media: {"slug"}. Not held by the download pause and needs no disk floor; one request per video, so it respects the platform's cooldown and records one when pushed back. | `pnpm ops metadata-scan --json '{"slug":"the-quartering"}'` | | `refresh-metadata` | refresh-metadata re-reads ONE video's metadata.info.json from its source (no subtitles, no media) on the platform's queue: {"slug", "id"}. The job's log ends with what the source now says — live\_status, formats, audio-only formats and whether any is non-fragmented, English captions, the keys that changed. An id with no data/&lt;id&gt;/ is refused (a refresh re-reads a video already archived), as are archive.org and Wayback records. | `pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait` | | `browser-lookup` | browser-lookup reads Odysee records from their pages in a headless browser, for when yt-dlp's lookup answers 429: {"slug", "ids": \[...\]} (at most 50) writes each record (none yet: whole, `_source: "browser"`) or completes it (the keys it lacks, and the one media file the page's player asked for); "listing": true (with "scrolls", default 5, at most 40) adds the uploads the channel page shows to the playlist, newest first, through the title match filter. One page a minute; not refused for a held platform. The log ends with a `summary: {...}` line. | `pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait`<br>`pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait` | @@ -184,7 +186,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `dismiss-service` | — | | | `rerun-service-jobs` | — | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | -| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). | | +| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. | | diff --git a/OPERATING.md b/OPERATING.md @@ -60,7 +60,14 @@ pnpm ops get channel example stops the listing but not the backlog, and a `paused` tier stops every lane, transcription too. - `"fetchPlaylist": true` on `create-channel` stores the playlist at once (the form's "Fetch playlist now"); a social channel's is `"fetchPostsNow": true`. - Rename or delete: `pnpm ops rename-channel --json '{"slug":"old","newSlug":"new"}'`, - `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` — both refused while the channel is busy. + `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` — both refused while the channel is busy. A delete + takes the channel off every site that names it (pool and cited scope) and says which (`sitesUpdated`). +- A site for it: `pnpm ops create-site --json '{"siteId":"example","siteTitle":"Examplealyzer","channels":["example"]}'` + — the New site form, private and unlisted unless `"audience": "public"` / `"listed": true`. An existing id is + refused; `"update": true` is the site page's Save with the keys given changed, every other key kept. +- Its place in the queue: `pnpm ops channel-rank --json '{"slug":"example","top":true}'` (or `"bottom"`, + `"before"`/`"after": "<slug>"`, `"rank": <n>`, `"rank": null`) — the rank alone; /channels' "Add to top" also + sets the tier to normal and turns the download lane on. ## Archive a new creator end to end, without interruptions diff --git a/common/controller/siteMemberships.test.ts b/common/controller/siteMemberships.test.ts @@ -0,0 +1,56 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { writeSite, type Site } from "../lib/site"; +import { dropChannelFromSites } from "./siteMemberships"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/siteMemberships.test.ts +// +// A deleted channel leaves no site naming it (9 Nov: `mooler` stayed in +// efapalyzer's pool): the pool and the cited scope drop it, through writeSite; +// a site that does not name it is not written. + +const site = (siteId: string, extra: Partial<Site> = {}): Site => ({ + siteId, + siteTitle: siteId, + siteDescription: "", + headerTitle: siteId, + homeTagline: "", + groups: [{ id: "default", name: "All", selectedByDefault: true }], + defaultGroupId: "default", + channels: [], + ...extra, +}); + +test("drops the slug from every pool and cited scope; leaves other sites unwritten", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "ttb-site-drop-")); + const paths = { sitesDir: path.join(dir, "sites"), channelsDir: path.join(dir, "channels") } as Paths; + const file = (id: string) => path.join(paths.sitesDir, id, "site.json"); + const read = async (id: string) => JSON.parse(await readFile(file(id), "utf8")) as Site; + try { + await writeSite(site("pool", { channels: [{ slug: "gone", order: 0 }, { slug: "kept", groupId: "default", order: 1 }] }), paths); + await writeSite(site("cites", { citedChannels: [{ slug: "gone" }, { slug: "other" }] }), paths); + await writeSite(site("only-cites", { citedChannels: [{ slug: "gone" }] }), paths); + await writeSite(site("untouched", { channels: [{ slug: "kept", order: 0 }] }), paths); + const untouchedAt = (await stat(file("untouched"))).mtimeMs; + + const r = await dropChannelFromSites(paths, "gone"); + assert.deepEqual(r, { updated: ["cites", "only-cites", "pool"], failed: [] }); + assert.deepEqual((await read("pool")).channels, [{ slug: "kept", groupId: "default", order: 1 }]); + assert.deepEqual((await read("cites")).citedChannels, [{ slug: "other" }]); + assert.equal("citedChannels" in (await read("only-cites")), false, "an empty scope is not written"); + assert.equal((await stat(file("untouched"))).mtimeMs, untouchedAt, "a site not naming it is not written"); + + assert.deepEqual(await dropChannelFromSites(paths, "gone"), { updated: [], failed: [] }, "a second pass finds none"); + assert.deepEqual(await dropChannelFromSites({ ...paths, sitesDir: path.join(dir, "none") }, "gone"), { + updated: [], + failed: [], + }); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/siteMemberships.ts b/common/controller/siteMemberships.ts @@ -0,0 +1,48 @@ +import type { Paths } from "../lib/paths"; +import { getSite, listSiteIds, patchSite, type Site } from "../lib/site"; + +// A DELETED CHANNEL LEAVES NO SITE NAMING IT (lane editor-gaps; 9 Nov: +// deleting `mooler` left it in efapalyzer's site.json, fixed by hand). Every +// site's pool (`channels`) and cited scope (`citedChannels`) drop the slug, +// through the one site writer (writeSite), the way a rename re-points them +// (renameChannel.ts, step 5), each as a patchSite under the site's lock. A +// site that does not name it is not written. +// +// Best-effort per site, because the channel is already gone: a site whose +// write is refused (its own file no longer valid) is named in `failed` with +// the writer's sentence and the others still go through. +export type SiteDropResult = { + updated: string[]; + failed: { siteId: string; error: string }[]; +}; + +export async function dropChannelFromSites(paths: Paths, slug: string): Promise<SiteDropResult> { + const result: SiteDropResult = { updated: [], failed: [] }; + for (const siteId of [...listSiteIds(paths)].sort()) { + try { + // A cheap look first, so a site that does not name it is not written; + // the edit itself is a patch, read again INSIDE the site's lock, so a + // concurrent edit of the site (a Reports-tab pages patch) is not + // written over with this copy. + if (!namesChannel(getSite(siteId, paths), slug)) continue; + const saved = await patchSite( + siteId, + (current) => ({ + channels: current.channels.filter((c) => c.slug !== slug), + citedChannels: (current.citedChannels ?? []).filter((c) => c.slug !== slug), + }), + paths, + ); + if (saved) result.updated.push(siteId); + } catch (err) { + result.failed.push({ siteId, error: (err as Error).message }); + } + } + return result; +} + +function namesChannel(site: Site, slug: string): boolean { + return ( + site.channels.some((c) => c.slug === slug) || (site.citedChannels ?? []).some((c) => c.slug === slug) + ); +} diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -144,6 +144,44 @@ export function isDownloadMode(v: unknown): v is DownloadMode { // yt-dlp's `--sub-langs` when the channel names none. export const DEFAULT_SUB_LANGS = "en.*,live_chat"; +// THE FORM'S CHECK OF A `subLangs` VALUE. yt-dlp splits `--sub-langs` on +// commas and matches each entry — a regex, or `all` — against a track's +// language; a leading `-` excludes. A value it cannot use fails every caption +// download on the channel at the moment it runs, so Configure and +// `channel-config` refuse it at the save instead: an empty entry (two commas, +// or one at an end), a space inside an entry, an entry that is not a regular +// expression, a value over 200 characters. Spaces AROUND an entry are not a +// problem: `normalizeSubLangs` drops them. +export const SUB_LANGS_MAX_LENGTH = 200; + +export function normalizeSubLangs(value: string): string { + return value + .split(",") + .map((x) => x.trim()) + .join(","); +} + +export function subLangsProblem(value: string): string | null { + const v = normalizeSubLangs(value.trim()); + if (!v) return null; + if (v.length > SUB_LANGS_MAX_LENGTH) { + return `is ${v.length} characters; at most ${SUB_LANGS_MAX_LENGTH}`; + } + for (const entry of v.split(",")) { + if (!entry) return `has an empty entry (two commas, or one at an end)`; + if (/\s/.test(entry)) return `entry "${entry}" has a space in it — entries are separated by commas`; + const pattern = entry.startsWith("-") ? entry.slice(1) : entry; + if (!pattern) return `entry "-" excludes nothing — a "-" goes before a language, e.g. -live_chat`; + if (pattern === "all") continue; + try { + new RegExp(`^(?:${pattern})$`); + } catch (e) { + return `entry "${entry}" is not a valid regular expression: ${(e as Error).message}`; + } + } + return null; +} + // The `--sub-langs` a caption download passes: the channel's (or the // default), WITHOUT the live chat unless `chat` fetches it with the download. // An entry that is `live_chat` itself is dropped; one that would still match diff --git a/common/lib/channelPriority.ts b/common/lib/channelPriority.ts @@ -635,6 +635,113 @@ export function renameChannelInPriority( return { focus, channels }; } +// --- Placing one channel's rank --------------------------------------------- + +// WHERE A CHANNEL GOES IN THE ORDER (`pnpm ops channel-rank`). The model has +// ONE rank per channel, ascending, unranked after every ranked channel (then by +// slug) — the same order inside every tier group (`orderWithin`). A placement +// moves one channel and leaves the order of every other exactly as it was: +// +// rank n the channel takes rank n, before any channel holding it; +// top / bottom before every ranked channel / after every ranked channel; +// before / after immediately before / after another RANKED channel, a tie +// on its rank included (an unranked one has no place to be +// next to — refused); +// unrank the rank removed: last in its tier, by slug. +// +// Only the rank moves. Unlike "Add to top" (the deck's promote, which also +// sets the tier to normal and turns the download lane on), a placement never +// changes a tier, an override, a focus or an auto-pause. +export type RankPlacement = + | { kind: "rank"; rank: number } + | { kind: "top" } + | { kind: "bottom" } + | { kind: "before"; slug: string } + | { kind: "after"; slug: string } + | { kind: "unrank" }; + +// A placement the document cannot carry out, in the words the caller sees. +export class RankPlacementError extends Error {} + +export function placeChannelRank( + model: ChannelPriority, + rawSlug: string, + place: RankPlacement, +): ChannelPriority { + const slug = rawSlug.trim(); + if (!slug) throw new RankPlacementError("No channel slug supplied."); + const current = model.channels[slug]; + if (place.kind === "unrank") { + if (current?.rank === undefined) return model; + const { rank: _dropped, ...rest } = current; + return { ...model, channels: { ...model.channels, [slug]: rest } }; + } + // The other ranked channels in the order the lanes take them (rank, then + // slug — orderWithin's rule), and where in that list this one goes. + const others = rankedOrder(model).filter((r) => r.slug !== slug); + let at: number; + let rank: number; + if (place.kind === "rank") { + if (!Number.isInteger(place.rank) || place.rank < 0) { + throw new RankPlacementError(`A rank is a whole number, 0 or more (0 = first); got ${place.rank}.`); + } + // Before every channel already holding that rank or a later one. + at = others.findIndex((r) => r.rank >= place.rank); + if (at < 0) at = others.length; + rank = place.rank; + } else if (place.kind === "top") { + at = 0; + rank = others[0]?.rank ?? 0; + } else if (place.kind === "bottom") { + at = others.length; + rank = others.length ? others[others.length - 1].rank + 1 : 0; + } else { + const anchor = place.slug.trim(); + if (anchor === slug) { + throw new RankPlacementError(`"${slug}" cannot be placed ${place.kind} itself.`); + } + const i = others.findIndex((r) => r.slug === anchor); + if (i < 0) { + throw new RankPlacementError( + `"${anchor}" has no rank, so there is no place ${place.kind} it — rank it first ` + + `(top, bottom or a rank), or place "${slug}" by rank.`, + ); + } + if (place.kind === "before") { + at = i; + rank = i > 0 ? others[i - 1].rank + 1 : others[i].rank; + } else { + at = i + 1; + rank = others[i].rank + 1; + } + } + // Strictly after the channel before it, so a tie never reorders it by slug. + if (at > 0) rank = Math.max(rank, others[at - 1].rank + 1); + // Every channel after it moves down only as far as it must to stay after + // it and after the one before it, and two that were tied stay tied — so the + // order of the rest is kept exactly. + const channels: Record<string, ChannelPriorityEntry> = { ...model.channels }; + let floor = rank; + let prevOld: number | null = null; + for (const r of others.slice(at)) { + // Tied with the one before it (and so after it by slug): tied still. + const next: number = prevOld !== null && r.rank === prevOld ? floor : r.rank > floor ? r.rank : floor + 1; + if (next !== r.rank) channels[r.slug] = { ...model.channels[r.slug], rank: next }; + prevOld = r.rank; + floor = next; + } + channels[slug] = { ...(current ?? { tier: DEFAULT_CHANNEL_TIER }), rank }; + return { ...model, channels }; +} + +// The ranked channels in the order the lanes take them: rank, then slug. +export function rankedOrder(model: ChannelPriority): { slug: string; rank: number }[] { + return Object.entries(model.channels) + .filter(([, e]) => e.rank !== undefined) + .map(([slug, e]) => ({ slug, rank: e.rank as number })) + .sort((a, b) => a.rank - b.rank || a.slug.localeCompare(b.slug)); +} + export function tierOrder(tier: ChannelTier): number { const i = CHANNEL_TIERS.indexOf(tier); return i < 0 ? CHANNEL_TIERS.length : i; diff --git a/common/lib/channelRank.test.ts b/common/lib/channelRank.test.ts @@ -0,0 +1,99 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + placeChannelRank, + rankedOrder, + RankPlacementError, + sanitizeChannelPriority, + type ChannelPriority, +} from "./channelPriority"; + +// `pnpm ops channel-rank`: one channel moved in the ONE order; every other +// channel's order kept exactly; nothing but the rank changes. +const doc = (channels: ChannelPriority["channels"]): ChannelPriority => ({ focus: { kind: "none" }, channels }); +const order = (m: ChannelPriority) => rankedOrder(m).map((r) => r.slug); +const ABC = doc({ + a: { tier: "normal", rank: 0 }, + b: { tier: "low", rank: 1, overrides: { sync: "normal" } }, + c: { tier: "normal", rank: 2 }, + u: { tier: "paused", overrides: { sync: "normal" } }, +}); + +test("top and bottom: first and last of the ranked channels; tier and overrides untouched", () => { + const top = placeChannelRank(ABC, "c", { kind: "top" }); + assert.deepEqual(order(top), ["c", "a", "b"]); + assert.deepEqual(top.channels.b, { tier: "low", rank: 2, overrides: { sync: "normal" } }); + const bottom = placeChannelRank(ABC, "a", { kind: "bottom" }); + assert.deepEqual(order(bottom), ["b", "c", "a"]); + assert.equal(bottom.channels.a.rank, 3, "after the last rank; nothing else shifts"); + assert.equal(bottom.channels.b.rank, 1); + // An unranked channel taken to the top keeps its tier and overrides. + const u = placeChannelRank(ABC, "u", { kind: "top" }); + assert.deepEqual(order(u), ["u", "a", "b", "c"]); + assert.deepEqual(u.channels.u, { tier: "paused", overrides: { sync: "normal" }, rank: 0 }); + // A channel with no entry at all gets one, at the default tier. + assert.deepEqual(placeChannelRank(ABC, "new", { kind: "bottom" }).channels.new, { tier: "normal", rank: 3 }); + // Nothing ranked: top and bottom are both rank 0. + assert.equal(placeChannelRank(doc({}), "x", { kind: "top" }).channels.x.rank, 0); + assert.equal(placeChannelRank(doc({}), "x", { kind: "bottom" }).channels.x.rank, 0); +}); + +test("before and after another ranked channel", () => { + assert.deepEqual(order(placeChannelRank(ABC, "a", { kind: "before", slug: "c" })), ["b", "a", "c"]); + assert.deepEqual(order(placeChannelRank(ABC, "c", { kind: "after", slug: "a" })), ["a", "c", "b"]); + assert.deepEqual(order(placeChannelRank(ABC, "a", { kind: "after", slug: "c" })), ["b", "c", "a"]); + assert.deepEqual(order(placeChannelRank(ABC, "u", { kind: "before", slug: "a" })), ["u", "a", "b", "c"]); + assert.throws( + () => placeChannelRank(ABC, "a", { kind: "before", slug: "u" }), + (e: Error) => e instanceof RankPlacementError && /"u" has no rank, so there is no place before it/.test(e.message), + ); + assert.throws(() => placeChannelRank(ABC, "a", { kind: "after", slug: "a" }), /cannot be placed after itself/); +}); + +test("rank n: taken pushes it and everything below down one; free takes the gap; unrank removes it", () => { + const taken = placeChannelRank(ABC, "c", { kind: "rank", rank: 1 }); + assert.deepEqual(order(taken), ["a", "c", "b"]); + assert.deepEqual(rankedOrder(taken), [ + { slug: "a", rank: 0 }, + { slug: "c", rank: 1 }, + { slug: "b", rank: 2 }, + ]); + const gap = placeChannelRank(doc({ a: { tier: "normal", rank: 0 }, c: { tier: "normal", rank: 10 } }), "b", { + kind: "rank", + rank: 5, + }); + assert.deepEqual(rankedOrder(gap), [ + { slug: "a", rank: 0 }, + { slug: "b", rank: 5 }, + { slug: "c", rank: 10 }, + ]); + assert.throws(() => placeChannelRank(ABC, "a", { kind: "rank", rank: -1 }), /a whole number, 0 or more/); + assert.throws(() => placeChannelRank(ABC, "a", { kind: "rank", rank: 1.5 }), /a whole number, 0 or more/); + const un = placeChannelRank(ABC, "b", { kind: "unrank" }); + assert.deepEqual(order(un), ["a", "c"]); + assert.deepEqual(un.channels.b, { tier: "low", overrides: { sync: "normal" } }); + // A channel whose entry said only its rank is dropped by the sanitizer. + assert.equal(sanitizeChannelPriority(placeChannelRank(ABC, "a", { kind: "unrank" })).channels.a, undefined); + assert.equal(placeChannelRank(ABC, "u", { kind: "unrank" }), ABC, "nothing to remove: the input"); +}); + +test("ties: after X lands immediately after X, before its tie partners, and ties below stay tied", () => { + const tied = doc({ + a: { tier: "normal", rank: 0 }, + x: { tier: "normal", rank: 0 }, + y: { tier: "normal", rank: 0 }, + p: { tier: "normal", rank: 3 }, + q: { tier: "normal", rank: 3 }, + }); + assert.deepEqual(order(tied), ["a", "x", "y", "p", "q"]); + assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "after", slug: "a" })), ["a", "z", "x", "y", "p", "q"]); + assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "after", slug: "x" })), ["a", "x", "z", "y", "p", "q"]); + assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "before", slug: "y" })), ["a", "x", "z", "y", "p", "q"]); + assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "before", slug: "a" })), ["z", "a", "x", "y", "p", "q"]); + const moved = placeChannelRank(tied, "z", { kind: "after", slug: "a" }); + assert.equal(moved.channels.x.rank, moved.channels.y.rank, "x and y were tied and stay tied"); + assert.equal(moved.channels.p.rank, 3, "a channel already far enough down does not move"); + assert.equal(moved.channels.p.rank, moved.channels.q.rank); + // Moving a channel out of a tie. + assert.deepEqual(order(placeChannelRank(tied, "a", { kind: "after", slug: "y" })), ["x", "y", "a", "p", "q"]); +}); diff --git a/common/lib/liveNow-server.ts b/common/lib/liveNow-server.ts @@ -0,0 +1,25 @@ +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import { liveDownloadRefusal, liveNowState, type LiveNowState } from "./liveNow"; + +// The live state a video's metadata.info.json records (lib/liveNow.ts), null +// when it records none — or there is no readable record, which says nothing +// either way: a download is not refused on a guess. +export async function readLiveNowState(videoDir: string): Promise<LiveNowState | null> { + try { + const meta = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as unknown; + return liveNowState(meta as Parameters<typeof liveNowState>[0]); + } catch { + return null; + } +} + +// The refusal for a download of this video, or null when its record says it +// is not a stream in progress. +export async function liveDownloadRefusalFor( + videoDir: string, + ids: { slug: string; videoId: string }, +): Promise<string | null> { + const state = await readLiveNowState(videoDir); + return state ? liveDownloadRefusal(state, ids) : null; +} diff --git a/common/lib/liveNow.test.ts b/common/lib/liveNow.test.ts @@ -0,0 +1,53 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { liveDownloadRefusal, liveNowState } from "./liveNow"; +import { liveDownloadRefusalFor, readLiveNowState } from "./liveNow-server"; + +test("liveNowState: is_live, is_upcoming and post_live are streams in progress; was_live and not_live are not", () => { + assert.equal(liveNowState({ live_status: "is_live" }), "is_live"); + assert.equal(liveNowState({ live_status: "is_upcoming" }), "is_upcoming"); + assert.equal(liveNowState({ live_status: "post_live" }), "post_live"); + assert.equal(liveNowState({ live_status: "was_live" }), null, "a finished VOD downloads normally"); + assert.equal(liveNowState({ live_status: "not_live" }), null); + assert.equal(liveNowState({}), null); + assert.equal(liveNowState(null), null); + // The boolean alone (an older record), and a status that overrules it. + assert.equal(liveNowState({ is_live: true }), "is_live"); + assert.equal(liveNowState({ is_live: true, live_status: "was_live" }), null, "the newer field wins"); + assert.equal(liveNowState({ is_live: "yes" }), null, "only a real true"); +}); + +test("liveDownloadRefusal names record-live and refresh-metadata with runnable bodies", () => { + const ids = { slug: "demo-yt", videoId: "abcdefghijk" }; + const live = liveDownloadRefusal("is_live", ids); + assert.match(live, /^abcdefghijk is live now \(live_status is_live\)/); + assert.match(live, /at 1x/); + assert.ok(live.includes(`pnpm ops record-live --json '{"slug":"demo-yt","id":"abcdefghijk"}'`), live); + assert.ok(live.includes(`pnpm ops refresh-metadata --json '{"slug":"demo-yt","id":"abcdefghijk"}'`), live); + assert.match(live, /wait for the VOD/); + assert.match(liveDownloadRefusal("is_upcoming", ids), /scheduled stream that has not started/); + const post = liveDownloadRefusal("post_live", ids); + assert.match(post, /VOD is still being processed/); + assert.equal(post.includes("record-live"), false, "an ended stream is not recorded"); +}); + +test("readLiveNowState reads metadata.info.json; no record (or junk) is no answer", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "live-now-")); + try { + const dir = path.join(root, "v1"); + await mkdir(dir); + assert.equal(await readLiveNowState(dir), null); + await writeFile(path.join(dir, "metadata.info.json"), "{not json"); + assert.equal(await readLiveNowState(dir), null); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "v1", live_status: "is_live" })); + assert.equal(await readLiveNowState(dir), "is_live"); + assert.match((await liveDownloadRefusalFor(dir, { slug: "s", videoId: "v1" })) ?? "", /v1 is live now/); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "v1", live_status: "was_live" })); + assert.equal(await liveDownloadRefusalFor(dir, { slug: "s", videoId: "v1" }), null); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/common/lib/liveNow.ts b/common/lib/liveNow.ts @@ -0,0 +1,65 @@ +// IS THIS VIDEO A STREAM THAT HAS NOT FINISHED? — and the sentence a +// download-for-transcription says when it is. +// +// A one-video download of a video that is live reads the HLS at 1x: yt-dlp +// follows the stream until it ends, and the platform's queue is held for the +// stream's whole length (4 Nov: a transcribe-one on a live YouTube video sat +// on platform:youtube for hours). Such a video is recorded by record-live, or +// transcribed once its VOD exists — never downloaded as a finished video. +// +// What a download already knows is the video's metadata.info.json (yt-dlp's +// `is_live` / `live_status`, the same fields skip-live and record-live read). +// It is a snapshot: a stream that has ended since still says `is_live` until +// the record is re-read, which is why the sentence names refresh-metadata. +// +// The three states are record-live's LIVE_STATES: `is_live`, `is_upcoming` +// (scheduled, not started) and `post_live` (ended; its VOD is still being +// processed and a download of it now is the stream's fragments, or an +// incomplete file). `was_live` is a finished VOD and downloads normally. + +export type LiveNowState = "is_live" | "is_upcoming" | "post_live"; + +export type LiveFields = { + is_live?: unknown; + live_status?: unknown; +}; + +export function liveNowState(meta: LiveFields | null | undefined): LiveNowState | null { + if (!meta || typeof meta !== "object") return null; + const status = typeof meta.live_status === "string" ? meta.live_status : ""; + if (status === "is_live" || status === "is_upcoming" || status === "post_live") return status; + // An extractor that sets only the boolean (older records, some platforms). + // A `live_status` that says otherwise wins: it is the newer field. + if (meta.is_live === true && (status === "" || status === "is_live")) return "is_live"; + return null; +} + +// The refusal. `slug` and `videoId` make the two commands it names runnable +// as they stand. +export function liveDownloadRefusal( + state: LiveNowState, + { slug, videoId }: { slug: string; videoId: string }, +): string { + const body = JSON.stringify({ slug, id: videoId }); + const record = `pnpm ops record-live --json '${body}'`; + const refresh = `pnpm ops refresh-metadata --json '${body}'`; + if (state === "is_upcoming") { + return ( + `${videoId} is a scheduled stream that has not started (live_status is_upcoming): there is nothing to ` + + `transcribe yet. Record it from its start with record-live (${record}), or wait for the VOD; once it has ` + + `aired, ${refresh} re-reads its record.` + ); + } + if (state === "post_live") { + return ( + `${videoId}'s stream has ended but its VOD is still being processed (live_status post_live): a download now ` + + `reads the stream's fragments, not the finished video. Wait for the VOD; ${refresh} re-reads its record ` + + `once it is ready.` + ); + } + return ( + `${videoId} is live now (live_status is_live): a download would read the stream at 1x and hold the ` + + `platform's queue for as long as it runs. Record it with record-live (${record}), or wait for the VOD; ` + + `once it has ended, ${refresh} re-reads its record.` + ); +} diff --git a/common/lib/site.ts b/common/lib/site.ts @@ -307,6 +307,20 @@ export async function writeSite( // interleave. A function patch is given the site as it is now (to reorder a // list it did not read itself). Validated and written by writeSite. Null when // the site has no site.json: a patch never creates a site. +// THE SITE FILE'S LOCK: a read-modify-write of one site.json that must not +// interleave with another (patchSite, the site form's save). Per process; NOT +// re-entrant — never patchSite from inside it. writeSite does not take it. +export function withSiteLock<T>( + siteId: string, + fn: () => Promise<T>, + paths: Paths = getPaths(), +): Promise<T> { + if (!isValidSiteId(siteId)) { + throw new Error(`Invalid site id: ${String(siteId)}`); + } + return withJsonFileLock(siteConfigFile(paths, siteId), fn); +} + export async function patchSite( siteId: string, patch: @@ -318,7 +332,7 @@ export async function patchSite( throw new Error(`Invalid site id: ${String(siteId)}`); } const file = siteConfigFile(paths, siteId); - return withJsonFileLock(file, async () => { + return withSiteLock(siteId, async () => { if (!fs.existsSync(file)) return null; const current = getSite(siteId, paths); const changes = typeof patch === "function" ? patch(current) : patch; diff --git a/common/lib/subLangs.test.ts b/common/lib/subLangs.test.ts @@ -0,0 +1,22 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { normalizeSubLangs, SUB_LANGS_MAX_LENGTH, subLangsProblem } from "./channelConfig"; + +// Configure's caption languages (subLangs): what yt-dlp's --sub-langs can use +// is saved; what would fail every caption download is refused at the save. +test("subLangsProblem accepts yt-dlp's forms: regexes, all, exclusions, spaces around entries", () => { + for (const ok of ["en.*", "en.*,live_chat", "all,-live_chat", "en,es,fr", "en-US", "en(-GB)?", " en.* , es ", ""]) { + assert.equal(subLangsProblem(ok), null, ok); + } + assert.equal(normalizeSubLangs(" en.* , es "), "en.*,es"); +}); + +test("subLangsProblem refuses an empty entry, a space inside an entry, a bare dash, a bad regex, an over-long value", () => { + assert.match(subLangsProblem("en,,es") ?? "", /has an empty entry/); + assert.match(subLangsProblem("en,") ?? "", /has an empty entry/); + assert.match(subLangsProblem("en us") ?? "", /entry "en us" has a space in it/); + assert.match(subLangsProblem("en,-") ?? "", /entry "-" excludes nothing/); + assert.match(subLangsProblem("en(") ?? "", /entry "en\(" is not a valid regular expression/); + assert.match(subLangsProblem("-[") ?? "", /entry "-\[" is not a valid regular expression/); + assert.match(subLangsProblem("e".repeat(SUB_LANGS_MAX_LENGTH + 1)) ?? "", /at most 200/); +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,11 @@ # Changelog ## [Unreleased] +- **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, each as a `patchSite` under that site's lock, so a concurrent edit of the site is not written over (a rename already re-points them through the same writer). The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`). +- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, a channel's `groupId` that names none of the site's groups, unknown keys and keys of the wrong type are refused before anything is written. The existence check, the read of the stored site and the save are one read-modify-write under the site's lock (`withSiteLock`). The site form's own Save now takes the same lock, so neither it nor an update is written over a concurrent edit such as a Reports-tab pages patch. It answers the saved site. +- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: channels after it move down only as far as they must, ties stay tied, and `after` lands immediately after its anchor even when the anchor's rank is tied. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. That writer now does its read-modify-write inside a settings lock, which every `saveSettings` takes too, so a concurrent deck save or a parallel `channel-rank` is never written over. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`). +- **Configure's Caption languages field (`subLangs`) is checked when you save.** Before, any text was saved, and a value yt-dlp's `--sub-langs` cannot use failed every caption download on the channel at the moment it ran. Configure and `pnpm ops channel-config` (`patch.subLangs`) now refuse it, in the field's words, with what you typed kept. Refused: an empty entry (two commas, or one at an end), a space inside an entry, a bare `-`, an entry that is not a regular expression, or a value over 200 characters. Spaces around an entry are dropped (`en.* , es` saves as `en.*,es`). A value saved before this check and submitted unchanged is kept, with a warning in the server log, so Configure is never locked on it. `all` and `-<lang>` exclusions are accepted as before (`common/lib/channelConfig.ts` `subLangsProblem`). +- **Transcribe refuses a video that is live.** On 4 Nov a transcribe-one on a live YouTube video downloaded the stream at 1x and held `platform:youtube` for the stream's whole length. Now the video page's Transcribe and `pnpm ops transcribe-one` refuse a video whose `metadata.info.json` says it is live (`is_live`), scheduled (`is_upcoming`) or still processing its VOD (`post_live`), before anything is queued. The refusal names `pnpm ops record-live` for the stream (not for `post_live`), says to wait for the VOD otherwise, and names `refresh-metadata` to re-read the record once the stream has ended. The job checks again just before its download, in case the record was re-read while it waited. Only the audio download is refused: a video whose audio or container is already on disk still transcribes, and a youtube-handling video with English captions listed still has its captions fetched instead. A finished stream (`was_live`) downloads as before (`common/lib/liveNow.ts`). - **The X run console: several X channels' posts fetched as one job that stops when the cookies go stale.** On 8 and 9 Nov an agent ran X fetch-posts by hand, one channel after another, watching the cookie jar age and putting off the rest once it went stale. `/review`'s new **X run** section lists the X posts channels in priority order (focus, tier, rank; paused ones unticked), with a tick and up/down buttons for each, and **Start X run** queues ONE `x-run` job on X's queue. The job fetches each channel in turn (new posts only, at most 200 each), waits X's queue gap (`pacing.jobGapSeconds.twitter`) between two channels, and checks the cookie jar again before EACH one. Once the jar is past `social.x.maxCookieAgeMinutes`, or the X alert is up, the run stops and the rest are **deferred until the next refresh**. It never refreshes cookies itself. The console shows each channel's state (queued, running, done with its new posts, deferred, failed), "N done, M deferred until the next refresh", the jar's age counted down to the limit, and the wait before the next channel. **Resume** runs the deferred channels after the operator presses Refresh cookies on /settings. A Retry of the job, and "Re-run stopped jobs", do the same. A restart does not resume a run: an interrupted run ends deferred. `pnpm ops x-run {"channels": [...]}` / `{"resume": "<run id>"}` and `pnpm ops get x-run` do the same from a terminal. - **Account activity on a posts channel's page: posts per day, with the long silences marked.** A compact bar strip shows posts per UTC day over the archive's range. Long silences are shaded and listed: a gap of at least 3× the account's median gap AND 48 h, each linked to the post before it and the post after. An open-ended silence since the last post is listed too, when the last fetch came that long after it. Only the account's own posts count (a with-replies timeline also archives the posts it answers). The silence is the archive's ("no archived post"), and a stretch no fetch reached looks the same. Mr Obvious's 5–8 Nov gap reads 4 Nov 10:54 → 8 Nov 19:00 UTC on ObviousRises-x. - **umtool: each character has a voice, auditioned on a page, the same in every project.** The operator wanted to "pick different voices for different characters, and in UI alone be able to try rendering different ones to compare … and try to maintain consistent voices for different repeating characters" -- tonight TheQuartering's reads were re-voiced by hand after scoring five voices against his real one. `/projects/<p>/voices` (from the Cut tab's Reads and voices) lists every character a project's reads use, the voice each reads in now and where it comes from (the cast, the project, the narrator's, the default), its reads in another voice, and its real voice. **Audition** reads one line (its own words here, a stock line, or typed) in 2-6 stock voices -- a job: the editor's tts, then each one's closeness to the real voice (speakers.json, TitaNet, local) -- played side by side at one loudness beside the real voice, a reference never a target. **Use for this project** or **Use everywhere** (the cast, `<reports>/.umtool/cast.json`), then the items to re-read, queued. A recording of an item can be made a character's read: kept, cleaned, converted to its stock voice. Every read -- a single post's and each piece of a thread read -- asks the same order (the read's own, the project's map, the cast, the narrator's, the default), and a cast voice of another engine is synthesized by it. `umtool cast ls|add|set|rm|undo|project|audition|use|reread`, `posts narrate … --recording`, and `umtool lint` warns when a cast character is read in another voice. diff --git a/editor/app/api/ops/channel-rank/route.test.ts b/editor/app/api/ops/channel-rank/route.test.ts @@ -0,0 +1,64 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/channel-rank/route.test.ts" +// +// `channel-rank`: one channel placed in the order through the deck's one +// writer. Every REFUSAL here is answered before anything is written; the +// writes end in revalidatePath, which a bare tsx process has no request store +// for, so they are driven over HTTP in e2e/ops-api.spec.ts. + +const corpus = await setupOpsCorpus(null); +for (const slug of ["alpha", "beta", "gamma", "off"]) { + await corpus.writeChannelConfig(slug, { url: `https://www.youtube.com/@${slug}` }); +} +await corpus.writeSettings({ + channelPriority: { + focus: { kind: "none" }, + channels: { alpha: { tier: "normal", rank: 0 }, beta: { tier: "normal", rank: 1 }, off: { tier: "paused" } }, + }, +}); +const { POST } = await import("./route"); +test.after(() => corpus.cleanup()); +const settingsText = () => readFile(corpus.settingsFile, "utf8"); + +test("exactly one placement, of the right type; unknown keys refused", async () => { + const before = await settingsText(); + for (const [body, re] of [ + [{ slug: "alpha" }, /give exactly one placement/], + [{ slug: "alpha", top: true, bottom: true }, /give exactly one placement .*; got "top", "bottom"/], + [{ slug: "alpha", rank: -1 }, /"rank" must be a whole number, 0 or more/], + [{ slug: "alpha", rank: 1.5 }, /"rank" must be a whole number/], + [{ slug: "alpha", rank: "2" }, /"rank" must be a whole number/], + [{ slug: "alpha", top: false }, /"top" must be true/], + [{ slug: "alpha", before: "../x" }, /not a valid channel slug/], + [{ slug: "alpha", first: true }, /first/], + ] as const) { + const r = await callPost(POST, body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(String(r.body.error), re, JSON.stringify(r.body)); + } + assert.equal(await settingsText(), before, "nothing written"); +}); + +test("an unknown channel is a 404; an unknown anchor, an unranked anchor, a paused-everywhere channel are refused", async () => { + const before = await settingsText(); + const missing = await callPost(POST, { slug: "nope", top: true }); + assert.equal(missing.status, 404); + assert.match(String(missing.body.error), /Channel "nope" not found/); + const anchor = await callPost(POST, { slug: "alpha", after: "nope" }); + assert.equal(anchor.status, 400); + assert.match(String(anchor.body.error), /Channel "nope" not found \(the "after" anchor\)/); + const unranked = await callPost(POST, { slug: "alpha", before: "gamma" }); + assert.equal(unranked.status, 400); + assert.match(String(unranked.body.error), /"gamma" has no rank, so there is no place before it/); + const self = await callPost(POST, { slug: "beta", after: "beta" }); + assert.match(String(self.body.error), /cannot be placed after itself/); + const paused = await callPost(POST, { slug: "off", top: true }); + assert.equal(paused.status, 400); + assert.match(String(paused.body.error), /"off" is paused for every operation/); + assert.equal(await settingsText(), before, "nothing written"); +}); diff --git a/editor/app/api/ops/channel-rank/route.ts b/editor/app/api/ops/channel-rank/route.ts @@ -0,0 +1,85 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { + rankOf, + rankedOrder, + type RankPlacement, +} from "yt-dlp-transcript-common/lib/channelPriority"; +import { channelExists } from "yt-dlp-transcript-common/controller/channels"; +import { setChannelRankAction } from "../../../channels/actions"; +import { OpsInputError, ops, opsFail, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, rank: <n> | null } | { slug, top: true } | { slug, bottom: true } +// | { slug, before: <slug> } | { slug, after: <slug> } +// -> { ok, slug, rank, order: [{slug, rank}, …] } +// +// ONE CHANNEL PLACED IN THE ORDER — the rank inside its tier that every lane +// and the sync scheduler follow (one rank per channel; unranked after every +// ranked channel, then by slug). Before this only /channels' "Add to top" +// moved a channel, and it also sets the tier to normal and turns the download +// lane on. This moves the rank alone, through the deck's one writer +// (saveChannelPriorityAction), which recompiles the four lane roots in the +// same write, under the settings lock. Every other channel keeps its order: +// the ones after it move down only as far as they must, ties stay tied. +// +// Exactly one placement. `rank: null` removes the rank. Refused before any +// write: an unknown channel or anchor, an anchor with no rank (nothing to be +// next to), a rank that is not a whole number ≥ 0, a channel paused for every +// operation (it is in no order; its rank would not be kept). +// The answer is the saved rank and the whole ranked order. +const PLACEMENTS = ["rank", "top", "bottom", "before", "after"] as const; + +export async function POST(request: Request) { + return ops(request, ["slug", ...PLACEMENTS], async (body) => { + const slug = reqSlug(body, "slug"); + const given = PLACEMENTS.filter((k) => body[k] !== undefined); + if (given.length !== 1) { + throw new OpsInputError( + `give exactly one placement — "rank" (a number, or null to unrank), "top": true, "bottom": true, ` + + `"before": "<slug>" or "after": "<slug>"${given.length ? `; got ${given.map((k) => `"${k}"`).join(", ")}` : ""}`, + ); + } + const paths = getPaths(); + if (!(await channelExists(paths, slug))) { + return opsFail(`Channel "${slug}" not found`, 404); + } + const place = await readPlacement(body, given[0], async (anchor) => { + if (!(await channelExists(paths, anchor))) { + throw new OpsInputError(`Channel "${anchor}" not found (the "${given[0]}" anchor)`); + } + }); + const result = await setChannelRankAction(slug, place); + if (result?.error) return opsFail(result.error); + const saved = getSettings().channelPriority; + return NextResponse.json({ ok: true, slug, rank: rankOf(saved, slug), order: rankedOrder(saved) }); + }); +} + +async function readPlacement( + body: Record<string, unknown>, + key: (typeof PLACEMENTS)[number], + checkAnchor: (slug: string) => Promise<void>, +): Promise<RankPlacement> { + const v = body[key]; + if (key === "rank") { + if (v === null) return { kind: "unrank" }; + if (typeof v !== "number" || !Number.isInteger(v) || v < 0) { + throw new OpsInputError('"rank" must be a whole number, 0 or more (0 = first), or null to remove the rank'); + } + return { kind: "rank", rank: v }; + } + if (key === "top" || key === "bottom") { + if (v !== true) throw new OpsInputError(`"${key}" must be true`); + return { kind: key }; + } + const anchor = reqSlug(body, key); + await checkAnchor(anchor); + return { kind: key, slug: anchor }; +} + +export function GET() { + return NextResponse.json({ ok: false, error: "POST only" }, { status: 405 }); +} diff --git a/editor/app/api/ops/create-site/route.test.ts b/editor/app/api/ops/create-site/route.test.ts @@ -0,0 +1,221 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/create-site/route.test.ts" +// +// `create-site`: the New site form over HTTP, saved by the form's own action +// (saveSiteAction -> writeSite) — and "update": the site page's Save with the +// given keys changed. The action does not revalidate, so its writes are +// tested here, against a temp corpus. + +const corpus = await setupOpsCorpus(null); +for (const slug of ["pooled", "critic", "other"]) { + await corpus.writeChannelConfig(slug, { url: `https://www.youtube.com/@${slug}` }); +} +await corpus.writeSite("neighbour", {}); +const { POST } = await import("./route"); +const { getSite, writeSite, withSiteLock } = await import("yt-dlp-transcript-common/lib/site"); +const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); +const { siteToFormData } = await import("../../../sites/lib/siteFormData"); +const { saveSiteAction } = await import("../../../sites/actions"); +test.after(() => corpus.cleanup()); + +const siteFile = async (id: string) => + JSON.parse(await readFile(path.join(corpus.transcripts, "sites", id, "site.json"), "utf8")) as Record< + string, + unknown + >; + +test("a create is private and unlisted by default, its header the title, through the form's writer", async () => { + const r = await callPost(POST, { siteId: "efapalyzer", siteTitle: "Efapalyzer", channels: ["pooled"] }); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(r.body.created, true); + const file = await siteFile("efapalyzer"); + assert.equal(file.siteTitle, "Efapalyzer"); + assert.equal(file.headerTitle, "Efapalyzer"); + assert.equal(file.audience, "private"); + assert.equal(file.listed, false); + assert.deepEqual(file.channels, [{ slug: "pooled", order: 0 }]); + assert.equal("publish" in file, false, "publish off"); + assert.equal("search" in file, false, "search on (absent)"); + assert.deepEqual((r.body.site as { siteId: string }).siteId, "efapalyzer"); + + // Public, listed, grouped, cited, with a policy: every key the form's. + const pub = await callPost(POST, { + siteId: "shown", + siteTitle: "Shownalyzer", + headerTitle: "Shownalyzer", + wordmarkLead: "Shown", + audience: "public", + listed: true, + accent: "#cc3366", + cloudflareProject: "shown-pages", + siteUrl: "https://shown.example/", + publishAuto: "production", + groups: [ + { id: "main", name: "Main", selectedByDefault: true }, + { id: "extra", name: "Extra" }, + ], + defaultGroupId: "main", + channels: [{ slug: "pooled", groupId: "extra" }], + citedChannels: ["critic", "pooled"], + archiveMaxMB: 24, + }); + assert.equal(pub.status, 200, JSON.stringify(pub.body)); + const s = await siteFile("shown"); + assert.equal("audience" in s, false, "public is the absent default"); + assert.equal("listed" in s, false, "listed is the absent default"); + assert.equal(s.accent, "#cc3366"); + assert.equal(s.siteUrl, "https://shown.example"); + assert.deepEqual(s.publish, { auto: "production" }); + assert.deepEqual(s.channels, [{ slug: "pooled", groupId: "extra", order: 0 }]); + assert.deepEqual(s.citedChannels, [{ slug: "critic" }], "a pooled slug is dropped from the cited scope"); + assert.equal(s.archiveMaxBytes, 24 * 1024 * 1024); + assert.equal(s.wordmarkLead, "Shown"); +}); + +test("an existing id is refused unless update; update keeps every key it does not name", async () => { + const before = await siteFile("shown"); + const again = await callPost(POST, { siteId: "shown", siteTitle: "Other" }); + assert.equal(again.status, 409); + assert.match(String(again.body.error), /Site "shown" already exists\. "update": true saves the keys given over it/); + assert.deepEqual(await siteFile("shown"), before, "nothing written"); + + const up = await callPost(POST, { siteId: "shown", update: true, homeTagline: "Every stream, searchable" }); + assert.equal(up.status, 200, JSON.stringify(up.body)); + assert.equal(up.body.created, false); + assert.deepEqual(await siteFile("shown"), { ...before, homeTagline: "Every stream, searchable" }); + + const none = await callPost(POST, { siteId: "nosuch", update: true, siteTitle: "X" }); + assert.equal(none.status, 404); + assert.match(String(none.body.error), /Site "nosuch" not found — leave out "update" to create it/); +}); + +test("the form's refusals, and the door's, before anything is written", async () => { + for (const [body, status, re] of [ + [{ siteId: "Bad Id", siteTitle: "X" }, 400, /not a valid site id/], + [{ siteId: "new", siteTitle: "X" }, 400, /new/], + [{ siteId: "untitled" }, 400, /a new site needs a "siteTitle"/], + [{ siteId: "blank", siteTitle: " " }, 400, /Site title is required/], + [{ siteId: "lead", siteTitle: "Leadalyzer", wordmarkLead: "lead" }, 400, /Wordmark lead must be how the header title starts/], + [{ siteId: "url", siteTitle: "U", siteUrl: "shown.example" }, 400, /Public URL must be an absolute http\(s\):\/\/ URL/], + [{ siteId: "aud", siteTitle: "A", audience: "friends" }, 400, /Unknown audience "friends"/], + [{ siteId: "pol", siteTitle: "P", audience: "public", publishAuto: "production" }, 400, /cloudflareProject/], + [{ siteId: "acc", siteTitle: "A", accent: "chartreuse" }, 400, /Unknown brand accent "chartreuse"/], + [{ siteId: "grp", siteTitle: "G", groups: [] }, 400, /At least one channel group is required/], + [{ siteId: "grp2", siteTitle: "G", groups: [{ name: "No id" }] }, 400, /"groups"\[0\] is not a channel group/], + [{ siteId: "ch", siteTitle: "C", channels: ["pooled", "ghost"] }, 400, /not a channel: "ghost"/], + [{ siteId: "cit", siteTitle: "C", citedChannels: ["ghost"] }, 400, /not a channel: "ghost"/], + [{ siteId: "typ", siteTitle: "T", listed: "yes" }, 400, /"listed" must be a boolean/], + [{ siteId: "typ2", siteTitle: "T", archiveMaxMB: "12" }, 400, /"archiveMaxMB" must be a number/], + [{ siteId: "unk", siteTitle: "U", pages: ["a"] }, 400, /pages/], + [ + { siteId: "grptypo", siteTitle: "G", channels: [{ slug: "pooled", groupId: "typo" }] }, + 400, + /"channels": "pooled" names group "typo", which is not one of the site's groups \("default"\)/, + ], + ] as const) { + const r = await callPost(POST, body); + assert.equal(r.status, status, JSON.stringify(body) + " " + JSON.stringify(r.body)); + assert.match(String(r.body.error), re, JSON.stringify(r.body)); + const id = (body as { siteId: string }).siteId; + if (id !== "new" && /^[a-z0-9-]+$/.test(id)) { + await assert.rejects(readFile(path.join(corpus.transcripts, "sites", id, "site.json")), `${id}: nothing written`); + } + } +}); + +// The round trip "update" rests on: a stored site, made into the form it would +// post untouched, saved by the form's action, is the same site.json. +test("siteToFormData -> saveSiteAction gives a full site back unchanged", async () => { + const paths = getPaths(); + await writeSite( + { + siteId: "full", + siteTitle: "Fullalyzer", + siteDescription: "Everything set", + headerTitle: "Fullalyzer", + wordmarkLead: "Full", + homeTagline: "All of it", + socialLinks: [{ label: "Site", url: "https://full.example", svg: '<svg viewBox="0 0 24 24"><path d="M0 0h24v24H0z"/></svg>' }], + groups: [ + { id: "main", name: "Main", selectedByDefault: true, order: 0, description: "The main ones" }, + { id: "side", name: "Side", selectedByDefault: false, order: 1, inline: true }, + ], + defaultGroupId: "side", + channels: [ + { slug: "pooled", groupId: "main", order: 0 }, + { slug: "other", order: 1 }, + ], + citedChannels: [{ slug: "critic" }], + cloudflareProject: "full-pages", + accent: "brass", + siteUrl: "https://full.example", + pages: ["intro"], + relatedSites: [{ label: "Friends", siteIds: ["neighbour"] }], + search: false, + pwa: true, + archives: false, + duplicates: false, + transcriptDownloads: false, + archiveMaxBytes: 12_345_678, + hubUrl: "https://hub.example", + publish: { auto: "preview" }, + }, + paths, + ); + const before = await siteFile("full"); + const r = await saveSiteAction(undefined, siteToFormData(getSite("full", paths))); + assert.equal(r.ok, true, JSON.stringify(r)); + assert.deepEqual(await siteFile("full"), before); + // And a private, inheriting, default-accent one. + await writeSite( + { + siteId: "plain", + siteTitle: "Plain", + siteDescription: "", + headerTitle: "Plain", + homeTagline: "", + groups: [{ id: "default", name: "All", selectedByDefault: true }], + defaultGroupId: "default", + channels: [], + audience: "private", + listed: false, + }, + paths, + ); + const plain = await siteFile("plain"); + assert.equal((await saveSiteAction(undefined, siteToFormData(getSite("plain", paths)))).ok, true); + assert.deepEqual(await siteFile("plain"), plain); +}); + +// An update is ONE read-modify-write under the site's lock: an edit of the +// site that holds the lock when the update arrives (a Reports-tab patch, say) +// is read by the update, not written over by a copy taken before it landed. +test("an update waits for a held edit of the site and keeps it", async () => { + const paths = getPaths(); + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + const held = withSiteLock( + "shown", + async () => { + const current = getSite("shown", paths); + await gate; + await writeSite({ ...current, homeTagline: "written while the update waited" }, paths); + }, + paths, + ); + const up = callPost(POST, { siteId: "shown", update: true, siteDescription: "after the held edit" }); + await new Promise((r) => setTimeout(r, 20)); + release(); + await held; + const r = await up; + assert.equal(r.status, 200, JSON.stringify(r.body)); + const file = await siteFile("shown"); + assert.equal(file.homeTagline, "written while the update waited"); + assert.equal(file.siteDescription, "after the held edit"); +}); diff --git a/editor/app/api/ops/create-site/route.ts b/editor/app/api/ops/create-site/route.ts @@ -0,0 +1,167 @@ +import { existsSync } from "node:fs"; +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + getSite, + isValidSiteId, + siteConfigFile, + withSiteLock, + type Site, +} from "yt-dlp-transcript-common/lib/site"; +import { + DEFAULT_GROUP_FALLBACK_ID, + FALLBACK_GROUP, + parseChannelGroups, +} from "yt-dlp-transcript-common/lib/channelGroups"; +import { channelExists, isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; +import { saveSiteFromForm } from "../../../sites/lib/saveSiteForm"; +import { + SITE_OPS_FIELDS, + SiteFieldError, + applySiteFields, + readChannels, + siteToFormData, +} from "../../../sites/lib/siteFormData"; +import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { siteId, siteTitle, …the site form's fields…, update? } +// -> { ok, siteId, created, site } +// +// THE NEW SITE FORM, OVER HTTP (lane editor-gaps; 9 Nov an agent had to call +// writeSite from a tsx script to make a site). The body's keys are the form's +// fields (app/sites/lib/siteFormData.ts SITE_OPS_FIELDS), built into the +// FormData the form posts and saved by the form's own action — saveSiteAction, +// so writeSite — with its validation and its sentences: a bad site id or a +// reserved one, no title, a wordmark lead that is not how the header starts, +// a URL that is not absolute, an unknown accent, audience or publish policy, a +// group list with none, a deploying policy with no Pages project. +// +// A CREATE IS PRIVATE AND UNLISTED unless the body says otherwise ("audience": +// "public", "listed": true) — the form defaults the other way because a +// person at it is building a public site; a script making one is usually +// making a reading copy. "headerTitle" defaults to "siteTitle". Every other +// key is the form's default: one inline group, no channels, search, archives, +// duplicates and transcript downloads on, publish off. +// +// AN EXISTING ID IS REFUSED (409) unless "update": true, which is the site +// page's Save with the given keys changed: the stored site is the form, the +// body's keys are laid over it, every key not named stays (the published page +// list is the Reports tab's and is always kept). "update" on a site that does +// not exist is a 404. +// +// Refused before anything is written, beside the action's own refusals: an +// unknown key, a key of the wrong type, a channel (or cited channel) that does +// not exist. +export async function POST(request: Request) { + return ops(request, ["siteId", "update", ...SITE_OPS_FIELDS], async (body) => { + const siteId = reqString(body, "siteId").trim(); + if (!isValidSiteId(siteId)) { + throw new OpsInputError(`"${siteId}" is not a valid site id (lowercase letters, numbers and hyphens)`); + } + const update = optBool(body, "update") === true; + const paths = getPaths(); + if (!update && typeof body.siteTitle !== "string") { + throw new OpsInputError('a new site needs a "siteTitle"'); + } + await refuseUnknownChannels(body); + const fields: Record<string, unknown> = {}; + for (const key of SITE_OPS_FIELDS) if (body[key] !== undefined) fields[key] = body[key]; + if (!update && fields.headerTitle === undefined) fields.headerTitle = fields.siteTitle; + // ONE READ-MODIFY-WRITE, under the site's lock (lib/site.ts withSiteLock): + // whether the site exists, the stored site an update starts from, and the + // form's save — so a concurrent edit of the site (a Reports-tab pages + // patch, a channel delete's membership patch) is never written over with + // the copy read here, and two creates of one id cannot both pass. + return withSiteLock(siteId, () => createOrUpdate(siteId, update, fields), paths); + }); +} + +async function createOrUpdate( + siteId: string, + update: boolean, + fields: Record<string, unknown>, +): Promise<NextResponse> { + const paths = getPaths(); + const exists = existsSync(siteConfigFile(paths, siteId)); + if (exists && !update) { + return opsFail( + `Site "${siteId}" already exists. "update": true saves the keys given over it, as its form's Save does ` + + `(site-config sets its cited channels and publish policy alone).`, + 409, + ); + } + if (!exists && update) { + return opsFail(`Site "${siteId}" not found — leave out "update" to create it`, 404); + } + const fd = siteToFormData(update ? getSite(siteId, paths) : blankSite(siteId)); + try { + applySiteFields(fd, fields); + refuseUnknownGroups(fd); + } catch (e) { + if (e instanceof SiteFieldError) return opsFail(e.message); + throw e; + } + const saved = await saveSiteFromForm(fd); + if (!saved.ok) return opsFail(saved.error); + return NextResponse.json({ ok: true, siteId, created: !update, site: getSite(siteId, paths) }); +} + +// A channel's groupId that names no group of the site: the parser would drop +// it without a word (the channel falls into the default group). The form only +// offers the site's groups; over ops it is said. +function refuseUnknownGroups(fd: FormData): void { + const groups = parseChannelGroups(JSON.parse(String(fd.get("groupsJson") ?? "[]"))); + const ids = new Set(groups.map((g) => g.id)); + const channels = JSON.parse(String(fd.get("channelsJson") ?? "[]")) as { slug?: unknown; groupId?: unknown }[]; + for (const c of channels) { + if (typeof c.groupId === "string" && c.groupId && !ids.has(c.groupId)) { + throw new SiteFieldError( + `"channels": "${String(c.slug)}" names group "${c.groupId}", which is not one of the site's groups ` + + `(${[...ids].map((id) => `"${id}"`).join(", ") || "none"})`, + ); + } + } +} + +// What /sites/new starts from, private and unlisted. +function blankSite(siteId: string): Site { + return { + siteId, + siteTitle: "", + siteDescription: "", + headerTitle: "", + homeTagline: "", + groups: [{ ...FALLBACK_GROUP }], + defaultGroupId: DEFAULT_GROUP_FALLBACK_ID, + channels: [], + audience: "private", + listed: false, + }; +} + +// The form offers only channels that exist; a slug here is checked the same. +async function refuseUnknownChannels(body: Record<string, unknown>): Promise<void> { + const slugs: string[] = []; + try { + if (body.channels !== undefined) slugs.push(...readChannels(body.channels).map((c) => c.slug)); + } catch (e) { + if (e instanceof SiteFieldError) throw new OpsInputError(e.message); + throw e; + } + if (Array.isArray(body.citedChannels)) { + slugs.push(...body.citedChannels.filter((s): s is string => typeof s === "string").map((s) => s.trim())); + } + const paths = getPaths(); + const missing: string[] = []; + for (const slug of new Set(slugs)) { + if (!isValidChannelSlug(slug)) { + throw new OpsInputError(`"${slug}" is not a valid channel slug`); + } + if (!(await channelExists(paths, slug))) missing.push(slug); + } + if (missing.length > 0) { + throw new OpsInputError(`not a channel: ${missing.map((s) => `"${s}"`).join(", ")}`); + } +} diff --git a/editor/app/api/ops/delete-channel/route.ts b/editor/app/api/ops/delete-channel/route.ts @@ -12,6 +12,10 @@ export const dynamic = "force-dynamic"; // compares them, and refuses in the form's own sentence. Every other refusal is // the form's too: a busy channel, media in transition. // +// Every site whose pool or cited scope named the channel is rewritten without +// it (through writeSite) and named in `sitesUpdated`; a site whose write is +// refused is a `warnings` line. +// // There is no undo, and transcripts/ is its own git repo — the only way back // is a commit there. export async function POST(request: Request) { @@ -21,6 +25,12 @@ export async function POST(request: Request) { fd.set("confirmSlug", reqString(body, "confirm")); const result = await deleteChannelFromForm(slug, fd); if (!result.ok) return opsFail(result.error); - return NextResponse.json({ ok: true, slug: result.slug, deleted: true }); + return NextResponse.json({ + ok: true, + slug: result.slug, + deleted: true, + sitesUpdated: result.sitesUpdated ?? [], + ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}), + }); }); } diff --git a/editor/app/api/ops/transcribe-one/route.test.ts b/editor/app/api/ops/transcribe-one/route.test.ts @@ -214,3 +214,60 @@ test("English captions listed and no audio: the captions are fetched instead; as assert.equal(bad.status, 400); assert.match(String(bad.body.error), /"asr" must be a boolean/); }); + +// 4 Nov: a transcribe-one on a video that was LIVE downloaded the HLS at 1x and +// held platform:youtube for the stream's length. Its record says so, and the +// door refuses it with the commands that do the right thing — nothing queued. +// The audio, or a container, already here owes no download and is transcribed. +test("a live, scheduled or processing stream is refused before anything is queued; with its audio here it transcribes", async () => { + const before = (await corpus.listJobIds()).length; + await video("liveHHHHHHH", { live_status: "is_live", is_live: true }); + const live = await callPost(POST, { slug: SLUG, id: "liveHHHHHHH", asr: true }); + assert.equal(live.status, 400, JSON.stringify(live.body)); + assert.match(String(live.body.error), /^liveHHHHHHH is live now \(live_status is_live\): a download would read the stream at 1x/); + assert.ok( + String(live.body.error).includes(`pnpm ops record-live --json '{"slug":"${SLUG}","id":"liveHHHHHHH"}'`), + String(live.body.error), + ); + // Without "asr" and with no captions listed: the audio download is next, refused. + const plain = await callPost(POST, { slug: SLUG, id: "liveHHHHHHH" }); + assert.equal(plain.status, 400); + assert.match(String(plain.body.error), /is live now/); + + await video("upcomingIII", { live_status: "is_upcoming" }); + const upcoming = await callPost(POST, { slug: SLUG, id: "upcomingIII" }); + assert.equal(upcoming.status, 400); + assert.match(String(upcoming.body.error), /scheduled stream that has not started/); + + await video("postliveJJJ", { live_status: "post_live" }); + const post = await callPost(POST, { slug: SLUG, id: "postliveJJJ" }); + assert.equal(post.status, 400); + assert.match(String(post.body.error), /VOD is still being processed/); + assert.equal((await corpus.listJobIds()).length, before, "nothing was queued"); + + // A (possibly stale) live record with English captions listed: the captions + // fetch is no audio download, so it goes through; asr: true is refused. + const captions = { automatic_captions: { en: [{ ext: "vtt", url: "https://example.invalid/en.vtt" }] } }; + await video("livecapsMMM", { live_status: "post_live", ...captions }); + const caps = await callPost(POST, { slug: SLUG, id: "livecapsMMM" }); + assert.equal(caps.status, 200, JSON.stringify(caps.body)); + assert.equal(caps.body.instead, "captions"); + await until("the live video's caption fetch", () => ended(String(caps.body.jobId))); + await video("livecapsNNN", { live_status: "is_live", ...captions }); + const capsAsr = await callPost(POST, { slug: SLUG, id: "livecapsNNN", asr: true }); + assert.equal(capsAsr.status, 400); + assert.match(String(capsAsr.body.error), /livecapsNNN is live now/); + + // A finished stream (was_live) downloads as any video does. + await video("wasliveKKKK", { live_status: "was_live" }); + const vod = await callPost(POST, { slug: SLUG, id: "wasliveKKKK", asr: true }); + assert.equal(vod.status, 200, JSON.stringify(vod.body)); + await until("the VOD's audio download", () => ended(String(vod.body.jobId))); + + // Audio already on disk: nothing to download, so nothing to refuse. + await video("liveaudioLL", { live_status: "is_live" }, { "audio.mp3": "fake audio\n" }); + const here = await callPost(POST, { slug: SLUG, id: "liveaudioLL" }); + assert.equal(here.status, 200, JSON.stringify(here.body)); + assert.equal(job(String(here.body.jobId)).kind, "transcribe-one"); + await until("the on-disk transcription", () => ended(String(here.body.jobId))); +}); diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -31,6 +31,7 @@ import { isEnglishCaptionTrack, readListedCaptionTracks, } from "yt-dlp-transcript-common/lib/listedCaptions-server"; +import { liveDownloadRefusalFor } from "yt-dlp-transcript-common/lib/liveNow-server"; import { clipWindowQueueKey, downloadQueueKey, @@ -729,6 +730,9 @@ export async function whisperVideoAction( }; const firstEntries = await readdir(videoDir).catch(() => [] as string[]); const audioOnDisk = firstEntries.some(isRealAudioFile); + const firstHeld = audioOnDisk + ? null + : await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries }); if (!audioOnDisk && asr !== true && r.config.handling === "youtube") { const onDisk = englishVttsByPreference(firstEntries); @@ -772,20 +776,29 @@ export async function whisperVideoAction( prelude: [`Audio already on disk for ${videoId}; skipping download.`], }); } - } else { - const held = await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries }); - if (held?.kind === "container") { - return queueTranscribeOne({ - slug, - videoId, - config: r.config, - audioFilename, - queueKey: transcribeQueue, - fullAudioFirst: false, - ...opts, - prelude: [containerLine(videoId, held)], - }); - } + } else if (firstHeld?.kind === "container") { + return queueTranscribeOne({ + slug, + videoId, + config: r.config, + audioFilename, + queueKey: transcribeQueue, + fullAudioFirst: false, + ...opts, + prelude: [containerLine(videoId, firstHeld)], + }); + } + + // A STREAM IN PROGRESS IS NEVER DOWNLOADED FOR A TRANSCRIPTION (4 Nov): the + // one-video download would read the HLS at 1x and hold the platform's queue + // for the stream's length. Refused while its record says it is live, + // scheduled or still processing — only here, where the audio download is + // what comes next: audio or a container already here owes no download, and + // a captions-only fetch (above) is harmless, the managed path skipping a + // stream that really is live. lib/liveNow.ts. + if (!audioOnDisk) { + const live = await liveDownloadRefusalFor(videoDir, { slug, videoId }); + if (live) return { ok: false, error: live }; } const platformQueue = videoQueueKey(r.config, queueKey); @@ -816,6 +829,10 @@ export async function whisperVideoAction( if (held?.kind === "no-audio") { onLog(`The container ${held.file} has no sound; downloading the audio instead.`); } + // The door's live check again, at the moment of the download: the + // record may have been re-read while this job waited for its queue. + const live = await liveDownloadRefusalFor(videoDir, { slug, videoId }); + if (live) throw new Error(live); // Only this branch writes bytes. Transcribing audio that is already on // disk produces a transcript.json measured in kilobytes, so a low disk // is no reason to refuse it — the gate belongs on the fetch, not on the diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -22,6 +22,7 @@ import { readChannelConfig, } from "yt-dlp-transcript-common/controller/channels"; import { renameChannel } from "yt-dlp-transcript-common/controller/renameChannel"; +import { dropChannelFromSites } from "yt-dlp-transcript-common/controller/siteMemberships"; import { inspectChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia"; import { channelMediaBusyReason } from "./lib/mediaBusy"; import { @@ -39,7 +40,7 @@ import { import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site"; import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config"; -import { saveSettings } from "../settings/saveSettings"; +import { saveSettings, saveSettingsHeld, withSettingsLock } from "../settings/saveSettings"; import { LANES, type AutoQueueKind, @@ -53,6 +54,8 @@ import { isChannelPaused, clearAutoPause, isDefaultChannelPriority, + placeChannelRank, + RankPlacementError, rankOf, renameChannelInPriority, resolveFocusSlugs, @@ -62,6 +65,7 @@ import { type ChannelPriority, type ChannelPriorityEntry, type PriorityOperation, + type RankPlacement, type SiteChannelIndex, type StoredChannelTier, } from "yt-dlp-transcript-common/lib/channelPriority"; @@ -215,6 +219,9 @@ export type ChannelLifecycleResult = jobIds: string[]; // Non-fatal problems after the move (rename's metadata migration). warnings: string[]; + // Delete: the sites whose pool or cited scope named the channel and + // were rewritten without it. + sitesUpdated?: string[]; } | ({ ok: false } & NonNullable<FormErrorState>); @@ -356,15 +363,18 @@ export async function updateChannelAction( formData: FormData, ): Promise<ActionResult> { const values = formValues(formData); + const paths = getPaths(); + const existing = await readChannelConfig(paths, slug); + if (!existing) return { error: `Channel "${slug}" not found`, values }; let parsed; try { - parsed = parseChannelForm(formData); + parsed = parseChannelForm(formData, { stored: existing }); } catch (e) { return { error: (e as Error).message, values }; } - const paths = getPaths(); - const existing = await readChannelConfig(paths, slug); - if (!existing) return { error: `Channel "${slug}" not found`, values }; + // A stored value today's checks refuse, saved unchanged: the save stands. + // The form has no place for a warning, so the server log says it. + for (const w of parsed.warnings) console.warn(`Channel ${slug} saved with a warning: ${w}`); // Plan the site-membership writes (Sites section) before touching anything, // so bad input errors out with no partial write. Null = field absent // (zero sites configured / legacy submit) → leave memberships alone. @@ -691,6 +701,17 @@ export async function deleteChannelFromForm( } catch (e) { return fail((e as Error).message); } + // NO SITE GOES ON NAMING IT (9 Nov: a deleted channel stayed in a site's + // pool). Each site that names it is rewritten through writeSite; one whose + // write is refused is a warning — the channel is gone either way. + const sites = await dropChannelFromSites(getPaths(), slug).catch((e: Error) => ({ + updated: [] as string[], + failed: [{ siteId: "*", error: e.message }], + })); + const warnings = sites.failed.map( + (f) => `Site "${f.siteId}" still names "${slug}": its update was refused: ${f.error}`, + ); + if (warnings.length > 0) console.warn(`Channel delete ${slug}:`, warnings.join("; ")); // Same reason as createChannelAction: the deleted channel keeps a leaf in // every compiled tree until something recompiles. A leaf matching nothing is // harmless to dispatch and confusing to read. @@ -701,7 +722,8 @@ export async function deleteChannelFromForm( } revalidatePath("/channels"); revalidatePath("/"); - return { ok: true, slug, jobIds: [], warnings: [] }; + if (sites.updated.length > 0) revalidatePath("/sites"); + return { ok: true, slug, jobIds: [], warnings, sitesUpdated: sites.updated }; } // Change a channel's slug (its on-disk directory name). High-friction: the @@ -837,6 +859,10 @@ export type ChannelPriorityEdit = // `paused` channel ranked first is still behind (or absent from) every // normal one. See prioritizeChannelDownloadAction. | { kind: "promote"; slug: string } + // ONE CHANNEL MOVED IN THE ORDER (`pnpm ops channel-rank`): its rank alone, + // every other channel's order kept — placeChannelRank in the model. No tier, + // override, focus or lane changes, unlike promote. + | { kind: "rank"; slug: string; place: RankPlacement } // NOT AN EDIT: the channel POPULATION changed (a channel was created or // deleted), so the four trees have to be re-derived from an unchanged // document. Never seeds — see the writer. @@ -868,6 +894,7 @@ function applyPriorityEdit( return renameChannelInPriority(model, edit.from, edit.to); } if (edit.kind === "focus") return { ...model, focus: edit.focus }; + if (edit.kind === "rank") return placeChannelRank(model, edit.slug, edit.place); if (edit.kind === "promote") { const slug = edit.slug.trim(); if (!slug) return model; @@ -952,86 +979,119 @@ export async function saveChannelPriorityAction( opts?: { enableLanes?: readonly AutoQueueKind[] }, ): Promise<ActionResult> { const paths = getPaths(); - const settings = getSettings(); - const stored = settings.channelPriority; + // The channel population first, OUTSIDE the lock: it is a directory read, + // and nothing below writes it. const configs = await listChannelConfigs(paths); const slugs = configs.map((c) => c.slug); - // THE LEGACY SEED, and it is the difference between this feature shipping - // and this feature destroying the two hand-made 9+9 lane orders on its first - // click (the S2/S3 review, finding 3, restated with its mechanism in 8). - // - // `laneDispatchRoot` is all-or-nothing on `isDefaultChannelPriority`: the - // moment a document says ANYTHING, the stored trees stop being dispatched - // from and the compiled ones take over. A first click that set one tier and - // nothing else would therefore compile a tree in which no channel has a rank - // — every one of them alphabetical inside `prio-normal` — and the operator's - // order would be gone with no way back, because the trees it was written in - // have just been overwritten. - // - // So: when the stored document says nothing AND the stored trees are not - // already compiled, derive the document the migration would have produced - // and apply the edit on top of THAT. The corpus's existing order survives a - // first click by an operator who never ran the migration. - // - // NOT ON A `recompile` OR A `rename`: creating or renaming a channel is not - // an operator's statement about priority, and neither must silently switch a - // corpus from its stored trees to compiled ones. - const base = - edit.kind !== "recompile" && - edit.kind !== "rename" && - isDefaultChannelPriority(stored) && - !hasCompiledLaneRoots(settings.autoQueue) - ? channelPriorityFromLegacy( - // THE SEED READS THE LANE ORDERS, NOT THE FLAG. `excludeFromSync` is - // deleted and `parseChannelConfig` drops the key, so nothing the - // editor can read still carries it — turning those 15 channels into - // `overrides: {sync:"paused"}` is the migration script's half, off - // the raw config.json. What this seed is for is the ORDER, and the - // order lives in the stored trees. - configs.map((c) => ({ slug: c.slug, config: {} })), - settings.autoQueue, - ) - : stored; - const next = sanitizeChannelPriority(applyPriorityEdit(base, edit)); - // WHEN A DEFAULT DOCUMENT STILL HAS TO COMPILE, and the two halves of the - // question are different corpora. - // - // The runner's bypass means a default document dispatches from the STORED - // tree, so what matters here is what that stored tree is: - // - // never compiled (hand-made, or the shipped default) -> LEAVE IT. This is - // the same rule `laneDispatchRoot` applies, and compiling over it would - // replace an operator's tree with an all-normal one at the moment the last - // priority was cleared. - // - // already compiled -> RECOMPILE, even for a default document. Ending a - // focus leaves the document saying nothing while every stored root still - // opens with `prio-focus` — and the runner, back on its bypass, would - // dispatch from exactly that tree and go on holding the channels the focus - // was just ended for. There is no hand-made tree left to protect on a - // corpus whose roots the compiler already wrote. - const autoQueue = { ...settings.autoQueue }; - if ( - !isDefaultChannelPriority(next) || - hasCompiledLaneRoots(settings.autoQueue) - ) { - const focusSlugs = resolveFocusSlugs(next, siteChannelIndex(paths), slugs); - const roots = compileLanes(next, slugs, focusSlugs); - for (const lane of LANES) { - autoQueue[lane] = { ...settings.autoQueue[lane], root: roots[lane] }; + // THE READ-MODIFY-WRITE IS SERIALIZED (review of lane editor-gaps): the + // document is read INSIDE the settings lock and written before it is let go, + // so a concurrent deck save or a parallel `channel-rank` is never written + // over with a copy read before it landed. Every saveSettings takes the same + // lock (settings/saveSettings.ts). + const saved = await withSettingsLock(async (): Promise<ActionResult | "saved"> => { + const settings = getSettings(); + const stored = settings.channelPriority; + // THE LEGACY SEED, and it is the difference between this feature shipping + // and this feature destroying the two hand-made 9+9 lane orders on its first + // click (the S2/S3 review, finding 3, restated with its mechanism in 8). + // + // `laneDispatchRoot` is all-or-nothing on `isDefaultChannelPriority`: the + // moment a document says ANYTHING, the stored trees stop being dispatched + // from and the compiled ones take over. A first click that set one tier and + // nothing else would therefore compile a tree in which no channel has a rank + // — every one of them alphabetical inside `prio-normal` — and the operator's + // order would be gone with no way back, because the trees it was written in + // have just been overwritten. + // + // So: when the stored document says nothing AND the stored trees are not + // already compiled, derive the document the migration would have produced + // and apply the edit on top of THAT. The corpus's existing order survives a + // first click by an operator who never ran the migration. + // + // NOT ON A `recompile` OR A `rename`: creating or renaming a channel is not + // an operator's statement about priority, and neither must silently switch a + // corpus from its stored trees to compiled ones. + const base = + edit.kind !== "recompile" && + edit.kind !== "rename" && + isDefaultChannelPriority(stored) && + !hasCompiledLaneRoots(settings.autoQueue) + ? channelPriorityFromLegacy( + // THE SEED READS THE LANE ORDERS, NOT THE FLAG. `excludeFromSync` is + // deleted and `parseChannelConfig` drops the key, so nothing the + // editor can read still carries it — turning those 15 channels into + // `overrides: {sync:"paused"}` is the migration script's half, off + // the raw config.json. What this seed is for is the ORDER, and the + // order lives in the stored trees. + configs.map((c) => ({ slug: c.slug, config: {} })), + settings.autoQueue, + ) + : stored; + let next: ChannelPriority; + try { + next = sanitizeChannelPriority(applyPriorityEdit(base, edit)); + } catch (e) { + // A placement the document cannot carry out (next to an unranked channel, + // a rank that is not one) is the caller's to fix, said before any write. + if (e instanceof RankPlacementError) return { error: e.message }; + throw e; } - } - for (const lane of opts?.enableLanes ?? []) { - autoQueue[lane] = { ...autoQueue[lane], enabled: true }; - } - try { - // BOTH BLOCKS IN ONE WRITE — the reason saveSettings takes a whole-settings - // patch rather than one block. `channelPriority` is a full document (its - // `channels` map replaces), and `autoQueue` carries all four lanes. - await saveSettings({ channelPriority: next, autoQueue }); - } catch (e) { - return { error: (e as Error).message }; - } + // A rank the sanitizer drops: a channel paused for every operation is in no + // group anywhere, so it orders nothing and its rank is not kept. Said, not + // saved as a silent no-op. + if ( + edit.kind === "rank" && + edit.place.kind !== "unrank" && + next.channels[edit.slug.trim()]?.rank === undefined + ) { + return { + error: + `"${edit.slug.trim()}" is paused for every operation, so it is in no order a rank could place it in — ` + + `give it a tier first (pnpm ops channel-priority), then rank it.`, + }; + } + // WHEN A DEFAULT DOCUMENT STILL HAS TO COMPILE, and the two halves of the + // question are different corpora. + // + // The runner's bypass means a default document dispatches from the STORED + // tree, so what matters here is what that stored tree is: + // + // never compiled (hand-made, or the shipped default) -> LEAVE IT. This is + // the same rule `laneDispatchRoot` applies, and compiling over it would + // replace an operator's tree with an all-normal one at the moment the last + // priority was cleared. + // + // already compiled -> RECOMPILE, even for a default document. Ending a + // focus leaves the document saying nothing while every stored root still + // opens with `prio-focus` — and the runner, back on its bypass, would + // dispatch from exactly that tree and go on holding the channels the focus + // was just ended for. There is no hand-made tree left to protect on a + // corpus whose roots the compiler already wrote. + const autoQueue = { ...settings.autoQueue }; + if ( + !isDefaultChannelPriority(next) || + hasCompiledLaneRoots(settings.autoQueue) + ) { + const focusSlugs = resolveFocusSlugs(next, siteChannelIndex(paths), slugs); + const roots = compileLanes(next, slugs, focusSlugs); + for (const lane of LANES) { + autoQueue[lane] = { ...settings.autoQueue[lane], root: roots[lane] }; + } + } + for (const lane of opts?.enableLanes ?? []) { + autoQueue[lane] = { ...autoQueue[lane], enabled: true }; + } + try { + // BOTH BLOCKS IN ONE WRITE — the reason saveSettings takes a whole-settings + // patch rather than one block. `channelPriority` is a full document (its + // `channels` map replaces), and `autoQueue` carries all four lanes. + await saveSettingsHeld({ channelPriority: next, autoQueue }); + } catch (e) { + return { error: (e as Error).message }; + } + return "saved"; + }); + if (saved !== "saved") return saved; revalidatePath("/channels"); revalidatePath("/operations"); revalidatePath("/operations/[id]", "page"); @@ -1116,6 +1176,18 @@ export async function prioritizeChannelDownloadPriorityAction( ); } +// Place one channel in the order (`pnpm ops channel-rank`): rank n, top, +// bottom, before or after another ranked channel, or unranked. Through the one +// writer, so the four lane roots are recompiled in the same write. +export async function setChannelRankAction( + slug: string, + place: RankPlacement, +): Promise<ActionResult> { + const trimmed = (slug ?? "").trim(); + if (!trimmed) return { error: "No channel slug supplied." }; + return saveChannelPriorityAction({ kind: "rank", slug: trimmed, place }); +} + export async function endFocusAction(): Promise<ActionResult> { return saveChannelPriorityAction({ kind: "focus", focus: { kind: "none" } }); } diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -358,6 +358,31 @@ test("subLangs and chat: parsed, refused when unknown, round-tripped through the assert.equal("chat" in cleared, false); }); +// Caption languages are checked at the save (lane editor-gaps): a value +// yt-dlp's --sub-langs cannot use is refused in the field's words, on the form +// and through the ops patch alike; spaces around an entry are dropped. +test("subLangs: a value --sub-langs cannot use is refused; spaces around entries are dropped", () => { + assert.equal(parseChannelForm(form({ subLangs: "en.* , es" })).config.subLangs, "en.*,es"); + assert.equal(parseChannelForm(form({ subLangs: "all,-live_chat" })).config.subLangs, "all,-live_chat"); + assert.throws(() => parseChannelForm(form({ subLangs: "en,,es" })), /^Error: Caption languages has an empty entry/); + assert.throws(() => parseChannelForm(form({ subLangs: "en us" })), /Caption languages entry "en us" has a space in it/); + assert.throws( + () => parseChannelForm(form({ subLangs: "en(" })), + /Caption languages entry "en\(" is not a valid regular expression/, + ); + const fd = channelConfigToFormData({ handling: "youtube", name: "Example VODs" }); + applyChannelFormPatch(fd, { subLangs: "en,(" }); + assert.throws(() => parseChannelForm(fd), /Caption languages entry "\(" is not a valid regular expression/); + // A value saved before the check, submitted unchanged, does not lock the + // form: kept as stored, with a warning. Changed, it is refused. + const stored = { subLangs: "en us" }; + const kept = parseChannelForm(form({ subLangs: "en us" }), { stored }); + assert.equal(kept.config.subLangs, "en us"); + assert.match(kept.warnings[0] ?? "", /Caption languages entry "en us" has a space in it .*\. Kept as stored, since it is unchanged/); + assert.throws(() => parseChannelForm(form({ subLangs: "en uk" }), { stored }), /has a space in it/); + assert.deepEqual(parseChannelForm(form({ subLangs: "en.*" }), { stored }).warnings, []); +}); + // 2026-10-29: manual downloads (lib/manualDownloads.ts) are a Configure field // and a `channel-config` patch key — and the operator's two-step recipe (set // manual, THEN clear the download filter) must keep the mode across the second diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -10,6 +10,8 @@ import { KEEP_LATEST_MAX, SYNC_INTERVAL_MAX_MINUTES, SYNC_INTERVAL_MIN_MINUTES, + normalizeSubLangs, + subLangsProblem, type AudioCheckConfig, type ExtractionMode, } from "yt-dlp-transcript-common/lib/channelConfig"; @@ -59,6 +61,16 @@ export type ParsedChannelForm = { name: string; slug: string; config: ChannelConfig; + // Saved, but said: a stored value the form's checks would refuse today, + // submitted unchanged (see `stored`). + warnings: string[]; +}; + +// What a Configure save knows of the channel as stored. A check added after a +// value was saved (caption languages, lane editor-gaps) must not lock the form +// on it: the stored value, submitted unchanged, is kept with a warning. +export type ParseChannelFormContext = { + stored?: Pick<ChannelConfig, "subLangs"> | null; }; // ChannelConfig keys the form authoritatively controls. updateChannelAction @@ -104,7 +116,11 @@ export const CHANNEL_FORM_FIELDS = [ // Maps FormData -> ChannelConfig. Throws on invalid input so the server // action can render an error message. -export function parseChannelForm(formData: FormData): ParsedChannelForm { +export function parseChannelForm( + formData: FormData, + ctx: ParseChannelFormContext = {}, +): ParsedChannelForm { + const warnings: string[] = []; const name = String(formData.get("name") ?? "").trim(); if (!name) throw new Error("Name is required"); @@ -291,7 +307,19 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { // Caption languages and the live chat (2026-10-26). Blank = the default // (`en.*,live_chat`), omitted; "with-download" is the default chat mode, // omitted too, so choosing it clears a stored mode. - const subLangs = stringOrUndef(formData, "subLangs"); + const subLangsRaw = stringOrUndef(formData, "subLangs"); + let subLangs = subLangsRaw ? normalizeSubLangs(subLangsRaw) : undefined; + if (subLangsRaw) { + const problem = subLangsProblem(subLangsRaw); + const stored = ctx.stored?.subLangs?.trim(); + if (problem && stored && normalizeSubLangs(stored) === subLangs) { + // Unchanged from what is stored: kept as stored, and said. + subLangs = stored; + warnings.push(`Caption languages ${problem}. Kept as stored, since it is unchanged; yt-dlp may refuse it.`); + } else if (problem) { + throw new Error(`Caption languages ${problem}`); + } + } const chatRaw = String(formData.get("chat") ?? "").trim(); if (chatRaw && !isChatMode(chatRaw)) { throw new Error(`Live chat must be one of: ${CHAT_MODES.join(", ")}`); @@ -502,7 +530,7 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { if (wayback) config.wayback = wayback; if (xSearch) config.xSearch = xSearch; - return { name, slug, config }; + return { name, slug, config, warnings }; } // The platform select's value for an X search channel: not a platform (the diff --git a/editor/app/settings/saveSettings.test.ts b/editor/app/settings/saveSettings.test.ts @@ -18,7 +18,7 @@ const ROOT = mkdtempSync(path.join(os.tmpdir(), "save-settings-")); process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); -const { mergeSettingsPatch, saveSettings } = await import("./saveSettings"); +const { mergeSettingsPatch, saveSettings, saveSettingsHeld, withSettingsLock } = await import("./saveSettings"); const { defaultSiteSettings, getSettings } = await import( "yt-dlp-transcript-common/lib/settings" ); @@ -134,3 +134,26 @@ test("an icon stored by an older build survives unrelated saves; editing it is c { ...stored, svg: `<svg aria-hidden="true" fill="currentColor" viewBox="0 0 8 8"><path d="M0 0"/></svg>` }, ]); }); + +// THE LOCK (review of lane editor-gaps): a long read-modify-write held under +// withSettingsLock is not written over by a save that starts while it runs — +// the save waits, reads what the held writer wrote, and keeps both changes. +test("a save waits for a held read-modify-write and keeps its change", async () => { + writeFileSync(process.env.SETTINGS_FILE!, JSON.stringify(defaultSiteSettings())); + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + const held = withSettingsLock(async () => { + const read = getSettings(); + await gate; // an await between the read and the write, as the priority writer has + // The whole document as read, as a writer of a full block does: a save + // that slipped in between would be written over. + await saveSettingsHeld({ ...read, syncScheduler: { ...read.syncScheduler, maxConcurrentSyncs: 5 } }); + }); + const other = saveSettings({ minFreeDiskGB: 42 }); + await new Promise((r) => setTimeout(r, 20)); + release(); + await Promise.all([held, other]); + const after = getSettings(); + assert.equal(after.syncScheduler.maxConcurrentSyncs, 5); + assert.equal(after.minFreeDiskGB, 42, "the later save read the held writer's result"); +}); diff --git a/editor/app/settings/saveSettings.ts b/editor/app/settings/saveSettings.ts @@ -3,6 +3,8 @@ import { writeSettings, type SiteSettings, } from "yt-dlp-transcript-common/lib/settings"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { withJsonFileLock } from "yt-dlp-transcript-common/lib/jsonFile-server"; // THE EDITOR'S ONE SETTINGS WRITER (one-core phase 3 slice 4a). // @@ -53,6 +55,24 @@ export function mergeSettingsPatch( return merged as SiteSettings; } -export async function saveSettings(patch: Patch): Promise<void> { +// THE SETTINGS LOCK (review of lane editor-gaps). A save reads the file, +// merges and writes; two saves that interleave — one reading before the other +// has written — lose the first one's change. Every save runs inside the lock +// on settings.json, so the read and the write of one save never straddle +// another's. A writer whose read-modify-write is longer than one patch (the +// channel-priority writer reads the document, compiles the lane roots and +// writes both) takes the lock itself and saves with `saveSettingsHeld`. +// Per process (withJsonFileLock); NOT re-entrant: never call saveSettings +// from inside withSettingsLock. +export function withSettingsLock<T>(fn: () => Promise<T>): Promise<T> { + return withJsonFileLock(getPaths().settingsFile, fn); +} + +// A save for a caller already holding the lock. +export async function saveSettingsHeld(patch: Patch): Promise<void> { await writeSettings(mergeSettingsPatch(getSettings(), patch)); } + +export async function saveSettings(patch: Patch): Promise<void> { + await withSettingsLock(() => saveSettingsHeld(patch)); +} diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts @@ -1,33 +1,7 @@ "use server"; -import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { - parseAccent, - parseAccentSetting, -} from "yt-dlp-transcript-common/lib/accent"; -import { - DEFAULT_ACCENT, - wordmarkLeadFor, -} from "yt-dlp-transcript-common/lib/brand"; -import { - getSite, - writeSite, - isValidSiteId, - reservedSiteIdProblem, - parseRelatedSites, - parseSiteChannels, - parseSiteUrl, - type Site, -} from "yt-dlp-transcript-common/lib/site"; -import { - parseSocialLinks, - type SocialLink, -} from "yt-dlp-transcript-common/lib/settings"; -import { - parseChannelGroups, - resolveDefaultGroupId, -} from "yt-dlp-transcript-common/lib/channelGroups"; +import { isValidSiteId, withSiteLock } from "yt-dlp-transcript-common/lib/site"; import { migrateToSites } from "yt-dlp-transcript-common/controller/migrateToSites"; import { SiteDeleteRefusedError, @@ -36,288 +10,21 @@ import { siteDeleteBlocked, type SiteDeletePlan, } from "yt-dlp-transcript-common/publish/siteDelete"; -import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks"; -import { formValues, type FormState, type FormValues } from "../lib/formState"; -import { reportSiteKeysFromForm } from "./lib/reportSiteKeys"; -import { citedChannelsFromForm } from "./lib/citedChannelsFromForm"; +import { saveSiteFromForm, type SaveResult } from "./lib/saveSiteForm"; -// A failure carries what was submitted, so SiteForm keeps what was typed -// (lib/formState.ts). -export type SaveResult = FormState<{ siteId: string; values: FormValues }>; +export type { SaveResult } from "./lib/saveSiteForm"; +// The site form's Save: the save under the site's lock (lib/site.ts +// withSiteLock), so it and a concurrent patch of the same site (the Reports +// tab's pages, a channel delete's membership patch) never interleave. An +// invalid id has no file to lock; the save refuses it in its own words. export async function saveSiteAction( _prev: SaveResult | undefined, formData: FormData, ): Promise<SaveResult> { - const values = formValues(formData); const siteId = String(formData.get("siteId") ?? "").trim(); - if (!isValidSiteId(siteId)) { - return { - ok: false, - error: "Site ID must be lowercase letters, numbers, and hyphens.", - values, - }; - } - // `articles` and `new` are the editor's own /sites/ routes (writeSite refuses - // them too): said here, before anything else is read. - const reserved = reservedSiteIdProblem(siteId); - if (reserved) return { ok: false, error: reserved, values }; - const siteTitle = String(formData.get("siteTitle") ?? "").trim(); - const headerTitle = String(formData.get("headerTitle") ?? "").trim(); - if (!siteTitle) { - return { ok: false, error: "Site title is required", values }; - } - if (!headerTitle) { - return { ok: false, error: "Header title is required", values }; - } - const siteDescription = String(formData.get("siteDescription") ?? "").trim(); - const homeTagline = String(formData.get("homeTagline") ?? "").trim(); - // The wordmark's heavy lead must be a proper prefix of the header title; - // lib/siteSchema.ts would silently drop anything else, so say so here. - const wordmarkLead = String(formData.get("wordmarkLead") ?? "").trim(); - if (wordmarkLead && !wordmarkLeadFor(headerTitle, wordmarkLead)) { - return { - ok: false, - error: `Wordmark lead must be how the header title starts, same case, and shorter than it (e.g. "Jer" for "Jeralyzer") — or left blank.`, - values, - }; - } - // Brand accent: a named id from the radio group, or "custom" + its hex - // field. The default (Signal) is stored as absent — the two read the same. - // A bare hex in `accent` (a form from before the radio group) is taken as - // a custom colour. - const accentChoice = String(formData.get("accent") ?? "").trim(); - const accentCustomRaw = String(formData.get("accentCustom") ?? "").trim(); - let accent: string | undefined; - if (accentChoice === "custom") { - accent = parseAccent(accentCustomRaw); - if (!accent) { - return { - ok: false, - error: "Custom accent must be a hex color like #cc3366.", - values, - }; - } - } else if (accentChoice) { - accent = parseAccentSetting(accentChoice); - if (!accent) { - return { - ok: false, - error: `Unknown brand accent "${accentChoice}".`, - values, - }; - } - if (accent === DEFAULT_ACCENT) accent = undefined; - } - const cloudflareProject = String( - formData.get("cloudflareProject") ?? "", - ).trim(); - const siteUrlRaw = String(formData.get("siteUrl") ?? "").trim(); - if (siteUrlRaw && !parseSiteUrl(siteUrlRaw)) { - return { - ok: false, - error: "Public URL must be an absolute http(s):// URL, or left blank.", - values, - }; - } - const siteUrl = parseSiteUrl(siteUrlRaw); - // Listed on the homepage and hub by default: the same opt-out idiom as - // archives below (an unchecked box sends no key → persisted as false). - const listed = formData.get("listed") === "on"; - // Who the site is built for (release 17 slice XP): only "private" is kept. - const audienceRaw = String(formData.get("audience") ?? "public"); - if (audienceRaw !== "public" && audienceRaw !== "private") { - return { ok: false, error: `Unknown audience "${audienceRaw}".`, values }; - } - const isPrivate = audienceRaw === "private"; - // The publish lane's policy for this site (release 18). writeSite refuses a - // deploying policy with no Pages project (sitePublishProblem) and stores a - // private site's as "build". - const publishAutoRaw = String(formData.get("publishAuto") ?? "off"); - if (!(PUBLISH_POLICIES as readonly string[]).includes(publishAutoRaw)) { - return { ok: false, error: `Unknown publish policy "${publishAutoRaw}".`, values }; - } - const publishAuto = publishAutoRaw as PublishPolicy; - // Search (opt-out; off = pages only) and the page list, which is not on - // this form: the stored one is carried over. - let storedReports: Pick<Site, "pages"> | undefined; - try { - storedReports = getSite(siteId, getPaths()); - } catch { - storedReports = undefined; - } - const reportKeys = reportSiteKeysFromForm(formData, storedReports); - - // Hub parent (per-site override of the family default) + PWA opt-in. - const hubUrlRaw = String(formData.get("hubUrl") ?? "").trim(); - if (hubUrlRaw && !parseSiteUrl(hubUrlRaw)) { - return { - ok: false, - error: "Hub URL must be an absolute http(s):// URL, or left blank.", - values, - }; - } - const hubUrl = parseSiteUrl(hubUrlRaw); - const pwa = formData.get("pwa") === "on"; - // Archives default on: an unchecked (default-on) box yields no "archives" key - // → false → persisted as the explicit opt-out. - const archives = formData.get("archives") === "on"; - // Duplicates default on, same opt-out idiom as archives. - const duplicates = formData.get("duplicates") === "on"; - // Per-video transcript downloads default on, same opt-out idiom. - const transcriptDownloads = formData.get("transcriptDownloads") === "on"; - const archiveMaxMBRaw = String(formData.get("archiveMaxMB") ?? "").trim(); - let archiveMaxBytes: number | undefined; - if (archiveMaxMBRaw) { - const mb = Number(archiveMaxMBRaw); - if (!Number.isFinite(mb) || mb < 0) { - return { - ok: false, - error: "Archive size cap must be a non-negative number of MB, or blank.", - values, - }; - } - archiveMaxBytes = Math.floor(mb * 1024 * 1024); - } - - let relatedSitesInput: unknown; - try { - relatedSitesInput = JSON.parse( - String(formData.get("relatedSitesJson") ?? "[]"), - ); - } catch { - return { ok: false, error: "Related sites payload is malformed", values }; - } - const relatedSites = parseRelatedSites(relatedSitesInput); - - let groupsInput: unknown; - try { - groupsInput = JSON.parse(String(formData.get("groupsJson") ?? "[]")); - } catch { - return { ok: false, error: "Channel groups payload is malformed", values }; - } - const groups = parseChannelGroups(groupsInput); - if (groups.length === 0) { - return { - ok: false, - error: "At least one channel group is required (check ID/name fields)", - values, - }; - } - const defaultGroupIdRaw = String(formData.get("defaultGroupId") ?? "").trim(); - const defaultGroupId = resolveDefaultGroupId(defaultGroupIdRaw, groups); - if (defaultGroupIdRaw && defaultGroupIdRaw !== defaultGroupId) { - return { - ok: false, - error: `Default group "${defaultGroupIdRaw}" is not among the configured group IDs`, - values, - }; - } - - // When inheriting, leave socialLinks undefined so writeSite omits the key and - // the site falls back to the global default at render time. - const inheritSocialLinks = formData.get("inheritSocialLinks") === "on"; - let socialLinks: SocialLink[] | undefined; - if (!inheritSocialLinks) { - let socialInput: unknown; - try { - socialInput = JSON.parse(String(formData.get("socialLinksJson") ?? "[]")); - } catch { - return { ok: false, error: "Social links payload is malformed", values }; - } - const socialParsed = parseSocialLinks(socialInput); - if ( - Array.isArray(socialInput) && - socialParsed.length !== socialInput.length - ) { - return { - ok: false, - error: - "Each social link needs a label, URL (http(s)://, mailto:, or /), and SVG.", - values, - }; - } - // A link whose SVG is unchanged from the site's file is kept as it is; a - // new or edited one is checked (lib/socialLinks.ts socialLinksForSave). - let stored: SocialLink[] = []; - try { - stored = getSite(siteId, getPaths()).socialLinks ?? []; - } catch { - stored = []; - } - const checked = socialLinksForSave(socialParsed, stored); - if ("refused" in checked) { - return { - ok: false, - error: `Social link "${checked.refused.label}" has an invalid SVG: ${checked.refused.problem}.`, - values, - }; - } - socialLinks = checked.links; - } - - let channelsInput: unknown; - try { - channelsInput = JSON.parse(String(formData.get("channelsJson") ?? "[]")); - } catch { - return { - ok: false, - error: "Channel membership payload is malformed", - values, - }; - } - const channels = parseSiteChannels(channelsInput); - // The cited scope: channels outside the pool this site's reports may cite - // without publishing them (lib/citedChannelsFromForm.ts). - const citedChannels = citedChannelsFromForm(formData, channels); - if (citedChannels === null) { - return { ok: false, error: "Cited channels payload is malformed", values }; - } - - const site: Site = { - siteId, - siteTitle, - siteDescription, - headerTitle, - ...(wordmarkLead ? { wordmarkLead } : {}), - homeTagline, - ...(socialLinks !== undefined ? { socialLinks } : {}), - groups, - defaultGroupId, - channels, - ...(citedChannels.length > 0 ? { citedChannels } : {}), - ...(accent ? { accent } : {}), - ...(cloudflareProject ? { cloudflareProject } : {}), - ...(siteUrl ? { siteUrl } : {}), - // The Site is rebuilt from the form: a key missing here is dropped on save. - ...(listed ? {} : { listed: false }), - ...(isPrivate ? { audience: "private" as const } : {}), - ...(publishAuto !== "off" ? { publish: { auto: publishAuto } } : {}), - ...reportKeys, - ...(hubUrl ? { hubUrl } : {}), - ...(pwa ? { pwa: true } : {}), - ...(archives ? {} : { archives: false }), - ...(duplicates ? {} : { duplicates: false }), - ...(transcriptDownloads ? {} : { transcriptDownloads: false }), - ...(archiveMaxBytes !== undefined ? { archiveMaxBytes } : {}), - ...(relatedSites.length > 0 ? { relatedSites } : {}), - }; - try { - await writeSite(site, getPaths()); - } catch (err) { - return { - ok: false, - error: err instanceof Error ? err.message : String(err), - values, - }; - } - // NO revalidatePath (release 24 H5): React commits a revalidating action's - // state with the router's refresh of the page, which now and then did not - // settle until the next AutoRefresh tick, so "Saved." came up to ~6 s late. - // SiteForm seeds from `values` and refreshes the page itself once "Saved." is - // in (lib/formState.ts seedAfterSave, lib/useRefreshAfterSave.ts) — the h1 - // above the tabs and /sites's list follow with that refresh. - return { ok: true, siteId, values }; + if (!isValidSiteId(siteId)) return saveSiteFromForm(formData); + return withSiteLock(siteId, () => saveSiteFromForm(formData)); } export type DeleteResult = { ok: true } | { ok: false; error: string }; diff --git a/editor/app/sites/lib/saveSiteForm.ts b/editor/app/sites/lib/saveSiteForm.ts @@ -0,0 +1,317 @@ +// The site form's save (moved out of sites/actions.ts, review of lane +// editor-gaps, so a caller can hold the site's lock around it). NOT a "use +// server" module: saveSiteAction is the action a client may call. + +import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + parseAccent, + parseAccentSetting, +} from "yt-dlp-transcript-common/lib/accent"; +import { + DEFAULT_ACCENT, + wordmarkLeadFor, +} from "yt-dlp-transcript-common/lib/brand"; +import { + getSite, + writeSite, + isValidSiteId, + reservedSiteIdProblem, + parseRelatedSites, + parseSiteChannels, + parseSiteUrl, + type Site, +} from "yt-dlp-transcript-common/lib/site"; +import { + parseSocialLinks, + type SocialLink, +} from "yt-dlp-transcript-common/lib/settings"; +import { + parseChannelGroups, + resolveDefaultGroupId, +} from "yt-dlp-transcript-common/lib/channelGroups"; +import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks"; +import { formValues, type FormState, type FormValues } from "../../lib/formState"; +import { reportSiteKeysFromForm } from "./reportSiteKeys"; +import { citedChannelsFromForm } from "./citedChannelsFromForm"; + +// A failure carries what was submitted, so SiteForm keeps what was typed +// (lib/formState.ts). +export type SaveResult = FormState<{ siteId: string; values: FormValues }>; + +// THE SITE FORM'S SAVE, without its lock: the caller holds the site's lock +// (withSiteLock) around it, so the stored keys it carries over (the page +// list, unchanged social link SVGs) and the write are one read-modify-write. +// saveSiteAction is the form's; `pnpm ops create-site` takes the lock around +// its own read of the stored site as well. +export async function saveSiteFromForm(formData: FormData): Promise<SaveResult> { + const values = formValues(formData); + const siteId = String(formData.get("siteId") ?? "").trim(); + if (!isValidSiteId(siteId)) { + return { + ok: false, + error: "Site ID must be lowercase letters, numbers, and hyphens.", + values, + }; + } + // `articles` and `new` are the editor's own /sites/ routes (writeSite refuses + // them too): said here, before anything else is read. + const reserved = reservedSiteIdProblem(siteId); + if (reserved) return { ok: false, error: reserved, values }; + const siteTitle = String(formData.get("siteTitle") ?? "").trim(); + const headerTitle = String(formData.get("headerTitle") ?? "").trim(); + if (!siteTitle) { + return { ok: false, error: "Site title is required", values }; + } + if (!headerTitle) { + return { ok: false, error: "Header title is required", values }; + } + const siteDescription = String(formData.get("siteDescription") ?? "").trim(); + const homeTagline = String(formData.get("homeTagline") ?? "").trim(); + // The wordmark's heavy lead must be a proper prefix of the header title; + // lib/siteSchema.ts would silently drop anything else, so say so here. + const wordmarkLead = String(formData.get("wordmarkLead") ?? "").trim(); + if (wordmarkLead && !wordmarkLeadFor(headerTitle, wordmarkLead)) { + return { + ok: false, + error: `Wordmark lead must be how the header title starts, same case, and shorter than it (e.g. "Jer" for "Jeralyzer") — or left blank.`, + values, + }; + } + // Brand accent: a named id from the radio group, or "custom" + its hex + // field. The default (Signal) is stored as absent — the two read the same. + // A bare hex in `accent` (a form from before the radio group) is taken as + // a custom colour. + const accentChoice = String(formData.get("accent") ?? "").trim(); + const accentCustomRaw = String(formData.get("accentCustom") ?? "").trim(); + let accent: string | undefined; + if (accentChoice === "custom") { + accent = parseAccent(accentCustomRaw); + if (!accent) { + return { + ok: false, + error: "Custom accent must be a hex color like #cc3366.", + values, + }; + } + } else if (accentChoice) { + accent = parseAccentSetting(accentChoice); + if (!accent) { + return { + ok: false, + error: `Unknown brand accent "${accentChoice}".`, + values, + }; + } + if (accent === DEFAULT_ACCENT) accent = undefined; + } + const cloudflareProject = String( + formData.get("cloudflareProject") ?? "", + ).trim(); + const siteUrlRaw = String(formData.get("siteUrl") ?? "").trim(); + if (siteUrlRaw && !parseSiteUrl(siteUrlRaw)) { + return { + ok: false, + error: "Public URL must be an absolute http(s):// URL, or left blank.", + values, + }; + } + const siteUrl = parseSiteUrl(siteUrlRaw); + // Listed on the homepage and hub by default: the same opt-out idiom as + // archives below (an unchecked box sends no key → persisted as false). + const listed = formData.get("listed") === "on"; + // Who the site is built for (release 17 slice XP): only "private" is kept. + const audienceRaw = String(formData.get("audience") ?? "public"); + if (audienceRaw !== "public" && audienceRaw !== "private") { + return { ok: false, error: `Unknown audience "${audienceRaw}".`, values }; + } + const isPrivate = audienceRaw === "private"; + // The publish lane's policy for this site (release 18). writeSite refuses a + // deploying policy with no Pages project (sitePublishProblem) and stores a + // private site's as "build". + const publishAutoRaw = String(formData.get("publishAuto") ?? "off"); + if (!(PUBLISH_POLICIES as readonly string[]).includes(publishAutoRaw)) { + return { ok: false, error: `Unknown publish policy "${publishAutoRaw}".`, values }; + } + const publishAuto = publishAutoRaw as PublishPolicy; + // Search (opt-out; off = pages only) and the page list, which is not on + // this form: the stored one is carried over. + let storedReports: Pick<Site, "pages"> | undefined; + try { + storedReports = getSite(siteId, getPaths()); + } catch { + storedReports = undefined; + } + const reportKeys = reportSiteKeysFromForm(formData, storedReports); + + // Hub parent (per-site override of the family default) + PWA opt-in. + const hubUrlRaw = String(formData.get("hubUrl") ?? "").trim(); + if (hubUrlRaw && !parseSiteUrl(hubUrlRaw)) { + return { + ok: false, + error: "Hub URL must be an absolute http(s):// URL, or left blank.", + values, + }; + } + const hubUrl = parseSiteUrl(hubUrlRaw); + const pwa = formData.get("pwa") === "on"; + // Archives default on: an unchecked (default-on) box yields no "archives" key + // → false → persisted as the explicit opt-out. + const archives = formData.get("archives") === "on"; + // Duplicates default on, same opt-out idiom as archives. + const duplicates = formData.get("duplicates") === "on"; + // Per-video transcript downloads default on, same opt-out idiom. + const transcriptDownloads = formData.get("transcriptDownloads") === "on"; + const archiveMaxMBRaw = String(formData.get("archiveMaxMB") ?? "").trim(); + let archiveMaxBytes: number | undefined; + if (archiveMaxMBRaw) { + const mb = Number(archiveMaxMBRaw); + if (!Number.isFinite(mb) || mb < 0) { + return { + ok: false, + error: "Archive size cap must be a non-negative number of MB, or blank.", + values, + }; + } + archiveMaxBytes = Math.floor(mb * 1024 * 1024); + } + + let relatedSitesInput: unknown; + try { + relatedSitesInput = JSON.parse( + String(formData.get("relatedSitesJson") ?? "[]"), + ); + } catch { + return { ok: false, error: "Related sites payload is malformed", values }; + } + const relatedSites = parseRelatedSites(relatedSitesInput); + + let groupsInput: unknown; + try { + groupsInput = JSON.parse(String(formData.get("groupsJson") ?? "[]")); + } catch { + return { ok: false, error: "Channel groups payload is malformed", values }; + } + const groups = parseChannelGroups(groupsInput); + if (groups.length === 0) { + return { + ok: false, + error: "At least one channel group is required (check ID/name fields)", + values, + }; + } + const defaultGroupIdRaw = String(formData.get("defaultGroupId") ?? "").trim(); + const defaultGroupId = resolveDefaultGroupId(defaultGroupIdRaw, groups); + if (defaultGroupIdRaw && defaultGroupIdRaw !== defaultGroupId) { + return { + ok: false, + error: `Default group "${defaultGroupIdRaw}" is not among the configured group IDs`, + values, + }; + } + + // When inheriting, leave socialLinks undefined so writeSite omits the key and + // the site falls back to the global default at render time. + const inheritSocialLinks = formData.get("inheritSocialLinks") === "on"; + let socialLinks: SocialLink[] | undefined; + if (!inheritSocialLinks) { + let socialInput: unknown; + try { + socialInput = JSON.parse(String(formData.get("socialLinksJson") ?? "[]")); + } catch { + return { ok: false, error: "Social links payload is malformed", values }; + } + const socialParsed = parseSocialLinks(socialInput); + if ( + Array.isArray(socialInput) && + socialParsed.length !== socialInput.length + ) { + return { + ok: false, + error: + "Each social link needs a label, URL (http(s)://, mailto:, or /), and SVG.", + values, + }; + } + // A link whose SVG is unchanged from the site's file is kept as it is; a + // new or edited one is checked (lib/socialLinks.ts socialLinksForSave). + let stored: SocialLink[] = []; + try { + stored = getSite(siteId, getPaths()).socialLinks ?? []; + } catch { + stored = []; + } + const checked = socialLinksForSave(socialParsed, stored); + if ("refused" in checked) { + return { + ok: false, + error: `Social link "${checked.refused.label}" has an invalid SVG: ${checked.refused.problem}.`, + values, + }; + } + socialLinks = checked.links; + } + + let channelsInput: unknown; + try { + channelsInput = JSON.parse(String(formData.get("channelsJson") ?? "[]")); + } catch { + return { + ok: false, + error: "Channel membership payload is malformed", + values, + }; + } + const channels = parseSiteChannels(channelsInput); + // The cited scope: channels outside the pool this site's reports may cite + // without publishing them (lib/citedChannelsFromForm.ts). + const citedChannels = citedChannelsFromForm(formData, channels); + if (citedChannels === null) { + return { ok: false, error: "Cited channels payload is malformed", values }; + } + + const site: Site = { + siteId, + siteTitle, + siteDescription, + headerTitle, + ...(wordmarkLead ? { wordmarkLead } : {}), + homeTagline, + ...(socialLinks !== undefined ? { socialLinks } : {}), + groups, + defaultGroupId, + channels, + ...(citedChannels.length > 0 ? { citedChannels } : {}), + ...(accent ? { accent } : {}), + ...(cloudflareProject ? { cloudflareProject } : {}), + ...(siteUrl ? { siteUrl } : {}), + // The Site is rebuilt from the form: a key missing here is dropped on save. + ...(listed ? {} : { listed: false }), + ...(isPrivate ? { audience: "private" as const } : {}), + ...(publishAuto !== "off" ? { publish: { auto: publishAuto } } : {}), + ...reportKeys, + ...(hubUrl ? { hubUrl } : {}), + ...(pwa ? { pwa: true } : {}), + ...(archives ? {} : { archives: false }), + ...(duplicates ? {} : { duplicates: false }), + ...(transcriptDownloads ? {} : { transcriptDownloads: false }), + ...(archiveMaxBytes !== undefined ? { archiveMaxBytes } : {}), + ...(relatedSites.length > 0 ? { relatedSites } : {}), + }; + try { + await writeSite(site, getPaths()); + } catch (err) { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + values, + }; + } + // NO revalidatePath (release 24 H5): React commits a revalidating action's + // state with the router's refresh of the page, which now and then did not + // settle until the next AutoRefresh tick, so "Saved." came up to ~6 s late. + // SiteForm seeds from `values` and refreshes the page itself once "Saved." is + // in (lib/formState.ts seedAfterSave, lib/useRefreshAfterSave.ts) — the h1 + // above the tabs and /sites's list follow with that refresh. + return { ok: true, siteId, values }; +} diff --git a/editor/app/sites/lib/siteFormData.ts b/editor/app/sites/lib/siteFormData.ts @@ -0,0 +1,208 @@ +// THE SITE FORM'S FIELDS, BUILT WITHOUT A BROWSER — for `pnpm ops create-site`. +// +// The site form posts a FormData that saveSiteAction rebuilds the whole Site +// from (a key it does not post is dropped on save). So an ops caller goes +// through the same action with the same FormData: `siteToFormData` is the form +// a site would post if nothing in it were touched (what SiteForm seeds from), +// and `applySiteFields` lays the caller's keys over it. A create starts from a +// blank site, an update from the stored one — "update" is the site page's Save +// with those fields changed, and every key not named stays as it was. +// +// Pure: no fs, no server. The round trip (stored site -> FormData -> action -> +// the same site.json) is pinned in app/api/ops/create-site/route.test.ts. + +import { isAccentId } from "yt-dlp-transcript-common/lib/brand"; +import { parseChannelGroup } from "yt-dlp-transcript-common/lib/channelGroups"; +import type { Site } from "yt-dlp-transcript-common/lib/site"; +import { CITED_CHANNELS_FIELD } from "./citedChannelsFromForm"; + +const MB = 1024 * 1024; + +const on = (fd: FormData, key: string, value: boolean) => { + if (value) fd.set(key, "on"); + else fd.delete(key); +}; + +export function siteToFormData(site: Site): FormData { + const fd = new FormData(); + fd.set("siteId", site.siteId); + fd.set("siteTitle", site.siteTitle); + fd.set("headerTitle", site.headerTitle); + fd.set("wordmarkLead", site.wordmarkLead ?? ""); + fd.set("siteDescription", site.siteDescription); + fd.set("homeTagline", site.homeTagline); + setAccent(fd, site.accent); + fd.set("cloudflareProject", site.cloudflareProject ?? ""); + fd.set("siteUrl", site.siteUrl ?? ""); + fd.set("audience", site.audience === "private" ? "private" : "public"); + fd.set("publishAuto", site.publish?.auto ?? "off"); + // The opt-out checkboxes: absent / true = ticked. + on(fd, "search", site.search !== false); + on(fd, "listed", site.listed !== false); + on(fd, "archives", site.archives !== false); + on(fd, "duplicates", site.duplicates !== false); + on(fd, "transcriptDownloads", site.transcriptDownloads !== false); + on(fd, "pwa", site.pwa === true); + fd.set("hubUrl", site.hubUrl ?? ""); + // bytes / 2^20 is exact in binary and String() round-trips, so the action's + // floor(MB * 2^20) gives the stored bytes back. + fd.set("archiveMaxMB", site.archiveMaxBytes !== undefined ? String(site.archiveMaxBytes / MB) : ""); + setSocialLinks(fd, site.socialLinks); + fd.set("groupsJson", JSON.stringify(site.groups)); + fd.set("defaultGroupId", site.defaultGroupId); + fd.set("channelsJson", JSON.stringify(site.channels)); + fd.set(CITED_CHANNELS_FIELD, JSON.stringify((site.citedChannels ?? []).map((c) => c.slug))); + fd.set("relatedSitesJson", JSON.stringify(site.relatedSites ?? [])); + return fd; +} + +function setAccent(fd: FormData, accent: string | undefined) { + // Absent = the default accent (the radio group's first choice reads the same). + if (!accent || isAccentId(accent)) { + fd.set("accent", accent ?? ""); + fd.delete("accentCustom"); + return; + } + fd.set("accent", "custom"); + fd.set("accentCustom", accent); +} + +function setSocialLinks(fd: FormData, links: unknown[] | undefined | null) { + if (links === undefined || links === null) { + fd.set("inheritSocialLinks", "on"); + fd.delete("socialLinksJson"); + return; + } + fd.delete("inheritSocialLinks"); + fd.set("socialLinksJson", JSON.stringify(links)); +} + +// The keys `create-site` takes beyond `siteId` and `update`, each the form +// field of the same meaning. +export const SITE_OPS_FIELDS = [ + "siteTitle", + "headerTitle", + "siteDescription", + "homeTagline", + "wordmarkLead", + "accent", + "cloudflareProject", + "siteUrl", + "hubUrl", + "audience", + "publishAuto", + "listed", + "search", + "archives", + "duplicates", + "transcriptDownloads", + "pwa", + "archiveMaxMB", + "groups", + "defaultGroupId", + "channels", + "citedChannels", + "socialLinks", + "relatedSites", +] as const; + +const STRING_FIELDS = new Set([ + "siteTitle", + "headerTitle", + "siteDescription", + "homeTagline", + "wordmarkLead", + "cloudflareProject", + "siteUrl", + "hubUrl", + "audience", + "publishAuto", + "defaultGroupId", +]); +const BOOL_FIELDS = new Set(["listed", "search", "archives", "duplicates", "transcriptDownloads", "pwa"]); + +// A key of the wrong shape, in the caller's words. The VALUES are the action's +// to judge (its sentences: an unknown audience, a bad URL, a group list with +// none) — only what cannot be turned into a form field is refused here. +export class SiteFieldError extends Error {} + +export function applySiteFields(fd: FormData, fields: Record<string, unknown>): void { + for (const [key, v] of Object.entries(fields)) { + if (v === undefined) continue; + if (STRING_FIELDS.has(key)) { + if (typeof v !== "string") throw new SiteFieldError(`"${key}" must be a string`); + fd.set(key, v); + } else if (BOOL_FIELDS.has(key)) { + if (typeof v !== "boolean") throw new SiteFieldError(`"${key}" must be a boolean`); + on(fd, key, v); + } else if (key === "accent") { + if (typeof v !== "string") throw new SiteFieldError(`"accent" must be a string (an accent id or "#rrggbb")`); + // A hex is the form's "custom"; anything else is the radio's id, for the + // action to accept or refuse by name. + const a = v.trim(); + if (/^#?[0-9a-f]{6}$/i.test(a)) setAccent(fd, a); + else { + fd.set("accent", a); + fd.delete("accentCustom"); + } + } else if (key === "archiveMaxMB") { + if (v !== null && (typeof v !== "number" || !Number.isFinite(v))) { + throw new SiteFieldError(`"archiveMaxMB" must be a number of MB, or null for the global default`); + } + fd.set("archiveMaxMB", v === null ? "" : String(v)); + } else if (key === "groups") { + if (!Array.isArray(v)) throw new SiteFieldError(`"groups" must be an array of {id, name, …}`); + // The parser drops a group it cannot read, which on a form is a row the + // operator can see; over ops it would vanish without a word. + const bad = v.findIndex((g) => parseChannelGroup(g) === null); + if (bad >= 0) { + throw new SiteFieldError( + `"groups"[${bad}] is not a channel group: it needs an "id" (lowercase letters, digits, hyphens) and a "name"`, + ); + } + fd.set("groupsJson", JSON.stringify(v.map((g, order) => (isObject(g) ? { order, ...g } : g)))); + } else if (key === "channels") { + fd.set("channelsJson", JSON.stringify(readChannels(v))); + } else if (key === "citedChannels") { + if (!Array.isArray(v) || v.some((s) => typeof s !== "string")) { + throw new SiteFieldError(`"citedChannels" must be an array of channel slugs`); + } + fd.set(CITED_CHANNELS_FIELD, JSON.stringify(v)); + } else if (key === "socialLinks") { + if (v !== null && !Array.isArray(v)) { + throw new SiteFieldError(`"socialLinks" must be an array of {label, url, svg}, or null to inherit the global default`); + } + setSocialLinks(fd, v as unknown[] | null); + } else if (key === "relatedSites") { + if (!Array.isArray(v)) throw new SiteFieldError(`"relatedSites" must be an array of {label?, siteIds}`); + fd.set("relatedSitesJson", JSON.stringify(v)); + } else { + throw new SiteFieldError(`unknown site field "${key}"`); + } + } +} + +// `channels`: slugs, or {slug, groupId?} — the pool, in the order given. +export function readChannels(v: unknown): { slug: string; groupId?: string; order: number }[] { + if (!Array.isArray(v)) { + throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`); + } + return v.map((entry, order) => { + if (typeof entry === "string") return { slug: entry.trim(), order }; + if (isObject(entry) && typeof entry.slug === "string") { + if (entry.groupId !== undefined && typeof entry.groupId !== "string") { + throw new SiteFieldError(`"channels": the groupId of "${entry.slug}" must be a string`); + } + return { + slug: entry.slug.trim(), + ...(typeof entry.groupId === "string" && entry.groupId.trim() ? { groupId: entry.groupId.trim() } : {}), + order, + }; + } + throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`); + }); +} + +function isObject(v: unknown): v is Record<string, unknown> { + return typeof v === "object" && v !== null && !Array.isArray(v); +} diff --git a/editor/e2e/ops-api.spec.ts b/editor/e2e/ops-api.spec.ts @@ -144,12 +144,23 @@ test("a channel's lifecycle over ops: create on a site, list, re-site, rename, d expect(refused.body.error).toBe( 'Type the channel slug "made-renamed-x" exactly to confirm deletion', ); + // A deleted channel leaves no site naming it (lane editor-gaps, 9 Nov): back + // in mysite's pool, and in another site's cited scope. + expect( + (await ops(request, "channel-config", { slug: "made-renamed-x", sites: [{ siteId: "mysite" }] })).body, + ).toEqual({ ok: true }); + await writeSite("citer", { channels: [] }); + expect((await ops(request, "site-config", { siteId: "citer", citedChannels: ["made-renamed-x"] })).status).toBe(200); + const CITER = `${testPaths().transcriptsDir}/sites/citer/site.json`; const gone = await ops(request, "delete-channel", { slug: "made-renamed-x", confirm: "made-renamed-x", }); expect(gone.status).toBe(200); + expect(gone.body).toEqual({ ok: true, slug: "made-renamed-x", deleted: true, sitesUpdated: ["citer", "mysite"] }); expect(await list()).toEqual([]); + expect((await readJson<{ channels: unknown[] }>(SITE)).channels).toEqual([]); + expect((await readJson<{ citedChannels?: unknown[] }>(CITER)).citedChannels).toBeUndefined(); }); test("channel-config round-trips a download filter and refuses a bad regex", async ({ @@ -340,6 +351,97 @@ test("channel-priority sets and ends the focus", async ({ request }) => { await expect.poll(async () => (await focusOf())?.kind ?? "none").toBe("none"); }); +// create-site (lane editor-gaps): the New site form over HTTP — the form's +// action, so the site the /sites list shows; an existing id refused unless +// "update", which keeps every key it does not name. +test("create-site makes a private, unlisted site the /sites list shows; update changes only what it names", async ({ + request, + page, +}) => { + await resetData("one-youtube-channel-with-data"); + await settings(); + const made = await ops(request, "create-site", { + siteId: "opsalyzer", + siteTitle: "Opsalyzer", + channels: ["test-youtube"], + }); + expect(made.status, JSON.stringify(made.body)).toBe(200); + type SiteFile = { siteTitle: string; homeTagline: string; audience?: string; listed?: boolean; channels: { slug: string }[] }; + const file = `${testPaths().transcriptsDir}/sites/opsalyzer/site.json`; + const site = await readJson<SiteFile>(file); + expect(site).toMatchObject({ siteTitle: "Opsalyzer", audience: "private", listed: false }); + expect(site.channels.map((c) => c.slug)).toEqual(["test-youtube"]); + + await page.goto("/sites"); + await expect(page.getByRole("link", { name: /Opsalyzer/ })).toBeVisible(); + + const again = await ops(request, "create-site", { siteId: "opsalyzer", siteTitle: "Other" }); + expect(again.status).toBe(409); + expect(again.body.error).toMatch(/already exists/); + + const up = await ops(request, "create-site", { siteId: "opsalyzer", update: true, homeTagline: "Searchable" }); + expect(up.status, JSON.stringify(up.body)).toBe(200); + expect(await readJson<SiteFile>(file)).toEqual({ ...site, homeTagline: "Searchable" }); +}); + +// channel-rank (lane editor-gaps): one channel moved in the order through the +// deck's one writer — the rank alone; the tier and the lanes untouched, and +// the four lane roots recompiled in the same write. +test("channel-rank places a channel top, after another, by rank and unranked", async ({ request }) => { + await resetData("empty"); + for (const slug of ["rank-a", "rank-b", "rank-c"]) await writeChannelConfig(slug, {}); + await writeSettings({ + minFreeDiskGB: 0, + channelPriority: { + focus: { kind: "none" }, + channels: { + "rank-a": { tier: "normal", rank: 0 }, + "rank-b": { tier: "low", rank: 1 }, + "rank-c": { tier: "normal", rank: 2 }, + }, + }, + }); + type Prio = { channelPriority?: { channels?: Record<string, { tier: string; rank?: number }> } }; + const ranks = async () => { + const c = (await readJson<Prio>(testPaths().settingsFile)).channelPriority?.channels ?? {}; + return Object.fromEntries(Object.entries(c).map(([s, e]) => [s, e.rank ?? null])); + }; + + const top = await ops(request, "channel-rank", { slug: "rank-c", top: true }); + expect(top.status, JSON.stringify(top.body)).toBe(200); + expect(top.body).toMatchObject({ + ok: true, + slug: "rank-c", + rank: 0, + order: [ + { slug: "rank-c", rank: 0 }, + { slug: "rank-a", rank: 1 }, + { slug: "rank-b", rank: 2 }, + ], + }); + await expect.poll(ranks).toEqual({ "rank-a": 1, "rank-b": 2, "rank-c": 0 }); + const tiers = (await readJson<Prio>(testPaths().settingsFile)).channelPriority?.channels ?? {}; + expect(tiers["rank-b"]?.tier).toBe("low"); + + const after = await ops(request, "channel-rank", { slug: "rank-b", after: "rank-c" }); + expect(after.body).toMatchObject({ ok: true, rank: 1 }); + await expect.poll(ranks).toEqual({ "rank-a": 2, "rank-b": 1, "rank-c": 0 }); + + const unrank = await ops(request, "channel-rank", { slug: "rank-a", rank: null }); + expect(unrank.body).toMatchObject({ ok: true, slug: "rank-a", rank: null }); + await expect.poll(ranks).toEqual({ "rank-b": 1, "rank-c": 0 }); + + // The compiled download root lists the channels in that order. + type Root = { autoQueue?: { download?: { root?: unknown } } }; + const root = JSON.stringify((await readJson<Root>(testPaths().settingsFile)).autoQueue?.download?.root ?? null); + expect(root.indexOf("rank-c")).toBeGreaterThan(-1); + expect(root.indexOf("rank-c")).toBeLessThan(root.indexOf("rank-a")); + + const refused = await ops(request, "channel-rank", { slug: "rank-c", before: "rank-a" }); + expect(refused.status).toBe(400); + expect(refused.body.error).toMatch(/"rank-a" has no rank/); +}); + test("metadata-scan starts a job, and the job says it is a metadata-scan", async ({ request, }) => { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -75,6 +75,8 @@ // pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}' // pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}' // pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}' +// pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}' +// pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}' // pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}' // pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}' // pnpm ops articles-config --json '{"id":"demo-article","published":true}' @@ -88,6 +90,9 @@ // pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}' // pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}' // pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}' +// pnpm ops channel-rank --json '{"slug":"x","top":true}' +// pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}' +// pnpm ops channel-rank --json '{"slug":"x","rank":null}' // pnpm ops lane --json '{"lane":"download","held":true}' // pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}' // pnpm ops render-mode --json '{"on":false}' @@ -373,7 +378,14 @@ export const JOB_VERBS = [ const ACTIONS = [ "channel-priority", + // One channel placed in the order the lanes follow ({slug} and one of rank + // | top | bottom | before | after), through the deck's one writer. + "channel-rank", "channel-config", + // The New site form ({siteId, siteTitle, …its fields}), or the site page's + // Save with some keys changed ({siteId, update: true, …}), through the + // form's own action. Synchronous; no job. + "create-site", // A site's cited-only channels and its publish policy ({siteId, // citedChannels?, publishAuto?}), through the site form's own writer. "site-config", @@ -1270,6 +1282,12 @@ export function usage() { ' "whilePaused": true runs this one transcription during a pause-all on a', ' worker the pause alone switched off; the pause stays on (the video page\'s', ' "Transcribe now (workers paused)").', + ' A video its record says is live, scheduled or still processing its VOD', + ' (live_status is_live, is_upcoming, post_live) is refused before anything', + ' is queued — a download would read the stream at 1x and hold the platform', + ' queue: record it with record-live, or wait for the VOD (refresh-metadata', + ' re-reads the record once it has ended). With its audio on disk it', + ' transcribes.', "", 'delete-file deletes one file of one video, as its Files list does:', ' {"slug", "id", "file"}. A tiered media file goes with its bytes on the', @@ -1309,6 +1327,17 @@ export function usage() { ' {"kind": "none"}} alone is the deck\'s focus bar: those channels lead', ' every lane (a site focus follows its membership); "none" ends it.', "", + 'channel-rank places one channel in the order every lane and the sync', + ' scheduler follow inside a tier (one rank per channel, 0 first; unranked', + ' channels come after every ranked one, by slug): {"slug"} and exactly one', + ' of "rank": <n> (before any channel holding it) or null (unranked), "top":', + ' true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked', + ' channel; immediately next to it, a tie on its rank included). The channels', + ' after it move down only as far as they must. Only the rank moves — no tier,', + ' override or lane changes, unlike /channels\' "Add to top". Refused: an', + ' unknown channel, an unranked anchor, a channel paused for every', + ' operation. Answers {slug, rank, order: [{slug, rank}, …]}.', + "", 'sync lists a channel and downloads what is new, as its Sync button does:', ' {"slug"}. "full": true runs the periodic whole-listing sweep now (else', ' the configured cadence decides); "queueKey" picks another queue. On the', @@ -1405,6 +1434,23 @@ export function usage() { ' download-missing leave the channel alone; "" (or "auto") is automatic', ' (CHANNEL.md, downloadMode).', "", + 'create-site is the New site form: {"siteId", "siteTitle"} and any of its', + ' fields — "headerTitle" (default the title), "siteDescription",', + ' "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl",', + ' "cloudflareProject", "hubUrl", "audience" ("private" | "public"; default', + ' PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives",', + ' "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the', + ' global default), "groups" ([{"id", "name", "selectedByDefault"?,', + ' "description"?, "inline"?}]), "defaultGroupId", "channels" (slugs, or', + ' {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks"', + ' ([{"label", "url", "svg"}], null = inherit), "relatedSites". Saved by', + ' the form\'s action (its validation, its sentences). An existing id is', + ' refused (409) unless "update": true — the site page\'s Save with the', + ' keys given changed, every other key kept — one read-modify-write under', + ' the site\'s lock. An unknown channel, or a channel\'s groupId naming no', + ' group of the site, is refused.', + ' Answers {siteId, created, site}.', + "", 'site-config sets two keys of a site as its form does: {"siteId"} and any of', ' "citedChannels" (the WHOLE cited scope, channel slugs: what the site\'s', ' reports may cite without publishing the channel; [] clears it; a slug the', @@ -1479,8 +1525,10 @@ export function usage() { ' media in transition) or when the new slug is taken. Old links break.', "", 'delete-channel removes a channel\'s whole directory, as Danger → Delete does:', - ' {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the', - ' transcripts/ repo\'s own history.', + ' {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose', + ' pool or cited scope names it is rewritten without it (answered as', + ' "sitesUpdated"; a site whose write is refused is a "warnings" line). No', + ' undo outside the transcripts/ repo\'s own history.', "", 'fetch-chat fetches ONE video\'s live chat replay and nothing else: {"slug",', ' "id"} — the chat-only yt-dlp pass (the channel\'s cookies, the platform\'s',