Archilyzer · Source

archilyzer

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

commit 730804e29a82c6ad91d229c88fafcca6dff8ea2a
parent 3b7caec64ba92249993f96be3e7d717edc1ef68c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 19 Nov 2026 15:33:17 -0500

Merge lane/missing-source: the site says when a source is no longer public, and plays the visitor's own copy

A video that is members-only, private or removed at its platform is shown
without a dead player: a sentence with the state and the day it was first
seen, the platform link marked, the transcript as for any video. Records
and summaries carry the state and that day; a day is published only when a
history entry anchors it. A refused chat fetch or metadata refresh that
names members-only or private is recorded as an observation; a removal is
recorded only by the availability check. "Play your own copy" plays a local
file in the page with the transcript following and an offset control; the
file never leaves the browser. The browser's transcript cache is bumped so
returning visitors see the current state.

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

Diffstat:
MCOMMANDS.md | 4++--
Mcommon/components/FilePlayer.tsx | 12+++++++++++-
Acommon/components/LocalFileBar.tsx | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/components/LocalFilePicker.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/components/LocalFilePicker.tsx | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/components/PlayerProvider.tsx | 390++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/components/SearchResults.tsx | 2+-
Mcommon/components/SearchSessionContext.tsx | 4++++
Mcommon/components/TranscriptModal.tsx | 13+++++++++++--
Mcommon/components/badges.tsx | 8++++++--
Mcommon/components/transcriptStore.ts | 7++++++-
Mcommon/controller/buildIndex.test.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/buildIndex.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcommon/controller/fetchLiveChat.test.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchLiveChat.ts | 20++++++++++++++++++++
Mcommon/controller/refreshVideoMetadata.test.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/refreshVideoMetadata.ts | 35+++++++++++++++++++++++++++++++++++
Acommon/lib/availability-server.test.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/availability-server.ts | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/availability.test.ts | 32++++++++++++++++++++++++++++++++
Mcommon/lib/availability.ts | 44+++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/corpus.ts | 14++++++++++++--
Acommon/lib/localFileClock.test.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/localFileClock.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/sourceMissing.test.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/sourceMissing.ts | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/transcripts-server.ts | 4+++-
Mcommon/lib/transcripts.ts | 13+++++++++++++
Meditor/CHANGELOG.md | 19+++++++++++++++++++
Mexport/CHANGELOG.md | 28++++++++++++++++++++++++++++
Aexport/e2e/fixtures/missing-source.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexport/e2e/local-file.spec.ts | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexport/e2e/source-missing.spec.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 9++++++++-
34 files changed, 2191 insertions(+), 39 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -140,7 +140,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `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. 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` | +| `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. A refusal for the video as members-only or private, or a metadata availability field that changes the reading, is recorded in its availability.json (source fetch): the one-video availability recheck. A removal is recorded only by the channel's Check availability. | `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` | | `import-video` | import-video imports one video by URL into a channel: {"slug", "url"}. An archive.org URL becomes its canonical item or file (an item of several media files is refused — see import-archive-org); a BitChute or Odysee URL runs on that platform's queue at its pace, refused while it is held or cooling down, and refused when already on disk; a Wayback capture is named by what it copies. | `pnpm ops import-video --json '{"slug":"demo-archive","url":"https://archive.org/details/example-item"}'` | | `import-archive-org` | import-archive-org imports archive.org media into a channel, as one job on archive.org's queue: {"slug", "item", "files": \[...\] \| "match": "&lt;regex&gt;"} for one item; {"slug", "items": \["&lt;id&gt;" \| {"item", "files"? \| "match"?}, ...\]} for many (a bare id takes "match", else every media original); or {"slug", "query": "&lt;archive.org search&gt;", "limit"?: 100} for the first items a search finds (at most 500). One file at a time, a jittered pause between files and between items; a record already held (on disk, or in the saved-video store) is skipped. "dryRun": true lists each file as held, RESTRICTED (archive.org marks it not for download: a fetch would answer 401/403) or would get, and fetches nothing. A 401/403 skips the rest of its item; three such items in a row, a 429 or three failures in a row stop the job. The log ends with a summary: line; a re-run resumes. | `pnpm ops import-archive-org --json '{"slug":"demo-archive","item":"example-item","match":"\\.mp4$"}' --wait`<br>`pnpm ops import-archive-org --json '{"slug":"demo-archive","query":"collection:example-collection","dryRun":true}' --wait` | @@ -236,7 +236,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -&gt; {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/&lt;slug&gt;.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -&gt; {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -&gt; {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | | `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -&gt; {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` | -| `fetch-chat` | 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 pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` | +| `fetch-chat` | 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 pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for &lt;platform&gt;" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` | | `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/&lt;id&gt;/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` | | `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` | | `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it 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 the jar: Refresh cookies on /cookies, then {"resume": "&lt;run id&gt;"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` | diff --git a/common/components/FilePlayer.tsx b/common/components/FilePlayer.tsx @@ -19,6 +19,11 @@ type Props = { onPause?: () => void; onProgress?: (state: { playedSeconds: number }) => void; onError?: () => void; + // The element's accessible name ("Your copy" for a visitor's own file). + label?: string; + // Take focus once mounted: the visitor's own copy replaces the control that + // picked it, which would otherwise leave focus on nothing. + autoFocus?: boolean; }; // A plain media file in a native <video> — archive.org records, whose own @@ -28,7 +33,7 @@ type Props = { // PlayerProvider drives it the same way (full seeking + cue highlighting). An // audio file plays in the same element. const FilePlayer = forwardRef<FilePlayerHandle, Props>(function FilePlayer( - { url, playing, onReady, onPlay, onPause, onProgress, onError }, + { url, playing, onReady, onPlay, onPause, onProgress, onError, label, autoFocus }, ref, ) { const videoRef = useRef<HTMLVideoElement | null>(null); @@ -72,6 +77,10 @@ const FilePlayer = forwardRef<FilePlayerHandle, Props>(function FilePlayer( }; }, [url]); + useEffect(() => { + if (autoFocus) videoRef.current?.focus(); + }, [autoFocus]); + // Autoplay may be refused without a gesture; the native controls start it. useEffect(() => { const video = videoRef.current; @@ -84,6 +93,7 @@ const FilePlayer = forwardRef<FilePlayerHandle, Props>(function FilePlayer( <video ref={videoRef} controls + {...(label ? { "aria-label": label } : {})} playsInline preload="metadata" style={{ width: "100%", height: "100%", background: "black" }} diff --git a/common/components/LocalFileBar.tsx b/common/components/LocalFileBar.tsx @@ -0,0 +1,105 @@ +"use client"; + +import { CrosshairIcon, SquareIcon } from "lucide-react"; +import { ControlButton, usePlayer } from "./PlayerProvider"; +import { LocalFilePicker } from "./LocalFilePicker"; +import { formatOffset } from "../lib/localFileClock"; + +// THE VISITOR'S OWN COPY, IN THE MODAL (lane missing-source, slice 2). +// - No copy, source still public: the plain "Play your own copy" control and +// its one-sentence promise. (A source no longer public has the same control +// in the player slot's panel, so nothing shows here.) +// - A copy playing: its name, the offset, the four nudges, "This line is +// playing now" (the next cue click sets the offset) and Stop, which gives +// the focus back to the "Play your own copy" control in its place. +// +// Nothing in this file may reach the network or storage (the offset is written +// by the provider through lib/localFileClock.ts); LocalFilePicker.test.ts +// reads this source too. + +const NUDGES: ReadonlyArray<{ delta: number; label: string; title: string }> = [ + { delta: -1, label: "−1 s", title: "Offset −1 second" }, + { delta: -0.1, label: "−0.1 s", title: "Offset −0.1 second" }, + { delta: 0.1, label: "+0.1 s", title: "Offset +0.1 second" }, + { delta: 1, label: "+1 s", title: "Offset +1 second" }, +]; + +// ControlButton shows `icon ?? char` before its label; a nudge's label is its +// whole face. +const NO_ICON = <span aria-hidden="true" className="hidden" />; + +export function LocalFileBar() { + const { + data, + sourceGone, + sourceStatePending, + localFile, + localSyncArmed, + openLocalFile, + stopLocalFile, + takeLocalPickerFocus, + nudgeLocalOffset, + armLocalSync, + } = usePlayer(); + + if (!localFile) { + // Not before the record and its fresh state are here (the state decides + // where the control goes), and not for a source no longer public: the + // panel holds it. + if (!data || sourceStatePending || sourceGone) return null; + return ( + <div className="px-3 sm:px-0" data-testid="local-file-offer"> + <LocalFilePicker onPick={openLocalFile} takeFocus={takeLocalPickerFocus} /> + </div> + ); + } + + return ( + <div + role="group" + aria-label="Your copy" + data-testid="local-file-bar" + className="mx-3 sm:mx-0 flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg bg-zinc-900/80 ring-1 ring-white/10 p-2 text-xs text-zinc-200" + > + <span className="min-w-0 max-w-full truncate"> + Your copy: <span className="text-white">{localFile.name}</span> + </span> + <span aria-live="polite" data-testid="local-file-offset" className="font-mono text-white"> + Offset {formatOffset(localFile.offset)} + </span> + {NUDGES.map((n) => ( + <ControlButton + key={n.title} + title={n.title} + label={n.label} + icon={NO_ICON} + onClick={() => nudgeLocalOffset(n.delta)} + /> + ))} + <ControlButton + title="This line is playing now" + label="This line is playing now" + icon={<CrosshairIcon className="size-4" />} + highlight={localSyncArmed} + aria-pressed={localSyncArmed} + onClick={() => armLocalSync(!localSyncArmed)} + /> + <ControlButton + title="Stop using my copy" + label="Stop" + icon={<SquareIcon className="size-4" />} + onClick={stopLocalFile} + /> + {localSyncArmed && ( + <p role="status" className="basis-full text-amber-200"> + Click the line you hear now (Esc cancels). + </p> + )} + {localFile.error && ( + <p role="alert" className="basis-full text-rose-200"> + This browser cannot play that file. + </p> + )} + </div> + ); +} diff --git a/common/components/LocalFilePicker.test.ts b/common/components/LocalFilePicker.test.ts @@ -0,0 +1,53 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test components/LocalFilePicker.test.ts +// +// THE VISITOR'S OWN COPY NEVER LEAVES THE BROWSER (lane missing-source, slice +// 2). The modules that touch the picked file, its object URL or its offset may +// not mention any API that can carry bytes off the page or keep them: a fetch, +// a beacon, a socket, a worker message, the Cache API, IndexedDB, a service +// worker. The offset is the one thing stored, and only through the Storage the +// provider hands lib/localFileClock.ts — so neither these modules nor the clock +// names localStorage or sessionStorage either. The export e2e +// (export/e2e/local-file.spec.ts) checks the running page; this checks the source. + +const FILES = [ + "./LocalFilePicker.tsx", + "./LocalFileBar.tsx", + "../lib/localFileClock.ts", + "../lib/sourceMissing.ts", +]; + +const FORBIDDEN: ReadonlyArray<[string, RegExp]> = [ + ["fetch", /\bfetch\s*\(/], + ["XMLHttpRequest", /XMLHttpRequest/], + ["sendBeacon", /sendBeacon/], + ["WebSocket", /WebSocket/], + ["EventSource", /EventSource/], + ["postMessage", /postMessage/], + ["Cache API", /\bcaches\b/], + ["IndexedDB", /indexedDB/i], + ["service worker", /serviceWorker/], + ["localStorage", /localStorage/], + ["sessionStorage", /sessionStorage/], + ["a dynamic import", /\bimport\s*\(/], + ["FileReader", /FileReader/], +]; + +// Comments may name what the code must not do; only code is judged. +function code(src: string): string { + return src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"); +} + +for (const rel of FILES) { + test(`${rel} names no API that could carry or keep the visitor's file`, () => { + const src = code(readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8")); + for (const [name, re] of FORBIDDEN) { + assert.ok(!re.test(src), `${rel} mentions ${name}`); + } + }); +} diff --git a/common/components/LocalFilePicker.tsx b/common/components/LocalFilePicker.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useEffect, useId, useRef } from "react"; + +// THE VISITOR'S OWN COPY, PICKED (lane missing-source, slice 2): one plain +// button that opens the browser's file picker, and the one-sentence promise +// beside it. The chosen File goes to `onPick` and nowhere else — the provider +// plays it from an object URL. No context here, so PlayerProvider can render +// it without a cycle. +// +// Nothing in this file may reach the network or storage; a unit test reads +// this source and fails on any API that could (LocalFilePicker.test.ts). + +export const LOCAL_FILE_PRIVACY = "Your file stays in this browser: nothing is uploaded."; +export const LOCAL_FILE_BUTTON = "Play your own copy"; + +export function LocalFilePicker({ + onPick, + takeFocus, + tone = "dark", +}: { + onPick: (file: File) => void; + // Asked once on mount: true when this control replaces a copy the visitor + // just stopped, and so takes the focus back. + takeFocus?: () => boolean; + tone?: "dark"; +}) { + const inputRef = useRef<HTMLInputElement | null>(null); + const buttonRef = useRef<HTMLButtonElement | null>(null); + const noteId = useId(); + useEffect(() => { + if (takeFocus?.()) buttonRef.current?.focus(); + // On mount only: a later render is not a return from "Stop". + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + return ( + <span className="inline-flex flex-wrap items-center justify-center gap-x-2 gap-y-1" data-tone={tone}> + <button + ref={buttonRef} + type="button" + onClick={() => inputRef.current?.click()} + aria-describedby={noteId} + className="inline-flex h-10 sm:h-9 items-center rounded-md bg-white/10 px-3 text-sm text-white hover:bg-white/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-white" + > + {LOCAL_FILE_BUTTON} + </button> + <input + ref={inputRef} + type="file" + accept="video/*,audio/*" + hidden + data-testid="local-file-input" + onChange={(e) => { + const file = e.currentTarget.files?.[0]; + // Cleared so the same file can be picked again after "Stop". + e.currentTarget.value = ""; + if (file) onPick(file); + }} + /> + <span id={noteId} className="text-xs text-zinc-300"> + {LOCAL_FILE_PRIVACY} + </span> + </span> + ); +} diff --git a/common/components/PlayerProvider.tsx b/common/components/PlayerProvider.tsx @@ -14,6 +14,7 @@ import { type ReactNode, } from "react"; import type ReactPlayerType from "react-player"; +import { QueryClientContext, type QueryClient } from "@tanstack/react-query"; import { fetchTranscript } from "./transcriptCache"; import { fetchSubs } from "./subsCache"; import { fetchDigest, hasDigest } from "./digestCache"; @@ -32,6 +33,27 @@ import type { OdyseePlayerHandle } from "./OdyseePlayer"; import type { TwitchPlayerHandle } from "./TwitchPlayer"; import type { KickPlayerHandle } from "./KickPlayer"; import type { FilePlayerHandle } from "./FilePlayer"; +// The visitor's own copy plays in the same element, imported STATICALLY: once a +// file is picked the page may make no request at all (lane missing-source), and +// a lazily loaded chunk would be one. +import LocalCopyPlayer from "./FilePlayer"; +import { LocalFilePicker } from "./LocalFilePicker"; +import { splitId } from "./originId"; +import { isNotPublicState, summaryState, type VideoState } from "../lib/availability"; +import type { DisplaySummary } from "../lib/transcripts"; +import { + sourceLinkLabel, + sourceMissingSentence, + type SourceGone, +} from "../lib/sourceMissing"; +import { + nudgeOffset, + offsetFromSync, + readOffset, + toCueTime, + toFileTime, + writeOffset, +} from "../lib/localFileClock"; const ReactPlayer = dynamic(() => import("react-player/youtube"), { ssr: false, @@ -95,6 +117,11 @@ export type TranscriptData = { mediaUrl?: string; // A salvage transcript (release 30, lane Q): how much of the runtime decoded. salvaged?: { decodedSeconds: number; totalSeconds: number }; + // The record's own state at its platform and the day it was first seen + // (lane missing-source). The modal reads `sourceGone`, which prefers the + // fresh summaries' state over this cached record's. + state?: VideoState; + stateSince?: string; // The cues of the track on show: the primary, or the alternate the viewer // picked (`track`). cues?: Cue[]; @@ -129,6 +156,8 @@ type Detail = { mediaUrl?: string; // A salvage transcript (release 30, lane Q): how much of the runtime decoded. salvaged?: { decodedSeconds: number; totalSeconds: number }; + state?: VideoState; + stateSince?: string; cues?: Cue[]; } & TrackFields; @@ -198,6 +227,30 @@ type PlayerState = { copyTranscriptMarkdown: () => Promise<boolean>; openInPreservetube: () => void; seekTo: (seconds: number) => void; + // THE SOURCE IS NO LONGER PUBLIC at its platform (lane missing-source): + // members-only, private or deleted, and the day it was first seen. No + // platform player is mounted for it. Fresh summaries first (a cached record + // in IndexedDB is never refreshed), else the record's own. Null otherwise. + sourceGone: SourceGone | null; + // The fresh summaries have not settled for the active video yet: no platform + // player is mounted and the own-copy offer waits (it goes where the state says). + sourceStatePending: boolean; + // THE VISITOR'S OWN COPY (lane missing-source, slice 2): a local file playing + // from an object URL in place of the platform player, on the cue clock + // through `offset` (lib/localFileClock.ts). Never uploaded; only the offset + // is ever stored. Null when none is playing for the active video. + localFile: { name: string; offset: number; error: boolean } | null; + // "This line is playing now" is armed: the next cue click sets the offset. + localSyncArmed: boolean; + openLocalFile: (file: File) => void; + clearLocalFile: () => void; + // "Stop": clear the copy and give focus back to the "Play your own copy" + // control that takes its place (takeLocalPickerFocus, read once by it). + stopLocalFile: () => void; + takeLocalPickerFocus: () => boolean; + nudgeLocalOffset: (delta: number) => void; + armLocalSync: (on: boolean) => void; + syncLocalTo: (cueStart: number) => void; }; type PlayerTimeState = { @@ -404,6 +457,87 @@ function coreReducer(state: Core, action: CoreAction): Core { } } +// The active video's state as the FRESH summaries say it (lane missing-source), +// read out of the react-query cache the workspace's summaries load into (keys +// ["manifest", origin] and ["summaries-page", origin, page]). The transcript +// record may be an IndexedDB copy from a visit before the state changed — that +// store is never refreshed — whereas the summaries are fetched per visit. +// - "known": a loaded page holds the video; its state wins. +// - "pending": the summaries this route loads are still coming. The cached +// record is NOT trusted meanwhile: no platform player is mounted (a stale +// record of a video since made members-only would embed it and ask the +// platform), the player slot stays the black box it is while any player +// loads. +// - "absent": the summaries settled without the video (loaded or failed), or +// this route loads none (the duplicates page): the record's state stands +// in. There is no per-channel summaries read to ask instead — summaries are +// cross-channel pages — so a route with none falls back to the record. +type FreshSummaryState = + | { kind: "known"; state: VideoState; stateSince?: string } + | { kind: "pending" } + | { kind: "absent" }; +const FRESH_PENDING: FreshSummaryState = { kind: "pending" }; +const FRESH_ABSENT: FreshSummaryState = { kind: "absent" }; + +function readFreshSummaryState(client: QueryClient, id: string): FreshSummaryState { + const { origin, slug } = splitId(id); + for (const [, page] of client.getQueriesData<DisplaySummary[]>({ queryKey: ["summaries-page", origin] })) { + if (!Array.isArray(page)) continue; + const hit = page.find((r) => r.slug === slug); + if (hit) { + const state = summaryState(hit); + return { kind: "known", state, ...(hit.stateSince ? { stateSince: hit.stateSince } : {}) }; + } + } + // Not in what has landed. Is more coming? + const cache = client.getQueryCache(); + const manifest = cache.find<{ pageCount?: number }>({ queryKey: ["manifest", origin], exact: true }); + // No summaries on this route, or an archive switched out of the search. + if (!manifest || manifest.isDisabled()) return FRESH_ABSENT; + if (manifest.state.status === "error") return FRESH_ABSENT; + if (manifest.state.status === "pending") return FRESH_PENDING; + const pageCount = manifest.state.data?.pageCount ?? 0; + for (let i = 0; i < pageCount; i++) { + const q = cache.find({ queryKey: ["summaries-page", origin, i], exact: true }); + // Not built yet: the manifest just landed and its pages are a render away. + if (!q) return FRESH_PENDING; + if (q.state.status === "pending" && !q.isDisabled()) return FRESH_PENDING; + } + return FRESH_ABSENT; +} + +function useFreshSummaryState(id: string | null): FreshSummaryState { + const client = useContext(QueryClientContext); + const [found, setFound] = useState<{ id: string; key: string; value: FreshSummaryState } | null>(null); + useEffect(() => { + if (!client || !id) return; + const read = () => { + const value = readFreshSummaryState(client, id); + const key = value.kind === "known" ? `known\u0000${value.state}\u0000${value.stateSince ?? ""}` : value.kind; + setFound((prev) => (prev?.id === id && prev.key === key ? prev : { id, key, value })); + }; + read(); + return client.getQueryCache().subscribe((event) => { + if (event.type === "observerResultsUpdated") return; + const k = event.query.queryKey[0]; + if (k === "summaries-page" || k === "manifest") read(); + }); + }, [client, id]); + if (!id || !client) return FRESH_ABSENT; + // Before the first read for this video: not yet trusted. + if (!found || found.id !== id) return FRESH_PENDING; + return found.value; +} + +// localStorage, or null where the browser refuses it. +function safeLocalStorage(): Storage | null { + try { + return typeof window === "undefined" ? null : window.localStorage; + } catch { + return null; + } +} + export function PlayerProvider({ children, features = DEFAULT_PLAYER_FEATURES, @@ -423,6 +557,20 @@ export function PlayerProvider({ const [fileError, setFileError] = useState(false); const playerRef = useRef<PlayerHandle | null>(null); const pendingSeekRef = useRef<number | null>(null); + const currentTimeRef = useRef(0); + currentTimeRef.current = currentTime; + // The visitor's own copy (slice 2). The File itself is never kept: only its + // object URL (revoked when it is replaced, cleared, the video changes or the + // provider unmounts) and its name, shown on screen and nowhere else. + const [local, setLocal] = useState<{ slug: string; url: string; name: string } | null>(null); + const [localOffset, setLocalOffset] = useState(0); + const [localError, setLocalError] = useState(false); + const [localSyncArmed, setLocalSyncArmed] = useState(false); + const localOffsetRef = useRef(0); + localOffsetRef.current = localOffset; + // The file element's own time, as its last progress event said. + const localRawRef = useRef(0); + const localUrlRef = useRef<string | null>(null); const readyForSlugRef = useRef<string | null>(null); // The YouTube embed said it cannot play this video (removed, private, // embedding off). Its progress events are then the dead player's 0, never @@ -471,6 +619,8 @@ export function PlayerProvider({ hlsUrl: detail.hlsUrl, mediaUrl: detail.mediaUrl, ...(detail.salvaged ? { salvaged: detail.salvaged } : {}), + ...(detail.state ? { state: detail.state } : {}), + ...(detail.stateSince ? { stateSince: detail.stateSince } : {}), // A `vt` the record does not hold reads as the primary. cues: cuesOfTrack(detail, urlVt) ?? detail.cues, tracks: recordTracks(detail), @@ -480,6 +630,19 @@ export function PlayerProvider({ : (detail.track ?? null), }; }, [detail, detailMatches, urlVt]); + const freshState = useFreshSummaryState(activeSlug); + // The summaries are still coming: neither the cached record's state nor a + // platform player is trusted yet (useFreshSummaryState). + const sourceStatePending = freshState.kind === "pending"; + const sourceGone: SourceGone | null = useMemo(() => { + if (!data || freshState.kind === "pending") return null; + const state = freshState.kind === "known" ? freshState.state : data.state; + const since = freshState.kind === "known" ? freshState.stateSince : data.stateSince; + if (!state || !isNotPublicState(state)) return null; + return { state, ...(since ? { stateSince: since } : {}) }; + }, [data, freshState]); + const localActive = local !== null && local.slug === activeSlug; + const status: Status = !activeSlug ? "idle" : detailMatches @@ -564,6 +727,7 @@ export function PlayerProvider({ const copyShareUrl = useCallback(async (): Promise<boolean> => { if (!data) return false; const t = + localActive || data.platform === "youtube" || data.platform === "kick" || (playsFile(data.platform) && data.mediaUrl) @@ -587,7 +751,7 @@ export function PlayerProvider({ } catch { return false; } - }, [data, currentTime, urlTime, modalMode]); + }, [data, currentTime, urlTime, modalMode, localActive]); const openInPreservetube = useCallback(() => { if (!data || data.platform !== "youtube") return; @@ -686,6 +850,81 @@ export function PlayerProvider({ setCurrentTime(seconds); }, []); + // ── the visitor's own copy (lane missing-source, slice 2) ──────────────── + const revokeLocalUrl = useCallback(() => { + if (localUrlRef.current) URL.revokeObjectURL(localUrlRef.current); + localUrlRef.current = null; + }, []); + + const openLocalFile = useCallback( + (file: File) => { + if (!activeSlug) return; + revokeLocalUrl(); + const url = URL.createObjectURL(file); + localUrlRef.current = url; + localRawRef.current = 0; + setLocalError(false); + setLocalSyncArmed(false); + setLocalOffset(readOffset(safeLocalStorage(), activeSlug)); + setPlaying(false); + setLocal({ slug: activeSlug, url, name: file.name }); + }, + [activeSlug, revokeLocalUrl], + ); + + const clearLocalFile = useCallback(() => { + revokeLocalUrl(); + setLocal(null); + setLocalError(false); + setLocalSyncArmed(false); + setPlaying(false); + }, [revokeLocalUrl]); + + // When "Stop" was pressed; the picker that mounts in the copy's place takes + // focus if it mounts within a moment of it (and only once). + const pickerFocusAtRef = useRef(0); + const stopLocalFile = useCallback(() => { + pickerFocusAtRef.current = Date.now(); + clearLocalFile(); + }, [clearLocalFile]); + const takeLocalPickerFocus = useCallback(() => { + const due = pickerFocusAtRef.current > 0 && Date.now() - pickerFocusAtRef.current < 2000; + pickerFocusAtRef.current = 0; + return due; + }, []); + + const applyLocalOffset = useCallback( + (next: number) => { + if (!activeSlug) return; + setLocalOffset(next); + localOffsetRef.current = next; + writeOffset(safeLocalStorage(), activeSlug, next); + setCurrentTime(toCueTime(localRawRef.current, next)); + }, + [activeSlug], + ); + + const nudgeLocalOffset = useCallback( + (delta: number) => applyLocalOffset(nudgeOffset(localOffsetRef.current, delta)), + [applyLocalOffset], + ); + + const syncLocalTo = useCallback( + (cueStart: number) => { + applyLocalOffset(offsetFromSync(localRawRef.current, cueStart)); + setLocalSyncArmed(false); + }, + [applyLocalOffset], + ); + + const armLocalSync = useCallback((on: boolean) => setLocalSyncArmed(on), []); + + // Another video, or none: the copy belonged to the one it was picked on. + useEffect(() => { + if (local && local.slug !== activeSlug) clearLocalFile(); + }, [activeSlug, local, clearLocalFile]); + useEffect(() => revokeLocalUrl, [revokeLocalUrl]); + // Active-video change: reset chat state, kick off the transcript fetch. // The chat fetch (if needed) runs in a separate effect keyed on // `modalMode` so we don't fetch chat for the common transcript-only case. @@ -726,6 +965,8 @@ export function PlayerProvider({ webpageUrl: full.webpageUrl, hlsUrl: full.hlsUrl, mediaUrl: full.mediaUrl, + ...(full.state ? { state: full.state } : {}), + ...(full.stateSince ? { stateSince: full.stateSince } : {}), cues: full.cues, ...(full.altTracks?.length ? { track: full.track, altTracks: full.altTracks } @@ -922,11 +1163,17 @@ export function PlayerProvider({ useEffect(() => { if (!modalOpen) return; const onKey = (e: KeyboardEvent) => { - if (e.key === "Escape") setDisplayMode("mini"); + if (e.key !== "Escape") return; + // Esc first cancels "This line is playing now", if it is armed. + if (localSyncArmed) { + setLocalSyncArmed(false); + return; + } + setDisplayMode("mini"); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [modalOpen, setDisplayMode]); + }, [modalOpen, setDisplayMode, localSyncArmed]); const handleReady = () => { if ( @@ -980,6 +1227,17 @@ export function PlayerProvider({ copyTranscriptMarkdown, openInPreservetube, seekTo, + sourceGone, + sourceStatePending, + localFile: localActive && local ? { name: local.name, offset: localOffset, error: localError } : null, + localSyncArmed: localActive && localSyncArmed, + openLocalFile, + clearLocalFile, + stopLocalFile, + takeLocalPickerFocus, + nudgeLocalOffset, + armLocalSync, + syncLocalTo, }), [ activeSlug, @@ -1007,6 +1265,20 @@ export function PlayerProvider({ copyTranscriptMarkdown, openInPreservetube, seekTo, + sourceGone, + sourceStatePending, + localActive, + local, + localOffset, + localError, + localSyncArmed, + openLocalFile, + clearLocalFile, + stopLocalFile, + takeLocalPickerFocus, + nudgeLocalOffset, + armLocalSync, + syncLocalTo, ], ); const timeValue: PlayerTimeState = useMemo( @@ -1043,7 +1315,57 @@ export function PlayerProvider({ {showPlayer && ( <div className={containerClass} aria-hidden={displayMode === "hidden"}> - {data.platform === "rumble" ? ( + {localActive && local ? ( + // The visitor's own copy, from its object URL, on the cue clock: + // every seek goes in at cue + offset and every tick comes out at + // file - offset, so follow, click-to-seek and the clip marks are + // unchanged. Mounted INSTEAD of the platform player. + <LocalCopyPlayer + key={`local:${local.url}`} + ref={(p: FilePlayerHandle | null) => { + playerRef.current = p + ? { seekTo: (s: number) => p.seekTo(toFileTime(s, localOffsetRef.current)) } + : null; + }} + url={local.url} + label="Your copy" + autoFocus + playing={playing} + onReady={() => { + // A video whose player was already ready (a platform embed) + // carries on where the transcript is; otherwise the pending + // ?t= or cue click is taken as for any player. + if (readyForSlugRef.current === activeSlug && currentTimeRef.current > 0) { + playerRef.current?.seekTo(currentTimeRef.current, "seconds"); + } else { + handleReady(); + } + }} + onPlay={() => setPlaying(true)} + onPause={() => setPlaying(false)} + onProgress={(s: { playedSeconds: number }) => { + localRawRef.current = s.playedSeconds; + setCurrentTime(toCueTime(s.playedSeconds, localOffsetRef.current)); + }} + onError={() => setLocalError(true)} + /> + ) : sourceGone ? ( + // No longer public at its platform: no embed, no request to it. + // Click-to-seek still moves the transcript (seekTo's no-handle path). + <SourceMissingPanel + gone={sourceGone} + platform={data.platform} + isLivestream={data.isLivestream} + webpageUrl={data.webpageUrl} + compact={displayMode === "mini"} + onPick={openLocalFile} + takeFocus={takeLocalPickerFocus} + /> + ) : sourceStatePending ? ( + // The fresh state is not in yet: the empty black slot every player + // shows while it loads, and nothing asked of any platform. + <div className="h-full w-full" aria-busy="true" data-testid="player-pending" /> + ) : data.platform === "rumble" ? ( <RumblePlayer key={data.id} ref={(p: RumblePlayerHandle | null) => { @@ -1210,6 +1532,66 @@ function KickUnavailable({ ); } +// The player slot of a video whose source is no longer public at its platform +// (lane missing-source): the one sentence (lib/sourceMissing.ts), the platform +// link kept but marked, and the visitor's own copy. Never names who observed +// the state or how. +function SourceMissingPanel({ + gone, + platform, + isLivestream, + webpageUrl, + compact, + onPick, + takeFocus, +}: { + gone: SourceGone; + platform: Platform; + isLivestream: boolean; + webpageUrl: string; + compact: boolean; + onPick: (file: File) => void; + takeFocus: () => boolean; +}) { + const sentence = sourceMissingSentence({ + state: gone.state, + stateSince: gone.stateSince, + platform, + isLivestream, + }); + if (compact) { + return ( + <div className="flex h-full w-full items-center justify-center p-2 pb-8 text-center"> + <p className="text-xs text-zinc-200">No longer public</p> + </div> + ); + } + return ( + <section + aria-label="Source availability" + data-testid="source-missing" + data-state={gone.state} + className="flex h-full w-full flex-col items-center justify-center gap-2 sm:gap-3 overflow-y-auto p-3 sm:p-4 text-center" + > + <p className="max-w-md text-sm text-zinc-100">{sentence}</p> + {webpageUrl ? ( + <a + href={webpageUrl} + target="_blank" + rel="noopener noreferrer" + className="text-sm text-zinc-200 underline hover:text-white" + > + {sourceLinkLabel(platform, gone.state)} + </a> + ) : ( + // No address on record: the label, never an empty link. + <span className="text-sm text-zinc-200">{sourceLinkLabel(platform, gone.state)}</span> + )} + <LocalFilePicker onPick={onPick} takeFocus={takeFocus} /> + </section> + ); +} + function HiddenControls({ title, onShow, diff --git a/common/components/SearchResults.tsx b/common/components/SearchResults.tsx @@ -681,7 +681,7 @@ const ResultCard = memo(function ResultCard({ </span> {group.isLivestream && <LivestreamBadge />} {group.ageRestricted && <AgeRestrictedBadge />} - <VideoStateBadge state={group.state} /> + <VideoStateBadge state={group.state} since={group.stateSince} /> {siblings.length > 0 && ( <DuplicateBadge count={siblings.length} /> )} diff --git a/common/components/SearchSessionContext.tsx b/common/components/SearchSessionContext.tsx @@ -151,6 +151,8 @@ export type ResultGroup = { // Presence on the source platform, for the card's state badge. Posts are // always "available" — a post has no channel listing to fall out of. state: VideoState; + // The day the archive first saw `state` (YYYYMMDD), for the badge's tooltip. + stateSince?: string; // Carried through so the card can flag likely-expired stream VODs (Kick, // Twitch) via vodExpiry(platform, uploadDate). platform: Platform; @@ -1022,6 +1024,7 @@ function useSearchSessionState() { isLivestream: t.isLivestream, ageRestricted: t.ageRestricted, state: summaryState(t), + ...(t.stateSince ? { stateSince: t.stateSince } : {}), platform: t.platform, uploadDate: t.uploadDate, hits: [], @@ -1050,6 +1053,7 @@ function useSearchSessionState() { isLivestream: t.isLivestream, ageRestricted: t.ageRestricted, state: summaryState(t), + ...(t.stateSince ? { stateSince: t.stateSince } : {}), platform: t.platform, uploadDate: t.uploadDate, hits: hitsBySlug.get(t.slug) ?? [], diff --git a/common/components/TranscriptModal.tsx b/common/components/TranscriptModal.tsx @@ -38,6 +38,7 @@ import { formatTimestamp } from "../lib/vtt"; import { formatDate } from "../lib/format"; import { trackLabels } from "../lib/captionTracks"; import { partialTranscriptLine } from "../lib/salvageMark"; +import { LocalFileBar } from "./LocalFileBar"; type DisplayCue = { start: number; @@ -76,6 +77,8 @@ export default function TranscriptModal() { openInPreservetube, seekTo, features, + localSyncArmed, + syncLocalTo, } = usePlayer(); // Off on a site whose site.json sets `transcriptDownloads: false`: the two // per-video export controls (the Download menu and Copy MD) are not rendered @@ -187,12 +190,15 @@ export default function TranscriptModal() { }, []); // Stable seek callback so memo'd CueRow doesn't invalidate per render. + // With "This line is playing now" armed, a cue click sets the visitor's own + // copy's offset instead of seeking (lane missing-source, slice 2). const onSeekRow = useCallback( (start: number) => { scrollKindRef.current = "smooth"; - seekTo(start); + if (localSyncArmed) syncLocalTo(start); + else seekTo(start); }, - [seekTo], + [seekTo, localSyncArmed, syncLocalTo], ); // Three-way selector, expressed as two toggles that each fall back to the @@ -345,6 +351,9 @@ export default function TranscriptModal() { )} </div> + {/* The visitor's own copy: the plain control, or its offset strip. */} + <LocalFileBar /> + {modalNotice && ( <p role="status" diff --git a/common/components/badges.tsx b/common/components/badges.tsx @@ -1,4 +1,5 @@ import { VIDEO_STATE_LABELS, type VideoState } from "../lib/availability"; +import { stateSinceTitle } from "../lib/sourceMissing"; const badgeBase = "shrink-0 text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded"; @@ -49,12 +50,15 @@ const STATE_STYLES: Record< }, }; -export function VideoStateBadge({ state }: { state: VideoState }) { +// `since` (YYYYMMDD, lane missing-source): the day the archive first saw the +// state, added to the tooltip ("…; first seen 19 Nov 2026"). The label and test id +// are unchanged. +export function VideoStateBadge({ state, since }: { state: VideoState; since?: string }) { if (state === "available") return null; const style = STATE_STYLES[state]; return ( <span - title={style.title} + title={stateSinceTitle(style.title, since)} data-testid={`state-badge-${state}`} data-state={state} aria-label={VIDEO_STATE_LABELS[state]} diff --git a/common/components/transcriptStore.ts b/common/components/transcriptStore.ts @@ -12,7 +12,12 @@ const DB_NAME = "yt-dlp-transcript-browser"; // the bare slug, so behavior is unchanged after the one-time wipe. // v4 adds the optional `hlsUrl` field to cached TranscriptDetail (Kick VOD // playback); wipe so stale entries re-fetch the authoritative page JSON. -const DB_VERSION = 4; +// v5 (lane missing-source) adds `state` / `stateSince` to a record whose +// source is no longer public at its platform; wipe so a record cached before +// re-fetches. (A cached record is never refreshed after that — the modal reads +// a video's state from the fresh summaries first, PlayerProvider +// useFreshSummaryState.) +const DB_VERSION = 5; const STORE = "transcripts"; type Mode = "pending" | "ok" | "unavailable"; diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts @@ -801,6 +801,100 @@ test("(l) release 17: a tiered raw live chat that cannot be read, with no cues t assert.equal((await runIndex()).res.changed, 0); }); +test("(m) lane missing-source: a record no longer public carries its state and the day it was first seen", async () => { + resetCorpus([CHANNEL]); + seedVideo("m1"); + seedVideo("p1"); + seedVideo("u1"); + writeJson(path.join(videoDir("m1"), "availability.json"), { + checkedAt: "2026-01-09T08:00:00.000Z", + checkedBy: "fetch", + availability: "members_only", + history: [ + { availability: "public", observedAt: "2026-01-01T08:00:00.000Z", source: "backfill" }, + { availability: "members_only", observedAt: "2026-01-05T23:30:00.000Z", source: "fetch" }, + ], + }); + // u1 fell out of the listing and was never confirmed: a suspicion, summaries only. + writeJson(path.join(paths.channelsDir, CHANNEL, "maybe-missing.json"), { + checkedAt: "2026-01-08T12:00:00.000Z", + freshPlaylistCount: 0, + ids: ["u1"], + }); + await runIndex(); + const m1 = transcriptRecord("m1", CHANNEL) as Published & { stateSince?: string }; + assert.equal(m1.state, "members_only"); + assert.equal(m1.stateSince, "20260105"); + for (const id of ["p1", "u1"]) { + const r = transcriptRecord(id, CHANNEL) as Record<string, unknown>; + assert.ok(!("state" in r) && !("stateSince" in r), `${id}'s shard record has no state keys`); + } + const sm = summaries().find((s) => s.id === "m1") as Published & { stateSince?: string }; + assert.equal(sm.state, "members_only"); + assert.equal(sm.stateSince, "20260105"); + const su = summaries().find((s) => s.id === "u1") as Record<string, unknown>; + assert.equal(su.state, "maybe_missing"); + assert.ok(!("stateSince" in su)); + + // An index built before the day was cached: the record re-read once, and its + // shard gains the day; the version recorded, so the next build re-reads none. + withIndex((db) => { + const mt = db("mtimes"); + for (const { key, value } of [...mt.getRange()]) { + const rec = value as Record<string, unknown>; + if (!rec.availabilityDay) continue; + delete rec.availabilityDay; + delete rec.availabilityDayRead; + mt.putSync(key, rec); + } + db("meta").removeSync("stateSince"); + }); + rmSync(path.join(paths.exportSharedTranscriptsDir, CHANNEL), { recursive: true, force: true }); + const { log } = await runIndex(); + assert.ok(log.some((l) => /State since v1: 1 record\(s\) re-read\./.test(l)), log.join("\n")); + assert.equal((transcriptRecord("m1", CHANNEL) as Published & { stateSince?: string }).stateSince, "20260105"); + const again = await runIndex(); + assert.ok(!again.log.some((l) => /State since v1/.test(l))); +}); + +test("(n) lane missing-source: an undated state with a channel held is re-read once, not on every build", async () => { + resetCorpus(); + seedVideo("n1"); + seedDriveChannel(); + // Removed, recorded before history existed: no day is known. + writeJson(path.join(videoDir("n1"), "availability.json"), { + checkedAt: "2023-04-02T00:00:00.000Z", + checkedBy: "check", + availability: "deleted", + }); + await runIndex(); + const n1 = transcriptRecord("n1", CHANNEL) as Published & { stateSince?: string }; + assert.equal(n1.state, "deleted"); + assert.ok(!("stateSince" in n1), "a legacy checkedAt publishes no day"); + + // An index from before the day was cached, and the drive away: the version + // cannot be recorded while a channel is held. + withIndex((db) => { + db("meta").removeSync("stateSince"); + const mt = db("mtimes"); + for (const { key, value } of [...mt.getRange()]) { + const rec = value as Record<string, unknown>; + if (!("availabilityDayRead" in rec)) continue; + delete rec.availabilityDayRead; + mt.putSync(key, rec); + } + }); + unmount(); + const second = await runIndex(); + assert.deepEqual(second.res.heldChannels, [DRIVE_CHANNEL]); + assert.ok(second.log.some((l) => /State since v1: 1 record\(s\) re-read\./.test(l)), second.log.join("\n")); + const third = await runIndex(); + assert.deepEqual(third.res.heldChannels, [DRIVE_CHANNEL]); + assert.equal(third.res.changed, 0, third.log.join("\n")); + assert.ok(third.log.some((l) => /State since v1: 0 record\(s\) re-read\./.test(l)), third.log.join("\n")); + assert.ok(third.log.some((l) => l.startsWith("Shared transcript pages up to date")), third.log.join("\n")); +}); + test("(z) no write this file caused landed outside its temp root", () => { // LMDB writes natively, past the spy: its file must be under the root too. assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath); diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -121,7 +121,7 @@ import { type SubTrack, } from "../lib/videoStatus"; import { - resolveEffectiveAvailability, + resolveEffectiveAvailabilityObserved, resolveMaybeMissingState, } from "../lib/availability-server"; import { @@ -261,6 +261,26 @@ function storedCuesEmpty(db: { getBinaryFast(key: IndexKey): Buffer | undefined const ALT_TRACKS_VERSION = 1; const ALT_TRACKS_KEY = "altTracks"; +// THE DAY A STATE WAS FIRST SEEN (lane missing-source): an MtimeRecord now +// carries `availabilityDay` beside a non-available `availability`, and the +// transcript pages carry `state` + `stateSince` on such a record. The first +// build that sees a new STATE_SINCE_VERSION re-derives every record whose +// cached state is not "available" and that has no day yet — sparse by +// construction — then records the version, only when no channel is held. Each +// re-derived record also carries `availabilityDayRead`, so one with no day to +// find is not taken again on the next build (a held channel would otherwise +// keep the version unrecorded and re-page the shared tree on every build). +const STATE_SINCE_VERSION = 1; +const STATE_SINCE_KEY = "stateSince"; + +// An ISO instant as the YYYYMMDD day of uploadDate's shape (UTC), or undefined. +function isoDay(iso: string | null | undefined): string | undefined { + if (!iso) return undefined; + const ms = Date.parse(iso); + if (!Number.isFinite(ms)) return undefined; + return new Date(ms).toISOString().slice(0, 10).replace(/-/g, ""); +} + // Whether a scanned record can hold an alternate track at all — no file read. function canHoldAltTracks(s: { transcriptKind: IndexTranscript["kind"] | null; @@ -336,6 +356,15 @@ type MtimeRecord = { // availabilityMs already participates in change detection, so any video whose // availability.json is rewritten from here on picks up the exact string. availability?: Availability; + // The day (YYYYMMDD) the archive first saw `availability`, written only when + // it is not an "available" state (lane missing-source; STATE_SINCE_VERSION). + availabilityDay?: string; + // The STATE_SINCE_VERSION this record's day was derived under, written beside + // a non-available `availability` whether or not a day was found: "no day" (a + // legacy record with no history entry behind its state) is a SETTLED answer, + // so the one-time re-read never takes this record again — not even while a + // held channel keeps the version itself from being recorded. + availabilityDayRead?: number; isDeleted: boolean; isUnlisted: boolean; indexKey: IndexKey; @@ -974,6 +1003,25 @@ export async function buildIndex({ } log(`Alternate tracks v${ALT_TRACKS_VERSION}: ${reread} record(s) re-read.`); } + + // Records whose cached state is not "available" and carries no day yet + // (STATE_SINCE_KEY). A schema bump re-reads everything anyway. + const stateSinceDue = meta.get(STATE_SINCE_KEY) !== STATE_SINCE_VERSION; + if (stateSinceDue && !schemaBumped) { + const queued = new Set( + [...added, ...changed].map((s) => pathKeyId([s.channelSlug, s.videoDir])), + ); + let reread = 0; + for (const s of live) { + const pk: PathKey = [s.channelSlug, s.videoDir]; + const prev = mtimes.get(pk); + if (!prev || stateFromRecord(prev) === "available") continue; + if (prev.availabilityDay || prev.availabilityDayRead === STATE_SINCE_VERSION) continue; + reread++; + if (!queued.has(pathKeyId(pk))) changed.push(s); + } + log(`State since v${STATE_SINCE_VERSION}: ${reread} record(s) re-read.`); + } let altTrackRecords = 0; // RECORDED DATES (release 20 D1, lib/recordedDate.ts): each channel's rule, @@ -1360,9 +1408,15 @@ export async function buildIndex({ // to notice. Same source buildStats' status chart used to read // directly, so the two can't disagree. let availability: Availability | undefined; + let availabilityDay: string | undefined; + let availabilityDayRead: number | undefined; if (s.availabilityMs !== null) { - availability = - (await resolveEffectiveAvailability(videoFullDir)) ?? undefined; + const observed = await resolveEffectiveAvailabilityObserved(videoFullDir); + availability = observed?.availability; + if (availability && stateFromAvailability(availability) !== "available") { + availabilityDay = isoDay(observed?.observedAt); + availabilityDayRead = STATE_SINCE_VERSION; + } } byChannel.put(indexToChannelKey(indexKey), 1); @@ -1373,6 +1427,8 @@ export async function buildIndex({ availabilityMs: s.availabilityMs, digestMs: s.digestMs, ...(availability ? { availability } : {}), + ...(availabilityDay ? { availabilityDay } : {}), + ...(availabilityDayRead ? { availabilityDayRead } : {}), isDeleted: availability === "deleted", isUnlisted: availability === "unlisted", indexKey, @@ -1596,6 +1652,38 @@ export async function buildIndex({ return { push, finish }; }; + // The CONFIRMED states, out of MtimeRecord — which caches the availability + // check done at mutation-processing time — read before the transcript pages + // so a record whose source is no longer as it was carries its `state` and + // `stateSince` on its shard (lane missing-source). Previously this loop read + // availability.json for every video on every build (~28k sequential disk + // reads), which stalled GC right before the heaviest phase. + // + // All three maps are SPARSE: only non-`available` videos get an entry, so the + // common case costs nothing. stateByPath is the same data keyed the way + // buildStats needs it (see the videoState sub-DB written below); the + // maybe-missing overlay further down adds to the first two, never to the shards. + const stateByIndexKey = new Map<string, VideoState>(); + const stateByPath = new Map<string, VideoState>(); + const stateSinceByIndexKey = new Map<string, string>(); + for (const { key, value } of mtimes.getRange()) { + const rec = value as MtimeRecord; + const st = stateFromRecord(rec); + if (st === "available") continue; + const ikId = indexKeyId(rec.indexKey); + stateByIndexKey.set(ikId, st); + stateByPath.set(pathKeyId(key as PathKey), st); + if (rec.availabilityDay) stateSinceByIndexKey.set(ikId, rec.availabilityDay); + } + // What a transcript record carries: a confirmed state and its day, or nothing. + const shardStateOf = (indexKey: IndexKey): Pick<TranscriptDetail, "state" | "stateSince"> => { + const ikId = indexKeyId(indexKey); + const st = stateByIndexKey.get(ikId); + if (!st || st === "available" || st === "maybe_missing") return {}; + const since = stateSinceByIndexKey.get(ikId); + return { state: st, ...(since ? { stateSince: since } : {}) }; + }; + if (sharedNeedsBuild) { // One channel's transcript tree into `channelDir`. The SHARED tree (what every // site copies) leaves local recordings out; a channel that holds one also @@ -1643,6 +1731,9 @@ export async function buildIndex({ const detail: TranscriptDetail = { ...summary, cues: cueList, + // Only on a record whose source is no longer as it was (lane + // missing-source); every other record's bytes are what they were. + ...shardStateOf(indexKey), ...(trackFields?.altTracks?.length ? { track: trackFields.track, altTracks: trackFields.altTracks } : {}), @@ -1742,23 +1833,8 @@ export async function buildIndex({ log(`Shared transcript pages up to date; skipping rewrite.`); } - // Build lookups from indexKey → VideoState out of MtimeRecord, which caches - // the availability check done at mutation-processing time. Previously this - // loop read availability.json for every video on every build (~28k sequential - // disk reads), which stalled GC right before the heaviest phase. - // - // Both maps are SPARSE: only non-`available` videos get an entry, so the - // common case costs nothing. stateByPath is the same data keyed the way - // buildStats needs it (see the videoState sub-DB written below). - const stateByIndexKey = new Map<string, VideoState>(); - const stateByPath = new Map<string, VideoState>(); - for (const { key, value } of mtimes.getRange()) { - const rec = value as MtimeRecord; - const st = stateFromRecord(rec); - if (st === "available") continue; - stateByIndexKey.set(indexKeyId(rec.indexKey), st); - stateByPath.set(pathKeyId(key as PathKey), st); - } + // The confirmed states were read out of MtimeRecord above, before the + // transcript pages (`stateByIndexKey`, `stateByPath`, `stateSinceByIndexKey`). // Overlay the channel-level quick availability check. Computed here rather // than in the per-video loop above on purpose: maybe-missing.json is a @@ -1884,6 +1960,7 @@ export async function buildIndex({ if (isLocalRecord(summary)) continue; const display = toDisplaySummary(summary, { state: stateByIndexKey.get(indexKeyId(indexKey)), + stateSince: stateSinceByIndexKey.get(indexKeyId(indexKey)), }); const tracks: Record<string, Cue[]> = {}; let hasLiveChat = false; @@ -2534,7 +2611,10 @@ export async function buildIndex({ if (acc) acc.count++; tagCounter.add(ik[1], s.curatedTags); buffer.push( - toDisplaySummary(s, { state: stateByIndexKey.get(indexKeyId(ik)) }), + toDisplaySummary(s, { + state: stateByIndexKey.get(indexKeyId(ik)), + stateSince: stateSinceByIndexKey.get(indexKeyId(ik)), + }), ); total++; if (buffer.length >= pageSize) await flushPage(); @@ -2711,6 +2791,9 @@ export async function buildIndex({ if (altTracksDue && held.size === 0) { await meta.put(ALT_TRACKS_KEY, ALT_TRACKS_VERSION); } + if (stateSinceDue && held.size === 0) { + await meta.put(STATE_SINCE_KEY, STATE_SINCE_VERSION); + } for (const slug of recordedDateRuleChanged) { const rule = channelConfigs.get(slug)?.recordedDate; const key = `${RECORDED_DATE_RULE_KEY_PREFIX}${slug}`; diff --git a/common/controller/fetchLiveChat.test.ts b/common/controller/fetchLiveChat.test.ts @@ -189,6 +189,132 @@ test("a rate-limited pass records the cooldown and fails; an auth gate retries o assert.ok(calls[1].includes("--cookies-from-browser")); }); +test("a members-only refusal is recorded as the video's availability, and the job still fails", async () => { + const dir = await video("ym1", { webpage_url: "https://www.youtube.com/watch?v=ym1", was_live: true }); + // What the backfill wrote while the stream was live and public. + await writeFile( + path.join(dir, "availability.json"), + JSON.stringify({ + checkedAt: "2026-01-02T03:00:00.000Z", + checkedBy: "backfill", + availability: "public", + history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], + }), + ); + const stderr = + "ERROR: [youtube] ym1: Join this channel to get access to members-only content like this video, and other exclusive perks."; + const { run } = stubRunner({ exitCode: 1, stderr, writes: null }); + const l = log(); + await assert.rejects( + fetchLiveChat({ + paths, slug: SLUG, videoId: "ym1", videoUrl: "https://www.youtube.com/watch?v=ym1", + channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, + onLog: l.onLog, signal: new AbortController().signal, run, paceSeconds: 0, + }), + /could not fetch the chat of ym1/, + ); + const rec = JSON.parse(await readFile(path.join(dir, "availability.json"), "utf8")); + assert.equal(rec.availability, "members_only"); + assert.equal(rec.checkedBy, "fetch"); + assert.deepEqual(rec.history.map((h: { availability: string; source: string }) => [h.availability, h.source]), [ + ["public", "backfill"], + ["members_only", "fetch"], + ]); + // The same refusal again rewrites nothing. + const before = await readFile(path.join(dir, "availability.json"), "utf8"); + await assert.rejects( + fetchLiveChat({ + paths, slug: SLUG, videoId: "ym1", videoUrl: "https://www.youtube.com/watch?v=ym1", + channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, + onLog: l.onLog, signal: new AbortController().signal, run, paceSeconds: 0, + }), + ); + assert.equal(await readFile(path.join(dir, "availability.json"), "utf8"), before); +}); + +test("a members-only refusal is recorded even when the cookie retry then fetches the chat", async () => { + const dir = await video("ym2", { webpage_url: "https://www.youtube.com/watch?v=ym2", was_live: true }); + await writeFile( + path.join(dir, "availability.json"), + JSON.stringify({ + checkedAt: "2026-01-02T03:00:00.000Z", + checkedBy: "backfill", + availability: "public", + history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], + }), + ); + const calls: string[][] = []; + const refusedThenOk = async (cwd: string, args: string[]): Promise<AttemptOutcome> => { + calls.push(args); + if (calls.length === 1) { + return { + exitCode: 1, + stderrTail: "ERROR: [youtube] ym2: Join this channel to get access to members-only content like this video, and other exclusive perks.", + archiveLine: null, + formatLine: null, + }; + } + const base = args[args.findIndex((a) => a.startsWith("subtitle:"))].slice("subtitle:".length); + await writeFile(path.join(cwd, `${base}.live_chat.json`), REPLAY); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }; + const r = await fetchLiveChat({ + paths, slug: SLUG, videoId: "ym2", videoUrl: "https://www.youtube.com/watch?v=ym2", + channelConfig: CONFIG, cookiePolicy: { cookies: "firefox", mode: "when-required" }, + onLog: () => {}, signal: new AbortController().signal, run: refusedThenOk, paceSeconds: 0, + }); + assert.equal(r.status, "fetched"); + assert.equal(calls.length, 2); + assert.ok(calls[1].includes("--cookies-from-browser"), "the retry carried the members' cookies"); + const rec = JSON.parse(await readFile(path.join(dir, "availability.json"), "utf8")); + assert.equal(rec.availability, "members_only"); + assert.equal(rec.checkedBy, "fetch"); +}); + +test("a removal is never recorded from a chat refusal: only the availability check establishes one", async () => { + const dir = await video("yd1", { webpage_url: "https://www.youtube.com/watch?v=yd1", was_live: true }); + const before = JSON.stringify({ + checkedAt: "2026-01-02T03:00:00.000Z", + checkedBy: "backfill", + availability: "public", + history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], + }); + await writeFile(path.join(dir, "availability.json"), before); + const { run } = stubRunner({ + exitCode: 1, + stderr: "ERROR: [youtube] yd1: Video unavailable. This video has been removed by the uploader", + writes: null, + }); + await assert.rejects( + fetchLiveChat({ + paths, slug: SLUG, videoId: "yd1", videoUrl: "https://www.youtube.com/watch?v=yd1", + channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, + onLog: () => {}, signal: new AbortController().signal, run, paceSeconds: 0, + }), + ); + assert.equal(await readFile(path.join(dir, "availability.json"), "utf8"), before); +}); + +test("a rate-limited or soft-blocked chat pass records no availability", async () => { + const dir = await video("yr1", { webpage_url: "https://www.youtube.com/watch?v=yr1", was_live: true }); + for (const stderr of [ + "ERROR: [youtube] yr1: HTTP Error 429: Too Many Requests", + "ERROR: [youtube] yr1: This content isn't available, try again later.", + "ERROR: [youtube] yr1: Sign in to confirm you're not a bot", + ]) { + const { run } = stubRunner({ exitCode: 1, stderr, writes: null }); + await assert.rejects( + fetchLiveChat({ + paths, slug: SLUG, videoId: "yr1", videoUrl: "https://www.youtube.com/watch?v=yr1", + channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, + onLog: () => {}, signal: new AbortController().signal, run, paceSeconds: 0, + onPlatformBackoff: () => {}, + }), + ); + } + await assert.rejects(readFile(path.join(dir, "availability.json"), "utf8")); +}); + test("the job: refusals before any job (info for a skip), a fetch job, a normalize-only job", async () => { await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); const tw = await runFetchChatJob({ paths, slug: SLUG, videoId: "tw1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES }); diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts @@ -37,7 +37,9 @@ import { AUTH_RETRY_CLASSES, classifyDownloadFailure, parseUnavailableFromStderr, + refusalAvailability, } from "../lib/availability"; +import { recordFetchObservation } from "../lib/availability-server"; import type { ChannelConfig } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { @@ -190,6 +192,10 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC opts.onLog(`Fetching the live chat replay of ${opts.videoId} from ${opts.videoUrl} (no media)\n`); const firstCookies = alwaysCookies(policy); let outcome = await pass(firstCookies); + // A pass the platform refused for THIS video ("Join this channel …") is an + // observation, recorded even when the cookie retry below then succeeds: a + // members' cookie reading it is exactly what members-only means. + if (!succeeded(outcome.exitCode)) await noteRefusal(videoDir, outcome.stderrTail, opts.onLog); if (!succeeded(outcome.exitCode) && !opts.signal.aborted) { const cls = parseUnavailableFromStderr(outcome.stderrTail); const retryCookies = authRetryCookies(policy); @@ -201,6 +207,7 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC ) { opts.onLog(`The chat fetch needs a login (${cls}); retrying with --cookies-from-browser ${retryCookies}\n`); outcome = await pass(retryCookies); + if (!succeeded(outcome.exitCode)) await noteRefusal(videoDir, outcome.stderrTail, opts.onLog); } } if (opts.signal.aborted) throw new Error("Cancelled"); @@ -229,6 +236,19 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC return normalizeChat(opts, videoDir); } +// Best-effort: a failed write is logged, never the job's failure. +async function noteRefusal(videoDir: string, stderrTail: string, onLog: (s: string) => void): Promise<void> { + const seen = refusalAvailability(stderrTail); + if (!seen) return; + try { + if (await recordFetchObservation(videoDir, seen, new Date().toISOString())) { + onLog(`Recorded the source's answer for this video: ${seen} (availability.json)\n`); + } + } catch (err) { + onLog(`Could not record the availability (${seen}): ${(err as Error).message}\n`); + } +} + async function normalizeChat( opts: Pick<FetchLiveChatOpts, "slug" | "videoId" | "channelConfig" | "onLog">, videoDir: string, diff --git a/common/controller/refreshVideoMetadata.test.ts b/common/controller/refreshVideoMetadata.test.ts @@ -289,6 +289,94 @@ test("an auth-gated refresh retries once with cookies in when-required mode, nev } }); +test("a members-only refusal is recorded, once, even when the members' cookie retry then reads the video", async () => { + const f = await fixture({ meta: BEFORE }); + try { + await writeFile( + path.join(f.videoDir, "availability.json"), + JSON.stringify({ + checkedAt: "2026-01-02T03:00:00.000Z", + checkedBy: "backfill", + availability: "public", + history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], + }), + ); + const { run } = stubRunner([ + { exitCode: 1, stderr: `ERROR: [youtube] ${ID}: Join this channel to get access to members-only content like this video.` }, + { exitCode: 0, write: { ...AFTER, availability: "subscriber_only" } }, + ]); + const lines: string[] = []; + await refreshVideoMetadata({ + paths: f.paths, slug: SLUG, videoId: ID, videoUrl: URL, channelConfig: CONFIG, + cookiePolicy: { cookies: "firefox", mode: "when-required" }, + onLog: (s) => lines.push(s), signal: new AbortController().signal, run, paceSeconds: 1, + }); + const rec = JSON.parse(await readFile(path.join(f.videoDir, "availability.json"), "utf8")); + assert.equal(rec.availability, "members_only"); + assert.equal(rec.checkedBy, "fetch"); + assert.equal(rec.history.length, 2, "the refusal and the refreshed field agree: one entry"); + assert.match(lines.join(""), /Recorded the source's answer for this video: members_only/); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("a refresh writes availability only when the video's own field changes it", async () => { + const f = await fixture({ meta: BEFORE }); + try { + const checked = JSON.stringify({ + checkedAt: "2026-01-02T03:00:00.000Z", + checkedBy: "check", + availability: "public", + history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "check" }], + }); + await writeFile(path.join(f.videoDir, "availability.json"), checked); + const opts = { + paths: f.paths, slug: SLUG, videoId: ID, videoUrl: URL, channelConfig: CONFIG, + cookiePolicy: { cookies: undefined, mode: "when-required" } as ResolvedCookiePolicy, + onLog: () => {}, signal: new AbortController().signal, paceSeconds: 1, + }; + // Public again, and a record with no field at all: nothing written, the + // check stays a check. + await refreshVideoMetadata({ ...opts, run: stubRunner([{ exitCode: 0, write: { ...AFTER, availability: "public" } }]).run }); + await refreshVideoMetadata({ ...opts, run: stubRunner([{ exitCode: 0, write: AFTER }]).run }); + assert.equal(await readFile(path.join(f.videoDir, "availability.json"), "utf8"), checked); + // Made private: recorded as a fetch. + await refreshVideoMetadata({ ...opts, run: stubRunner([{ exitCode: 0, write: { ...AFTER, availability: "private" } }]).run }); + const rec = JSON.parse(await readFile(path.join(f.videoDir, "availability.json"), "utf8")); + assert.equal(rec.availability, "private"); + assert.equal(rec.checkedBy, "fetch"); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + +test("a removal is never recorded from a refresh's refusal: only the availability check establishes one", async () => { + const f = await fixture({ meta: BEFORE }); + try { + const before = JSON.stringify({ + checkedAt: "2026-01-02T03:00:00.000Z", + checkedBy: "backfill", + availability: "public", + history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], + }); + await writeFile(path.join(f.videoDir, "availability.json"), before); + const { run } = stubRunner([ + { exitCode: 1, stderr: `ERROR: [youtube] ${ID}: Video unavailable. This video has been removed by the uploader` }, + ]); + await assert.rejects( + refreshVideoMetadata({ + paths: f.paths, slug: SLUG, videoId: ID, videoUrl: URL, channelConfig: CONFIG, + cookiePolicy: { cookies: undefined, mode: "when-required" }, + onLog: () => {}, signal: new AbortController().signal, run, paceSeconds: 1, + }), + ); + assert.equal(await readFile(path.join(f.videoDir, "availability.json"), "utf8"), before); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); + test("a rate-limited refresh records the platform cooldown, rewrites nothing and fails", async () => { const f = await fixture({ meta: BEFORE }); try { diff --git a/common/controller/refreshVideoMetadata.ts b/common/controller/refreshVideoMetadata.ts @@ -48,9 +48,13 @@ import path from "node:path"; import { readFile, stat } from "node:fs/promises"; import { AUTH_RETRY_CLASSES, + availabilityFromJsonField, classifyDownloadFailure, parseUnavailableFromStderr, + refusalAvailability, + type Availability, } from "../lib/availability"; +import { recordFetchObservation } from "../lib/availability-server"; import type { ChannelConfig } from "../lib/channelConfig"; import { DEFAULT_COOKIE_MODE, @@ -445,6 +449,11 @@ export async function refreshVideoMetadata( const firstCookies = alwaysCookies(policy); let usedCookies = Boolean(firstCookies); let outcome = await pass(firstCookies); + // A pass the platform refused for THIS video is an observation (lane + // missing-source), recorded even when the cookie retry below succeeds. + if (!succeeded(outcome.exitCode)) { + await noteAvailability(videoDir, refusalAvailability(outcome.stderrTail), opts.onLog); + } // The prefetch's auth retry, verbatim in effect: once, with cookies, when // the failure is an auth/age gate, the mode allows it, and the failed pass @@ -464,6 +473,9 @@ export async function refreshVideoMetadata( ); usedCookies = true; outcome = await pass(retryCookies); + if (!succeeded(outcome.exitCode)) { + await noteAvailability(videoDir, refusalAvailability(outcome.stderrTail), opts.onLog); + } } } @@ -504,6 +516,13 @@ export async function refreshVideoMetadata( if (!isObject(meta)) { throw new Error(`${path.relative(channelDir, infoPath)} is not a JSON object`); } + // What the refreshed metadata itself says (a members' cookie reads + // `subscriber_only`), recorded only when the video's own field is there and + // differs from what the archive holds. + const field = (meta as { availability?: unknown }).availability; + if (typeof field === "string") { + await noteAvailability(videoDir, availabilityFromJsonField(field), opts.onLog); + } const summary = refreshSummaryLines({ videoId: opts.videoId, meta, @@ -513,3 +532,19 @@ export async function refreshVideoMetadata( opts.onLog(`${summary.join("\n")}\n`); return { meta, entries, usedCookies, summary }; } + +// Best-effort: a failed write is logged, never the job's failure. +async function noteAvailability( + videoDir: string, + seen: Availability | null, + onLog: (s: string) => void, +): Promise<void> { + if (!seen) return; + try { + if (await recordFetchObservation(videoDir, seen, new Date().toISOString())) { + onLog(`Recorded the source's answer for this video: ${seen} (availability.json)\n`); + } + } catch (err) { + onLog(`Could not record the availability (${seen}): ${(err as Error).message}\n`); + } +} diff --git a/common/lib/availability-server.test.ts b/common/lib/availability-server.test.ts @@ -0,0 +1,148 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + platformPresence, + recordAvailability, + recordFetchObservation, + resolveEffectiveAvailabilityObserved, +} from "./availability-server"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/availability-server.test.ts +// +// The fetch observation (lane missing-source) and the day a state was first +// seen. Every case is a temp video dir. + +async function dir(): Promise<string> { + return mkdtemp(path.join(tmpdir(), "avail-")); +} + +const PUBLIC_BACKFILL = { + checkedAt: "2026-01-02T03:00:00.000Z", + checkedBy: "backfill", + availability: "public", + history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], + webpageUrl: "https://www.youtube.com/watch?v=synthvid001", +}; + +test("a fetch observation over a backfilled 'public' moves the top level and keeps the page URL", async () => { + const d = await dir(); + try { + await writeFile(path.join(d, "availability.json"), JSON.stringify(PUBLIC_BACKFILL)); + assert.equal(await recordFetchObservation(d, "members_only", "2026-01-03T10:00:00.000Z"), true); + const rec = JSON.parse(await readFile(path.join(d, "availability.json"), "utf8")); + assert.equal(rec.availability, "members_only"); + assert.equal(rec.checkedBy, "fetch"); + assert.equal(rec.checkedAt, "2026-01-03T10:00:00.000Z"); + assert.equal(rec.webpageUrl, PUBLIC_BACKFILL.webpageUrl); + assert.equal(rec.history.length, 2); + // The same reading again writes nothing. + assert.equal(await recordFetchObservation(d, "members_only", "2026-01-04T10:00:00.000Z"), false); + assert.equal(JSON.parse(await readFile(path.join(d, "availability.json"), "utf8")).checkedAt, "2026-01-03T10:00:00.000Z"); + // A fetch never says a video is ON its platform. + const presence = await platformPresence(d, { maxAgeDays: 30, now: new Date("2026-01-03T12:00:00Z") }); + assert.equal(presence.onPlatform, false); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); + +test("a fetch that reads 'public' with no record writes nothing", async () => { + const d = await dir(); + try { + assert.equal(await recordFetchObservation(d, "public", "2026-01-03T10:00:00.000Z"), false); + await assert.rejects(readFile(path.join(d, "availability.json"), "utf8")); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); + +test("observed: the first entry of the trailing run; a day only a history entry anchors", async () => { + const d = await dir(); + try { + assert.equal(await resolveEffectiveAvailabilityObserved(d), null); + await writeFile( + path.join(d, "availability.json"), + JSON.stringify({ + checkedAt: "2026-01-09T00:00:00.000Z", + checkedBy: "check", + availability: "members_only", + history: [ + { availability: "public", observedAt: "2026-01-01T00:00:00.000Z", source: "backfill" }, + { availability: "members_only", observedAt: "2026-01-05T00:00:00.000Z", source: "fetch" }, + ], + }), + ); + assert.deepEqual(await resolveEffectiveAvailabilityObserved(d), { + availability: "members_only", + observedAt: "2026-01-05T00:00:00.000Z", + }); + // A legacy record (no history): its checkedAt is when it was last checked, + // not when it changed, so no day. + await writeFile( + path.join(d, "availability.json"), + JSON.stringify({ checkedAt: "2026-01-09T00:00:00.000Z", availability: "private" }), + ); + assert.deepEqual(await resolveEffectiveAvailabilityObserved(d), { + availability: "private", + observedAt: null, + }); + // A newer download outcome that found it removed wins; with no history + // entry agreeing, its finish (which moves with every attempt) is no day. + await writeFile( + path.join(d, "download-outcome.json"), + JSON.stringify({ + videoId: "synthvid001", + webpageUrl: "https://www.youtube.com/watch?v=synthvid001", + status: "failed", + startedAt: "2026-01-10T00:00:00.000Z", + finishedAt: "2026-01-10T00:01:00.000Z", + attempts: [{ n: 0, kind: "download", handling: "youtube", usedCookies: false, ytdlpExitCode: 1, availabilityClass: "deleted" }], + }), + ); + const got = await resolveEffectiveAvailabilityObserved(d); + assert.equal(got?.availability, "deleted"); + assert.equal(got?.observedAt, null); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); + +test("a legacy record's first write seeds its history, so a same-value recheck never moves the day", async () => { + const d = await dir(); + try { + // Removed long ago, recorded before history existed. + await writeFile( + path.join(d, "availability.json"), + JSON.stringify({ checkedAt: "2023-04-02T00:00:00.000Z", checkedBy: "check", availability: "deleted", history: [] }), + ); + assert.equal((await resolveEffectiveAvailabilityObserved(d))?.observedAt, null); + await recordAvailability(d, { availability: "deleted", observedAt: "2026-11-19T00:00:00.000Z", source: "check" }); + const rec = JSON.parse(await readFile(path.join(d, "availability.json"), "utf8")); + assert.equal(rec.checkedAt, "2026-11-19T00:00:00.000Z"); + assert.deepEqual(rec.history, [{ availability: "deleted", observedAt: "2023-04-02T00:00:00.000Z", source: "check" }]); + assert.equal((await resolveEffectiveAvailabilityObserved(d))?.observedAt, "2023-04-02T00:00:00.000Z"); + // And again: the day stays where it was. + await recordAvailability(d, { availability: "deleted", observedAt: "2026-11-20T00:00:00.000Z", source: "check" }); + assert.equal((await resolveEffectiveAvailabilityObserved(d))?.observedAt, "2023-04-02T00:00:00.000Z"); + + // A legacy record with no checkedBy, then a change: the old reading is kept + // ahead of the new one, as the weakest claim ("backfill"). + await writeFile( + path.join(d, "availability.json"), + JSON.stringify({ checkedAt: "2026-01-02T00:00:00.000Z", availability: "public" }), + ); + await recordAvailability(d, { availability: "members_only", observedAt: "2026-01-05T00:00:00.000Z", source: "fetch" }); + const moved = JSON.parse(await readFile(path.join(d, "availability.json"), "utf8")); + assert.deepEqual(moved.history, [ + { availability: "public", observedAt: "2026-01-02T00:00:00.000Z", source: "backfill" }, + { availability: "members_only", observedAt: "2026-01-05T00:00:00.000Z", source: "fetch" }, + ]); + assert.equal((await resolveEffectiveAvailabilityObserved(d))?.observedAt, "2026-01-05T00:00:00.000Z"); + } finally { + await rm(d, { recursive: true, force: true }); + } +}); diff --git a/common/lib/availability-server.ts b/common/lib/availability-server.ts @@ -62,6 +62,21 @@ export async function recordAvailability( const changed = lastAvail !== obs.availability; const history: AvailabilityHistoryEntry[] = [...(existing?.history ?? [])]; + // A LEGACY RECORD (written before history existed, or by a path that left it + // empty) is seeded on its first write from its own top level — the reading + // and the checkedAt it was made at — before the new observation is applied. + // Without it a same-value recheck appended nothing and only moved checkedAt, + // so a day derived from it slid forward on every recheck (a video removed in + // 2023 read "first seen" today). With it the first-seen day is fixed from + // then on. A record that never said who wrote it is seeded as "backfill", the + // weakest claim. + if (existing && history.length === 0) { + history.push({ + availability: existing.availability, + observedAt: existing.checkedAt, + source: existing.checkedBy ?? "backfill", + }); + } if (changed) { history.push({ availability: obs.availability, @@ -127,6 +142,77 @@ export async function resolveEffectiveAvailability( return outcome?.availability ?? null; } +// The effective availability (as resolveEffectiveAvailability) AND the instant +// the archive first observed it — the start of the trailing run of history +// entries that agree with it. ONLY a history entry dates it: a record's +// checkedAt is when it was last checked and an outcome's finishedAt when it was +// last attempted, and both move with every recheck, so a state with no +// history entry behind it has `observedAt: null` and the site publishes no day +// for it (we do not know when it changed). The published `stateSince` is this +// instant's day (buildIndex). +export async function resolveEffectiveAvailabilityObserved( + videoDir: string, +): Promise<{ availability: Availability; observedAt: string | null } | null> { + const [explicit, outcome] = await Promise.all([ + loadAvailability(videoDir), + loadDownloadOutcomeAvailability(videoDir), + ]); + const fromOutcome = + outcome && + (!explicit || + (outcome.finishedAt !== null && + new Date(outcome.finishedAt) > new Date(explicit.checkedAt))); + if (fromOutcome && outcome) { + // A download's class also appends a history entry (downloadOneManaged), so + // the history dates it when it agrees; else no day. + const since = explicit ? firstOfTrailingRun(explicit, outcome.availability) : null; + return { availability: outcome.availability, observedAt: since }; + } + if (!explicit) return null; + return { + availability: explicit.availability, + observedAt: firstOfTrailingRun(explicit, explicit.availability), + }; +} + +function firstOfTrailingRun(record: AvailabilityRecord, availability: Availability): string | null { + const history = record.history ?? []; + let since: string | null = null; + for (let i = history.length - 1; i >= 0; i--) { + if (history[i].availability !== availability) break; + since = history[i].observedAt; + } + return since; +} + +// RECORD WHAT A FETCH OF ONE VIDEO WAS TOLD (lane missing-source): the chat +// replay pass and the metadata refresh hear the platform answer for this one +// video — "Join this channel to get access to members-only content", or a +// refreshed metadata.info.json whose own field says subscriber_only — and that +// is an observation. Written, as source "fetch" over the top-level fields, ONLY +// when it differs from the effective availability, so a repeated refusal or an +// unchanged refresh rewrites nothing (and never turns a fresh "check" into a +// "fetch"). Returns whether it wrote. +export async function recordFetchObservation( + videoDir: string, + availability: Availability, + observedAt: string, +): Promise<boolean> { + const effective = await resolveEffectiveAvailability(videoDir).catch(() => null); + if (effective === availability) return false; + // A fetch that read "public" over NO record says nothing worth writing: the + // backfill or a check owns a first record. + if (effective === null && availability === "public") return false; + const existing = await loadAvailability(videoDir); + await recordAvailability(videoDir, { + availability, + observedAt, + source: "fetch", + ...(existing?.webpageUrl ? { webpageUrl: existing.webpageUrl } : {}), + }); + return true; +} + // Decide the VideoState for one video that the last quick availability check // found absent from its channel's fresh playlist listing. `scannedAtMs` is that // check's `checkedAt`. Three outcomes, and both of the non-obvious ones earn diff --git a/common/lib/availability.test.ts b/common/lib/availability.test.ts @@ -215,3 +215,35 @@ test("a subtitle 429 beside another subtitle failure classes as the OTHER failur "rate_limit", ); }); + +test("refusalAvailability: only members-only and private count, never a removal", async () => { + const { refusalAvailability } = await import("./availability"); + assert.equal( + refusalAvailability("ERROR: [youtube] abc: Join this channel to get access to members-only content like this video."), + "members_only", + ); + assert.equal(refusalAvailability("ERROR: [youtube] abc: Private video. Sign in if you've been granted access"), "private"); + for (const nothing of [ + // A removal is never taken from a fetch's refusal: its wording matches + // loosely, and only the availability check job establishes one. + "ERROR: [youtube] abc: Video unavailable. This video has been removed by the uploader", + "ERROR: [youtube] abc: Video unavailable", + "ERROR: [youtube] abc: HTTP Error 429: Too Many Requests", + "ERROR: [youtube] abc: This content isn't available, try again later. The current session has been rate-limited", + "ERROR: [youtube] abc: Sign in to confirm you're not a bot", + "ERROR: [youtube] abc: Sign in to confirm your age", + "ERROR: unable to download webpage: <urlopen error [Errno 111] ECONNREFUSED>", + "ERROR: something nobody has seen before", + ]) { + assert.equal(refusalAvailability(nothing), null, nothing); + } +}); + +test("isNotPublicState: members-only, private and deleted; never unlisted or a suspicion", async () => { + const { isNotPublicState } = await import("./availability"); + assert.deepEqual( + (["available", "maybe_missing", "unlisted", "private", "members_only", "deleted"] as const).filter((s) => isNotPublicState(s)), + ["private", "members_only", "deleted"], + ); + assert.equal(isNotPublicState(undefined), false); +}); diff --git a/common/lib/availability.ts b/common/lib/availability.ts @@ -68,6 +68,22 @@ export type VideoState = | "members_only" | "deleted"; +// NO LONGER PUBLIC AT ITS PLATFORM (lane missing-source): the states in which a +// visitor cannot watch the source there, so the export site mounts no player +// for it and says so. Unlisted still plays by direct link and "maybe missing" is +// a suspicion, so neither is here. NOT the same reading as lib/sourceGone.ts's +// goneState (deleted / private), which reports use and which by its own ruling +// does not count members-only as gone: a member's cookies fetch it. +export const NOT_PUBLIC_STATES: ReadonlyArray<VideoState> = [ + "members_only", + "private", + "deleted", +]; + +export function isNotPublicState(s: VideoState | null | undefined): boolean { + return s != null && NOT_PUBLIC_STATES.includes(s); +} + // Ordered for UI: the umbrella's leaves in the order they're offered. export const MISSING_STATES: ReadonlyArray<VideoState> = [ "maybe_missing", @@ -136,7 +152,17 @@ export const VIDEO_STATE_LABELS: Record<VideoState, string> = { unlisted: "Unlisted", }; -export type AvailabilityHistorySource = "check" | "backfill" | "download"; +// WHO OBSERVED IT. "check" is a real probe of the platform (the channel page's +// Diagnostics → Check availability); "backfill" an assumption copied from a +// video's metadata.info.json when it first lands; "download" a download +// attempt's class (history only — the class itself is in download-outcome.json). +// "fetch" (lane missing-source) is a one-video fetch — the chat replay pass, a +// metadata refresh — that the platform answered with a per-video reason +// ("Join this channel …"), or a refresh that read the video's own field. It is +// first-hand, but it is NOT a "check": platformPresence trusts only a check to +// say a video is still ON its platform, so a fetch can never make compaction +// treat a source as present. +export type AvailabilityHistorySource = "check" | "backfill" | "download" | "fetch"; export type AvailabilityHistoryEntry = { availability: Availability; @@ -371,6 +397,22 @@ export function classifyDownloadFailure( return "unknown"; } +// WHAT A REFUSED FETCH OF ONE VIDEO SAYS ABOUT IT, or null when it says +// nothing (lane missing-source). Only members-only and private count: the +// platform names them for this one video in words nothing else uses. A REMOVAL +// IS NEVER TAKEN FROM A FETCH: the "deleted" group matches loosely (a bare +// "Video unavailable" is also how a region block or a transient answer reads), +// and the site would then publish "removed" on it — a removal is established +// only by the availability check job (checkAvailability.ts). A rate limit, the +// soft block, the bot check, a network failure or an unclassified error never +// saw the video; an age gate (needs_auth) is the video answering, and a login +// retry may still read it. +export function refusalAvailability(stderrTail: string): Availability | null { + const cls = parseUnavailableFromStderr(stderrTail); + if (classifyDownloadFailure(stderrTail, cls) !== "per_video") return null; + return cls === "members_only" || cls === "private" ? cls : null; +} + // Map the `availability` field that yt-dlp puts in --dump-json output to our // enum. yt-dlp uses: public, unlisted, needs_auth, premium_only, subscriber_only, // public_unlisted (rare), private, etc. diff --git a/common/lib/corpus.ts b/common/lib/corpus.ts @@ -52,6 +52,11 @@ import { // older archive falls back to a shard record's `webpageUrl` / `platform` // (common/lib/remoteArchives-server.ts channelFactsOf). // +// NOT a v7: `state` / `stateSince` on a transcript shard record and +// `stateSince` on a summary (lane missing-source) are per-record keys, additive, +// documented in SHARD_SCHEME below — an older reader ignores them, as it always +// has, and no new document can be fetched. +// // NOT a v4: the `generator` field added below is deliberately unversioned. Every // prior bump announced a new FETCHABLE LAYER — a reader that ignored it would // miss data it could otherwise have retrieved. `generator` is an informational @@ -93,11 +98,16 @@ const SHARD_SCHEME = { "duration, channel, description, tags, webpageUrl, platform, cues: [{ start, end, text }] }; " + "a record with other English caption tracks whose words differ from its transcript " + "also carries `track` (the transcript's track id, e.g. \"en-orig\") and " + - "`altTracks: [{ track, cues }]` (e.g. \"en\", the uploaded captions) — absent otherwise", + "`altTracks: [{ track, cues }]` (e.g. \"en\", the uploaded captions) — absent otherwise; " + + "a record whose source is no longer as it was at its platform carries `state` " + + "(\"members_only\", \"private\", \"deleted\" or \"unlisted\") and `stateSince` " + + "(YYYYMMDD, the day the archive first saw it) — absent for a video still public there", subsManifest: "<channel.manifests.subs> -> lighter list-view records under the same slugToPage scheme", summariesIndex: - "/summaries/manifest.json + /summaries/page-<NNNN>.json -> cross-channel browse index", + "/summaries/manifest.json + /summaries/page-<NNNN>.json -> cross-channel browse index; " + + "a record carries `state` (also \"maybe_missing\": gone from its channel's listing, " + + "unconfirmed) and, for a confirmed state, `stateSince` — both absent when available", pageNumberFormat: "zero-padded to 4 digits, e.g. page 0 -> page-0000.json", } as const; diff --git a/common/lib/localFileClock.test.ts b/common/lib/localFileClock.test.ts @@ -0,0 +1,72 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + OFFSET_LIMIT_SECONDS, + formatOffset, + nudgeOffset, + offsetFromSync, + offsetKey, + readOffset, + toCueTime, + toFileTime, + writeOffset, +} from "./localFileClock"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/localFileClock.test.ts + +function memoryStore() { + const m = new Map<string, string>(); + return { + m, + getItem: (k: string) => m.get(k) ?? null, + setItem: (k: string, v: string) => void m.set(k, v), + removeItem: (k: string) => void m.delete(k), + }; +} + +test("the two clocks round-trip through the offset, and never go below 0", () => { + assert.equal(toFileTime(10, 2.5), 12.5); + assert.equal(toCueTime(12.5, 2.5), 10); + assert.equal(toFileTime(1, -3), 0); + assert.equal(toCueTime(1, 3), 0); + for (const off of [-7.25, 0, 0.1, 42]) assert.equal(toCueTime(toFileTime(100, off), off), 100); +}); + +test("nudge and sync round to centiseconds and stay in range", () => { + assert.equal(nudgeOffset(0, 0.1), 0.1); + assert.equal(nudgeOffset(0.1, 0.1), 0.2); + assert.equal(nudgeOffset(0.2, -1), -0.8); + assert.equal(nudgeOffset(OFFSET_LIMIT_SECONDS, 1), OFFSET_LIMIT_SECONDS); + // The line that starts at 30 s is what the file plays at 32.346 s. + assert.equal(offsetFromSync(32.346, 30), 2.35); + assert.equal(offsetFromSync(5, 30), -25); +}); + +test("the offset display", () => { + assert.equal(formatOffset(0), "0.00 s"); + assert.equal(formatOffset(1.5), "+1.50 s"); + assert.equal(formatOffset(-0.1), "−0.10 s"); +}); + +test("storage holds only a number under the video's key; junk and refusals read as 0", () => { + const s = memoryStore(); + assert.equal(readOffset(s, "chan/vid"), 0); + writeOffset(s, "chan/vid", 2.345); + assert.deepEqual([...s.m.entries()], [[offsetKey("chan/vid"), "2.35"]]); + assert.equal(readOffset(s, "chan/vid"), 2.35); + writeOffset(s, "chan/vid", 0); + assert.equal(s.m.size, 0, "0 removes the key"); + s.m.set(offsetKey("chan/vid"), "not a number"); + assert.equal(readOffset(s, "chan/vid"), 0); + s.m.set(offsetKey("chan/vid"), String(OFFSET_LIMIT_SECONDS * 2)); + assert.equal(readOffset(s, "chan/vid"), 0); + const refusing = { + getItem: () => { throw new Error("SecurityError"); }, + setItem: () => { throw new Error("QuotaExceededError"); }, + removeItem: () => { throw new Error("SecurityError"); }, + }; + assert.equal(readOffset(refusing, "chan/vid"), 0); + writeOffset(refusing, "chan/vid", 1); + assert.equal(readOffset(null, "chan/vid"), 0); +}); diff --git a/common/lib/localFileClock.ts b/common/lib/localFileClock.ts @@ -0,0 +1,76 @@ +// A VISITOR'S OWN COPY ON THE TRANSCRIPT'S CLOCK (lane missing-source, slice 2). +// +// The export site can play a local file the visitor picks — from an object URL, +// in the page, never uploaded — with the transcript following it. Their copy +// may start earlier or later than the cues' clock, so everything the page does +// (follow, click-to-seek, clip marks, Share's t=) stays on the CUE clock and the +// file is reached through one offset: +// +// fileTime = cueTime + offset cueTime = fileTime - offset +// +// A positive offset: the transcript's 0:00 is that far into the file (the copy +// has a lead-in). The offset is the ONLY thing ever stored, per video, in +// localStorage — never the file's name, size or anything else about it. +// +// Pure: client-safe, no node: imports, no I/O but the Storage handed in. + +export const OFFSET_LIMIT_SECONDS = 24 * 3600; +export const OFFSET_KEY_PREFIX = "archilyzer:local-offset:"; + +const round = (v: number) => Math.round(v * 100) / 100; +const clampOffset = (v: number) => Math.max(-OFFSET_LIMIT_SECONDS, Math.min(OFFSET_LIMIT_SECONDS, round(v))); + +export function toFileTime(cueTime: number, offset: number): number { + return Math.max(0, cueTime + offset); +} + +export function toCueTime(fileTime: number, offset: number): number { + return Math.max(0, fileTime - offset); +} + +export function nudgeOffset(offset: number, delta: number): number { + return clampOffset(offset + delta); +} + +// "This line is playing now": the line that starts at `cueStart` is what the +// file plays at `fileTime`. +export function offsetFromSync(fileTime: number, cueStart: number): number { + return clampOffset(fileTime - cueStart); +} + +export function formatOffset(offset: number): string { + const v = round(offset); + if (v === 0) return "0.00 s"; + return `${v > 0 ? "+" : "−"}${Math.abs(v).toFixed(2)} s`; +} + +export function offsetKey(slug: string): string { + return `${OFFSET_KEY_PREFIX}${slug}`; +} + +type OffsetStore = Pick<Storage, "getItem" | "setItem" | "removeItem">; + +// A stored offset, or 0 when there is none, it is not a finite number in range, +// or storage is unavailable (a private window, blocked site data). +export function readOffset(store: OffsetStore | null | undefined, slug: string): number { + try { + const raw = store?.getItem(offsetKey(slug)); + if (raw == null) return 0; + const v = Number(raw); + if (!Number.isFinite(v) || Math.abs(v) > OFFSET_LIMIT_SECONDS) return 0; + return round(v); + } catch { + return 0; + } +} + +// 0 removes the key: nothing is kept for a copy that needs no offset. +export function writeOffset(store: OffsetStore | null | undefined, slug: string, offset: number): void { + try { + const v = clampOffset(offset); + if (v === 0) store?.removeItem(offsetKey(slug)); + else store?.setItem(offsetKey(slug), String(v)); + } catch { + /* storage refused: the offset lives for this page only */ + } +} diff --git a/common/lib/sourceMissing.test.ts b/common/lib/sourceMissing.test.ts @@ -0,0 +1,47 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + formatStateDay, + sourceLinkLabel, + sourceMissingSentence, + stateSinceTitle, +} from "./sourceMissing"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/sourceMissing.test.ts + +test("the sentence names the state and the day it was first seen, and nothing else", () => { + assert.equal( + sourceMissingSentence({ state: "members_only", stateSince: "20261119", platform: "youtube", isLivestream: true }), + "This stream is no longer public on YouTube (members-only; first seen 19 Nov 2026). The transcript is kept here.", + ); + assert.equal( + sourceMissingSentence({ state: "private", stateSince: "20260301", platform: "rumble" }), + "This video is no longer public on Rumble (private; first seen 1 Mar 2026). The transcript is kept here.", + ); + assert.equal( + sourceMissingSentence({ state: "deleted", stateSince: "20251231", platform: "youtube" }), + "This video is no longer public on YouTube (removed; first seen 31 Dec 2025). The transcript is kept here.", + ); + // No day: the state alone. + assert.equal( + sourceMissingSentence({ state: "deleted", platform: "odysee" }), + "This video is no longer public on Odysee (removed). The transcript is kept here.", + ); +}); + +test("states that keep their player get no sentence", () => { + for (const state of ["available", "unlisted", "maybe_missing", undefined] as const) { + assert.equal(sourceMissingSentence({ state, platform: "youtube" }), null, String(state)); + } +}); + +test("the marked link, the badge title, the day format", () => { + assert.equal(sourceLinkLabel("youtube", "members_only"), "Open on YouTube (members-only)"); + assert.equal(sourceLinkLabel("twitch", "deleted"), "Open on Twitch (removed)"); + assert.equal(sourceLinkLabel(undefined, "private"), "Open on its platform (private)"); + assert.equal(stateSinceTitle("Members-only on the source platform", "20261119"), "Members-only on the source platform; first seen 19 Nov 2026"); + assert.equal(stateSinceTitle("Deleted", undefined), "Deleted"); + assert.equal(formatStateDay("2026-11-19"), null); + assert.equal(formatStateDay("20261319"), null); +}); diff --git a/common/lib/sourceMissing.ts b/common/lib/sourceMissing.ts @@ -0,0 +1,84 @@ +// WHAT THE SITE SAYS WHEN A SOURCE IS NO LONGER PUBLIC (lane missing-source). +// +// A video whose state is members-only, private or deleted at its platform +// (availability.ts NOT_PUBLIC_STATES) gets no player on the export site: a +// sentence in its place, the platform link kept but marked, and the transcript +// as for any video. The sentence names the state and the day the archive first +// saw it (`stateSince`) and nothing else — never who observed it or how. It +// says "first seen", never "since": the archive knows when it first saw the +// state, not when the platform changed it. +// +// Pure: client-safe, no node: imports. + +import { isNotPublicState, type VideoState } from "./availability"; + +// A platform's name as a person writes it. Kept here rather than imported from +// the report modules so the client bundle does not pull them in. +const PLATFORM_NAMES: Readonly<Record<string, string>> = { + youtube: "YouTube", + rumble: "Rumble", + odysee: "Odysee", + twitch: "Twitch", + kick: "Kick", + archiveorg: "archive.org", + bitchute: "BitChute", +}; + +export function sourcePlatformName(platform: string | null | undefined): string { + return (platform && PLATFORM_NAMES[platform]) || "its platform"; +} + +// The state as the sentence says it. +const STATE_WORDS: Readonly<Record<string, string>> = { + members_only: "members-only", + private: "private", + deleted: "removed", +}; + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +// "20261119" -> "19 Nov 2026"; anything else -> null. +export function formatStateDay(yyyymmdd: string | null | undefined): string | null { + if (!yyyymmdd || !/^\d{8}$/.test(yyyymmdd)) return null; + const m = Number(yyyymmdd.slice(4, 6)); + const d = Number(yyyymmdd.slice(6, 8)); + if (m < 1 || m > 12 || d < 1 || d > 31) return null; + return `${d} ${MONTHS[m - 1]} ${yyyymmdd.slice(0, 4)}`; +} + +export type SourceGone = { + state: VideoState; + stateSince?: string; +}; + +// The one sentence: "This stream is no longer public on YouTube (members-only; +// first seen 19 Nov 2026). The transcript is kept here." With no day (a state +// whose first sighting is not on record), the parenthesis is the state alone. +// Null for a state that keeps its player. +export function sourceMissingSentence(o: { + state: VideoState | null | undefined; + stateSince?: string | null; + platform: string | null | undefined; + isLivestream?: boolean; +}): string | null { + if (!isNotPublicState(o.state)) return null; + const what = o.isLivestream ? "stream" : "video"; + const word = STATE_WORDS[o.state as string]; + const day = formatStateDay(o.stateSince); + const paren = day ? `${word}; first seen ${day}` : word; + return `This ${what} is no longer public on ${sourcePlatformName(o.platform)} (${paren}). The transcript is kept here.`; +} + +// The platform link, kept but marked: "Open on YouTube (members-only)". +export function sourceLinkLabel(platform: string | null | undefined, state: VideoState): string { + const word = STATE_WORDS[state]; + const name = sourcePlatformName(platform); + return word ? `Open on ${name} (${word})` : `Open on ${name}`; +} + +// The badge tooltip's day: "Members-only on the source platform; first seen +// 19 Nov 2026". +export function stateSinceTitle(base: string, stateSince: string | null | undefined): string { + const day = formatStateDay(stateSince); + return day ? `${base}; first seen ${day}` : base; +} diff --git a/common/lib/transcripts-server.ts b/common/lib/transcripts-server.ts @@ -279,7 +279,7 @@ export function summarizeStats( export function toDisplaySummary( t: TranscriptSummary, - extras: { state?: VideoState } = {}, + extras: { state?: VideoState; stateSince?: string } = {}, ): DisplaySummary { const state = extras.state ?? "available"; return { @@ -303,6 +303,8 @@ export function toDisplaySummary( // (writeJsonAtomic), so the beneficiaries are the subs page hashes in // createPageWriter and the compose-site dirSignature reconcile. ...(state === "available" ? {} : { state }), + // The day it was first seen, only beside a state (lane missing-source). + ...(state !== "available" && extras.stateSince ? { stateSince: extras.stateSince } : {}), platform: t.platform, webpageUrl: t.webpageUrl, // Curated tags ride through to the browse index, so a list can be narrowed diff --git a/common/lib/transcripts.ts b/common/lib/transcripts.ts @@ -73,6 +73,11 @@ export type DisplaySummary = { // available), so a page with no missing videos stays byte-identical to the // one already on disk and the build's downstream hashing still short-circuits. state?: VideoState; + // THE DAY THE ARCHIVE FIRST SAW `state` (YYYYMMDD, the shape of uploadDate) — + // lane missing-source. Present only beside a confirmed state the archive can + // date; absent for "available" and for an unconfirmed "maybe missing". A day, + // never who saw it or how. + stateSince?: string; platform: Platform; webpageUrl: string; // Curated tag ids (common/lib/curatedTags.ts) — the operator's cross-channel @@ -85,8 +90,16 @@ export type DisplaySummary = { // `track` / `altTracks` (lib/captionTracks.ts): the primary's track id and the // other English tracks whose words differ from it — present only on a record // that has such a track. +// +// `state` / `stateSince` (lane missing-source): the record's source is no +// longer as it was at its platform — members-only, private, deleted or +// unlisted — and the day the archive first saw it. Present ONLY on such a +// record (a confirmed state; "maybe missing" stays a summaries-only suspicion), +// so every other record's page bytes are what they were. export type TranscriptDetail = TranscriptSummary & { cues: Cue[] | undefined; + state?: Exclude<VideoState, "available" | "maybe_missing">; + stateSince?: string; } & TrackFields; export type TranscriptPage = TranscriptDetail[]; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,25 @@ # Changelog ## [Unreleased] +- **A fetch the platform refused for one video now records why.** + - The chat replay pass (`fetch-chat`, the chat backlog, find-clips) and `refresh-metadata` used to drop a refusal + such as "Join this channel to get access to members-only content". A stream backfilled "public" while it was + live kept reading public after it went members-only. + - Both now record members-only or private in the video's `availability.json` as source `fetch`. A refresh also + records the video's own metadata field when it changes the reading. + - A removal is never taken from a fetch's refusal (its wording matches too loosely): only the channel's Check + availability records one. + - Written only when the reading changes, and never for a rate limit, the soft block, the bot check or an age gate. + - A `fetch` is not a `check`: compaction still trusts only a real check to say a source is on its platform. + - To recheck one video: `pnpm ops refresh-metadata {"slug","id"}` (one paced request on the platform's queue). +- **The index publishes when a state was first seen.** + - A transcript record whose source is members-only, private, deleted or unlisted carries `state` and + `stateSince` (YYYYMMDD). Summaries carry `stateSince` beside `state`. + - The day is the first history entry of the current state. A record written before history existed has no such + entry and publishes no day; its first rewrite seeds the history from the reading it held, so a same-value + recheck never moves the day forward. + - The first index build after this re-reads only the records with such a state and no day yet, once each: a + record with no day to find is settled, even while a channel is held. - **X jobs run on X's queue only, under a cap no setting can raise.** - A job that asks X is refused on any queue but `platform:twitter`, when it is queued and where it runs: a posts fetch in any mode, a resumed backfill, a Sync, a capture, a trending read, an import of an X post, an diff --git a/export/CHANGELOG.md b/export/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## [Unreleased] +- **A video whose source is no longer public says so, with the day, and mounts no dead player.** + - A members-only, private or removed video gets one sentence in the player's place, e.g. "This stream is no + longer public on YouTube (members-only; first seen 19 Nov 2026). The transcript is kept here." The day is + when the archive first saw the state, not when the platform changed it; a state the archive has no first + sighting of on record shows no day ("(removed)"). + - The platform link is kept but marked ("Open on YouTube (members-only)"), or shown as plain text when the + record has no address. No embed is loaded and nothing is asked of the platform. + - The transcript, a cue click, the clip marks and Share work as for any video. Unlisted and "Missing?" videos + keep their player. + - A search card's state badge shows the day in its tooltip ("…; first seen 19 Nov 2026"). + - The state is read from the fresh summaries first, so a video's transcript cached in the browser from an earlier + visit no longer hides a later change. The browser's transcript cache is cleared once for it. + - Until the summaries have answered, no platform player is mounted: the player slot stays black, so a cached + record of a video since made members-only never asks the platform. A page that loads no summaries (Duplicates) + goes by the record. + - `corpus.json` documents the record keys `state` and `stateSince` (YYYYMMDD). They are per-record and additive, + so it stays spec 6. +- **Play your own copy.** + - On any video page a visitor can pick a video or audio file they have. It plays in the page from the browser's + own copy, the transcript follows it, and a click on a line seeks it. + - The control sits in the "no longer public" panel when the source is gone, and is a plain **Play your own copy** + control otherwise. Beside it: "Your file stays in this browser: nothing is uploaded." + - Picking a file makes no network request, and only the sync offset is remembered (per video, in this browser). + - The offset can be nudged by −1, −0.1, +0.1 or +1 s, or set with **This line is playing now** and a click on + the line you hear (Esc cancels). **Stop** puts the panel or the platform player back, and the focus on + **Play your own copy**. + ## [0.11.3] - 2026-11-18 - **A site's secondary tags sit under More filters, and a site with many channels can find one.** A curated tag the operator marked secondary is still published, still filters and still rides on `?tg=` links, but its chips sit in a **More filters** disclosure above Advanced options instead of the main Tags row, its group's name beside them. It is closed by default and opens on its own when a link or a saved profile selects one of its tags; once you open or close it, it stays as you left it, and its summary says how many of its tags are selected. On a site with more than 12 channels, a small magnifier beside **Channels** opens a field that narrows the groups as you type to the channels whose name or slug holds the text (case, accents and punctuation ignored), or to a whole group whose name does. Esc clears it and gives the panel back as it was; in the phone sheet the first Esc clears the field and the next closes the sheet. A site with no secondary tag and 12 channels or fewer looks as it did. Needs a rebuild and deploy of each site. - **`corpus.json` is spec 6: each channel says where it is.** A channel's entry adds `platform` (youtube, rumble, …) and `url`, its page on that platform, when the archive's operator configured them, and `llms.txt` shows them beside the channel's name — what a machine with no copy of the channel needs to fetch a cited moment's media (a fresh Archilyzer clone pointed at the archive). Additive: a reader that does not know spec 6 reads the archive as before, and a reader of an older archive takes the platform from a transcript record's `webpageUrl`. Needs a rebuild and deploy of each site. diff --git a/export/e2e/fixtures/missing-source.ts b/export/e2e/fixtures/missing-source.ts @@ -0,0 +1,157 @@ +import type { Page, Route } from "@playwright/test"; + +// SOURCES NO LONGER PUBLIC (lane missing-source): one invented channel with a +// video per state, served entirely by route mocks. Every name, id and address +// here is made up. `record` overrides let a case make the transcript record and +// the summaries disagree (an IndexedDB copy from before the state changed). + +export const CHANNEL = "Synth Channel"; +export const CHANNEL_SLUG = "synth-channel"; + +export type Vid = { + id: string; + title: string; + state?: "members_only" | "private" | "deleted" | "unlisted" | "maybe_missing"; + stateSince?: string; + isLivestream?: boolean; + // What the transcript record says, when it differs from the summary. + record?: { state?: string; stateSince?: string }; + // A record with no platform address at all. + noUrl?: boolean; +}; + +export const VIDS: Vid[] = [ + { id: "synthpub001", title: "Synth public talk" }, + { id: "synthmem001", title: "Synth members stream", state: "members_only", stateSince: "20261119", isLivestream: true }, + { id: "synthpri001", title: "Synth private talk", state: "private" }, + { id: "synthdel001", title: "Synth removed talk", state: "deleted", stateSince: "20251231" }, + { id: "synthunl001", title: "Synth unlisted talk", state: "unlisted", stateSince: "20260102" }, + // The summaries say members-only; a stale record says nothing. + { id: "synthstl001", title: "Synth stale record", state: "members_only", stateSince: "20261001", record: {} }, + // The summaries say public again; a stale record still says removed. + { id: "synthbak001", title: "Synth back again", record: { state: "deleted", stateSince: "20250101" } }, + // Removed, and no address to link to. + { id: "synthnou001", title: "Synth no address", state: "deleted", noUrl: true }, +]; + +export const CUES = [ + { start: 0, end: 2, text: "first synth line" }, + { start: 2, end: 3, text: "second synth line" }, + { start: 3, end: 5, text: "third synth line" }, + { start: 5, end: 6, text: "fourth synth line" }, +]; + +export const slugOf = (id: string) => `${CHANNEL_SLUG}/${id}`; +export const watchUrl = (id: string) => `https://www.youtube.com/watch?v=${id}`; + +function summary(v: Vid) { + return { + slug: slugOf(v.id), + id: v.id, + channelSlug: CHANNEL_SLUG, + title: v.title, + uploadDate: "20260101", + date: "2026-01-01", + duration: "0:06", + channel: CHANNEL, + isLivestream: v.isLivestream === true, + ageRestricted: false, + isDeleted: v.state === "deleted", + isUnlisted: v.state === "unlisted", + ...(v.state ? { state: v.state } : {}), + ...(v.state && v.stateSince ? { stateSince: v.stateSince } : {}), + platform: "youtube" as const, + webpageUrl: v.noUrl ? "" : watchUrl(v.id), + }; +} + +function record(v: Vid) { + const base = summary(v); + const { state: _s, stateSince: _d, isDeleted: _i, isUnlisted: _u, date: _dt, ...rest } = base as Record<string, unknown>; + const st = v.record ? v.record.state : v.state === "maybe_missing" ? undefined : v.state; + const since = v.record ? v.record.stateSince : v.stateSince; + return { + ...rest, + duration: 6, + description: "", + tags: [], + ...(st ? { state: st } : {}), + ...(st && since ? { stateSince: since } : {}), + cues: CUES, + }; +} + +async function fulfillJson(route: Route, body: unknown) { + await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(body) }); +} + +// Every archive path the workspace asks for, mocked; every request to a video +// platform recorded and aborted (`platformHits`). `summariesDelayMs` holds the +// summaries pages back, so the transcript record lands first (a returning +// visitor's cached record against a slow network). +export async function installMissingSourceRoutes( + page: Page, + opts: { summariesDelayMs?: number } = {}, +): Promise<{ platformHits: string[] }> { + const platformHits: string[] = []; + await page.route(/youtube\.com|youtube-nocookie\.com|ytimg\.com|googlevideo\.com/, async (route) => { + platformHits.push(route.request().url()); + await route.abort(); + }); + const list = VIDS.map(summary); + await page.route("**/summaries/manifest.json", (route) => + fulfillJson(route, { + version: 3, + totalCount: list.length, + pageSize: 1000, + pageCount: 1, + generatedAt: new Date().toISOString(), + channels: [{ name: CHANNEL, count: list.length, groupId: "default" }], + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", + }), + ); + await page.route("**/summaries/page-*.json", async (route) => { + if (opts.summariesDelayMs) await new Promise((r) => setTimeout(r, opts.summariesDelayMs)); + await fulfillJson(route, list); + }); + await page.route(/\/transcripts\/[^/]+\/manifest\.json$/, (route) => + fulfillJson(route, { + version: 1, + channelSlug: CHANNEL_SLUG, + pageCount: 1, + maxPageBytes: 8388608, + generatedAt: new Date().toISOString(), + slugToPage: Object.fromEntries(VIDS.map((v) => [v.id, 0])), + }), + ); + await page.route(/\/transcripts\/[^/]+\/page-\d+\.json$/, (route) => fulfillJson(route, VIDS.map(record))); + await page.route("**/subs/manifest.json", (route) => + fulfillJson(route, { version: 4, channels: [], totalCount: 0, liveChatTotalCount: 0, generatedAt: new Date().toISOString() }), + ); + return { platformHits }; +} + +// A short mono 16-bit PCM WAV of a quiet tone, made in the test: no binary in +// the repo, nothing fetched. +export function makeWav(seconds = 8, rate = 8000): Buffer { + const samples = seconds * rate; + const buf = Buffer.alloc(44 + samples * 2); + buf.write("RIFF", 0, "ascii"); + buf.writeUInt32LE(36 + samples * 2, 4); + buf.write("WAVE", 8, "ascii"); + buf.write("fmt ", 12, "ascii"); + buf.writeUInt32LE(16, 16); + buf.writeUInt16LE(1, 20); // PCM + buf.writeUInt16LE(1, 22); // mono + buf.writeUInt32LE(rate, 24); + buf.writeUInt32LE(rate * 2, 28); + buf.writeUInt16LE(2, 32); + buf.writeUInt16LE(16, 34); + buf.write("data", 36, "ascii"); + buf.writeUInt32LE(samples * 2, 40); + for (let i = 0; i < samples; i++) { + buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 440 * i) / rate) * 2000), 44 + i * 2); + } + return buf; +} diff --git a/export/e2e/local-file.spec.ts b/export/e2e/local-file.spec.ts @@ -0,0 +1,141 @@ +import { expect, test, type Page } from "@playwright/test"; +import { expectModalOpen } from "./helpers"; +import { installMissingSourceRoutes, makeWav, slugOf } from "./fixtures/missing-source"; + +// THE VISITOR'S OWN COPY (lane missing-source, slice 2). A local file picked on +// a video page plays in the page from an object URL, the transcript follows it +// and a cue click seeks it, through an offset the visitor can nudge or set from +// "This line is playing now". The file never leaves the browser: from the pick +// on, the page makes NO request but blob: ones, and localStorage gains nothing +// but the offset. + +const OFFSET_KEY = `archilyzer:local-offset:${slugOf("synthmem001")}`; +const FILE = { name: "my-synth-copy.wav", mimeType: "audio/wav", buffer: makeWav() }; + +const video = (page: Page) => page.locator('video[aria-label="Your copy"]'); +const fileTime = (page: Page) => video(page).evaluate((v: HTMLVideoElement) => v.currentTime); +const localStorageKeys = (page: Page) => page.evaluate(() => Object.keys(localStorage).sort()); + +// Playback itself is the browser's; what is tested is where the page puts the +// file's clock. So play() starts nothing and every currentTime read is exactly +// where the page put it. +async function stillPlayback(page: Page) { + await page.addInitScript(() => { + HTMLMediaElement.prototype.play = function () { + return Promise.resolve(); + }; + }); +} + +async function pick(page: Page) { + await expect(page.getByRole("button", { name: "Play your own copy" })).toBeVisible(); + await page.getByTestId("local-file-input").setInputFiles(FILE); + await expect(video(page)).toHaveAttribute("src", /^blob:/); + await expect.poll(() => video(page).evaluate((v: HTMLVideoElement) => v.readyState)).toBeGreaterThanOrEqual(1); +} + +async function cue(page: Page, text: string) { + await page.locator("li", { hasText: text }).getByRole("button").click(); +} + +test.describe("export — play your own copy", () => { + test("on a source no longer public: plays, follows, seeks, takes an offset, sends nothing", async ({ page }) => { + await installMissingSourceRoutes(page); + await stillPlayback(page); + await page.goto(`/?v=${slugOf("synthmem001")}`); + await expectModalOpen(page); + const panel = page.getByTestId("source-missing"); + await expect(panel.getByRole("button", { name: "Play your own copy" })).toBeVisible(); + await expect(panel).toContainText("Your file stays in this browser: nothing is uploaded."); + const keysBefore = await localStorageKeys(page); + + // From here on, the only requests allowed are blob: ones. + const after: string[] = []; + page.on("request", (r) => { + if (!r.url().startsWith("blob:")) after.push(`${r.method()} ${r.url()}`); + }); + await pick(page); + await expect(page.getByTestId("local-file-bar")).toContainText("Your copy: my-synth-copy.wav"); + await expect(page.getByTestId("local-file-offset")).toHaveText("Offset 0.00 s"); + + // Click-to-seek, on the cue clock. + await cue(page, "second synth line"); + await expect.poll(() => fileTime(page)).toBeCloseTo(2, 1); + // +1 s: the transcript's 0:03 is now 0:04 into the file. + await page.getByRole("button", { name: "Offset +1 second" }).click(); + await expect(page.getByTestId("local-file-offset")).toHaveText("Offset +1.00 s"); + await cue(page, "third synth line"); + await expect.poll(() => fileTime(page)).toBeCloseTo(4, 1); + // The transcript follows the file: at 4.0 s with +1 s, the 0:03 line is on. + await expect(page.locator("li", { hasText: "third synth line" })).toHaveClass(/bg-blue-950/); + + // "This line is playing now": the file at 5.5 s is the 0:02 line → +3.50 s. + await video(page).evaluate( + (v: HTMLVideoElement) => + new Promise<void>((res) => { + v.addEventListener("seeked", () => res(), { once: true }); + v.currentTime = 5.5; + }), + ); + await page.getByRole("button", { name: "This line is playing now" }).click(); + await expect(page.getByText("Click the line you hear now (Esc cancels).")).toBeVisible(); + await cue(page, "second synth line"); + await expect(page.getByTestId("local-file-offset")).toHaveText("Offset +3.50 s"); + expect(await fileTime(page)).toBeCloseTo(5.5, 1); + + // Only the offset was stored, as a number. + const keysAfter = await localStorageKeys(page); + expect(keysAfter.filter((k) => !keysBefore.includes(k))).toEqual([OFFSET_KEY]); + expect(await page.evaluate((k) => localStorage.getItem(k), OFFSET_KEY)).toBe("3.5"); + const stored = await page.evaluate(() => JSON.stringify({ ...localStorage })); + expect(stored).not.toContain("my-synth-copy"); + // Nothing went over the network once the file was picked. + expect(after).toEqual([]); + + // Stop: the URL is revoked and the panel is back. + const src = await video(page).getAttribute("src"); + await page.getByRole("button", { name: "Stop using my copy" }).click(); + await expect(video(page)).toHaveCount(0); + await expect(page.getByTestId("source-missing")).toBeVisible(); + // Focus goes back to the control that picked the file. + await expect(panel.getByRole("button", { name: "Play your own copy" })).toBeFocused(); + const revoked = await page.evaluate((u) => fetch(u as string).then(() => false, () => true), src); + expect(revoked).toBe(true); + }); + + test("the offset comes back for the same video, and Esc cancels the sync", async ({ page }) => { + await installMissingSourceRoutes(page); + await stillPlayback(page); + await page.addInitScript((k) => localStorage.setItem(k, "-0.5"), OFFSET_KEY); + await page.goto(`/?v=${slugOf("synthmem001")}`); + await expectModalOpen(page); + await pick(page); + await expect(page.getByTestId("local-file-offset")).toHaveText("Offset −0.50 s"); + await page.getByRole("button", { name: "This line is playing now" }).click(); + await page.keyboard.press("Escape"); + await expect(page.getByText("Click the line you hear now (Esc cancels).")).toHaveCount(0); + // Esc cancelled the sync; it did not collapse the modal. + await expectModalOpen(page); + }); + + test("on a public video: behind a plain control, and the embed gives way", async ({ page }) => { + await installMissingSourceRoutes(page); + await stillPlayback(page); + await page.goto(`/?v=${slugOf("synthpub001")}`); + await expectModalOpen(page); + const offer = page.getByTestId("local-file-offer"); + await expect(offer.getByRole("button", { name: "Play your own copy" })).toBeVisible(); + await expect(offer).toContainText("Your file stays in this browser: nothing is uploaded."); + const after: string[] = []; + page.on("request", (r) => { + if (!r.url().startsWith("blob:")) after.push(`${r.method()} ${r.url()}`); + }); + await pick(page); + await expect(page.locator("iframe")).toHaveCount(0); + await cue(page, "fourth synth line"); + await expect.poll(() => fileTime(page)).toBeCloseTo(5, 1); + expect(after).toEqual([]); + await page.getByRole("button", { name: "Stop using my copy" }).click(); + await expect(offer.getByRole("button", { name: "Play your own copy" })).toBeFocused(); + }); +}); diff --git a/export/e2e/source-missing.spec.ts b/export/e2e/source-missing.spec.ts @@ -0,0 +1,105 @@ +import { expect, test } from "@playwright/test"; +import { expectModalOpen } from "./helpers"; +import { installMissingSourceRoutes, slugOf, watchUrl } from "./fixtures/missing-source"; + +// A SOURCE NO LONGER PUBLIC (lane missing-source, slice 1). A video whose state +// is members-only, private or deleted at its platform gets no player — no +// embed, no request to the platform — but one sentence with the state and the +// day, the platform link kept but marked, and its transcript working as for any +// video. Unlisted keeps its player. The state comes from the fresh summaries +// first: a transcript record cached in IndexedDB is never refreshed. + +const panel = (page: import("@playwright/test").Page) => page.getByTestId("source-missing"); +const panelRegion = (page: import("@playwright/test").Page) => page.getByRole("region", { name: "Source availability" }); + +test.describe("export — a source no longer public", () => { + test("members-only: the sentence, the marked link, no embed and no platform request", async ({ page }) => { + const { platformHits } = await installMissingSourceRoutes(page); + await page.goto(`/?v=${slugOf("synthmem001")}`); + await expectModalOpen(page); + await expect(panel(page)).toContainText( + "This stream is no longer public on YouTube (members-only; first seen 19 Nov 2026). The transcript is kept here.", + ); + await expect(panelRegion(page)).toBeVisible(); + const link = panel(page).getByRole("link", { name: "Open on YouTube (members-only)" }); + await expect(link).toHaveAttribute("href", watchUrl("synthmem001")); + await expect(link).toHaveAttribute("rel", /noopener/); + await expect(page.locator("iframe")).toHaveCount(0); + // The transcript follows a click with no player at all. + const third = page.locator("li", { hasText: "third synth line" }); + await third.getByRole("button").click(); + await expect(third).toHaveClass(/bg-blue-950/); + await page.waitForTimeout(500); + expect(platformHits).toEqual([]); + }); + + test("private with no day, and deleted with one", async ({ page }) => { + await installMissingSourceRoutes(page); + await page.goto(`/?v=${slugOf("synthpri001")}`); + await expectModalOpen(page); + await expect(panel(page)).toContainText( + "This video is no longer public on YouTube (private). The transcript is kept here.", + ); + await expect(panel(page).getByRole("link", { name: "Open on YouTube (private)" })).toBeVisible(); + + await page.goto(`/?v=${slugOf("synthdel001")}`); + await expectModalOpen(page); + await expect(panel(page)).toContainText( + "This video is no longer public on YouTube (removed; first seen 31 Dec 2025). The transcript is kept here.", + ); + await expect(panel(page).getByRole("link", { name: "Open on YouTube (removed)" })).toBeVisible(); + + // No address: the label, never an empty link. + await page.goto(`/?v=${slugOf("synthnou001")}`); + await expectModalOpen(page); + await expect(panel(page)).toContainText("Open on YouTube (removed)"); + await expect(panel(page).getByRole("link")).toHaveCount(0); + await expect(page.locator('a[href=""]')).toHaveCount(0); + }); + + test("unlisted and public keep their player", async ({ page }) => { + const { platformHits } = await installMissingSourceRoutes(page); + for (const id of ["synthunl001", "synthpub001"]) { + await page.goto(`/?v=${slugOf(id)}`); + await expectModalOpen(page); + await expect(panel(page)).toHaveCount(0); + } + // The embed was asked for (and aborted by the mock). + await expect.poll(() => platformHits.length).toBeGreaterThan(0); + }); + + test("the fresh summaries win over a stale record, both ways", async ({ page }) => { + // The summaries arrive well after the stale record: no embed is mounted + // meanwhile, so the platform is never asked. + const { platformHits } = await installMissingSourceRoutes(page, { summariesDelayMs: 1500 }); + await page.goto(`/?v=${slugOf("synthstl001")}`); + await expectModalOpen(page); + await expect(page.getByRole("heading", { name: "Synth stale record" })).toBeVisible(); + await expect(panel(page)).toContainText("(members-only; first seen 1 Oct 2026)"); + await page.waitForTimeout(500); + expect(platformHits).toEqual([]); + await expect(page.locator("iframe")).toHaveCount(0); + + await page.goto(`/?v=${slugOf("synthbak001")}`); + await expectModalOpen(page); + // The record (loaded: its title is up) says removed; the summaries say + // public, and they win once they land. + await expect(page.getByRole("heading", { name: "Synth back again" })).toBeVisible(); + await expect(panel(page)).toHaveCount(0); + }); + + test("a search card's badge tooltip carries the day", async ({ page }) => { + await installMissingSourceRoutes(page); + await page.goto("/"); + await page.getByTestId("query-builder").waitFor(); + const scope = page.locator('[data-testid^="leaf-scope-"]').first(); + await scope.selectOption({ label: "Title / channel" }); + const input = page.locator('[data-testid^="leaf-query-"]').first(); + await input.click(); + await input.fill("synth"); + await input.press("Enter"); + const badge = page.getByTestId("state-badge-members_only").first(); + await expect(badge).toHaveAttribute("title", /; first seen 19 Nov 2026$/); + await expect(page.getByTestId("state-badge-private")).toHaveAttribute("title", "Made private on the source platform"); + }); +}); diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1875,7 +1875,10 @@ export function usage() { " pace) on the platform's download queue, then live_chat.cues.json. YouTube", ' only: another platform answers "no chat fetcher for <platform>" (info, no', " job), as do a chat already here and fresh and a video never live. A pass", - " that finds no replay ends done and says so.", + " that finds no replay ends done and says so. A pass the source refuses for", + " the video as members-only or private records that in its", + " availability.json (source fetch); a removal is recorded only by the", + " channel's Check availability.", "", 'fetch-chat-backlog fetches a channel\'s stream chats after its downloads:', ' {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose', @@ -1911,6 +1914,10 @@ export function usage() { ' audio-only formats and whether any is non-fragmented, English captions,', ' the keys that changed. An id with no data/<id>/ is refused (a refresh', ' re-reads a video already archived), as are archive.org and Wayback records.', + " A refusal for the video as members-only or private, or a metadata", + " availability field that changes the reading, is recorded in its", + " availability.json (source fetch): the one-video availability recheck. A", + " removal is recorded only by the channel's Check availability.", "", '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)',