Archilyzer · Source

archilyzer

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

commit 037d0ea7f3730edf0b0d67eebc47037a38bfceda
parent 102c3e62d376c1a9a241a515e886c162d1761886
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 19 Nov 2026 13:54:00 -0500

export: no dead player for a source no longer public; play your own copy

A members-only, private or deleted source mounts no platform player: no
embed and no request to the platform. In the player slot are the sentence,
the marked platform link and "Play your own copy". Unlisted and "Missing?"
keep their player. The state comes from the fresh summaries first, because a
record cached in IndexedDB is never refreshed.

Any video page can play a local file the visitor picks. The control is in
that panel when the source is gone and is a plain "Play your own copy"
control otherwise, with "Your file stays in this browser: nothing is
uploaded." beside it. The file plays from an object URL in place of the
platform player. The transcript follows it, a cue click seeks it, and the
clip marks and Share work on the cue clock through an offset. The offset can
be nudged by -1, -0.1, +0.1 or +1 s, or set from "This line is playing now"
(the next cue click; Esc cancels). Only the offset is ever stored. The file
player is imported statically, so picking a file makes no request at all.
That is asserted by the new e2e spec, alongside a source scan of the
modules that touch the file.

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

Diffstat:
Mcommon/components/FilePlayer.tsx | 12+++++++++++-
Acommon/components/LocalFileBar.tsx | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/components/LocalFilePicker.test.ts | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/components/LocalFilePicker.tsx | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/components/PlayerProvider.tsx | 310+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/components/TranscriptModal.tsx | 13+++++++++++--
Aexport/e2e/fixtures/missing-source.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexport/e2e/local-file.spec.ts | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aexport/e2e/source-missing.spec.ts | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 908 insertions(+), 7 deletions(-)

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,101 @@ +"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. +// +// 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, + localFile, + localSyncArmed, + openLocalFile, + clearLocalFile, + nudgeLocalOffset, + armLocalSync, + } = usePlayer(); + + if (!localFile) { + // Not before the record is here (its state decides where the control + // goes), and not for a source no longer public: the panel holds it. + if (!data || sourceGone) return null; + return ( + <div className="px-3 sm:px-0" data-testid="local-file-offer"> + <LocalFilePicker onPick={openLocalFile} /> + </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={clearLocalFile} + /> + {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,54 @@ +"use client"; + +import { 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, + tone = "dark", +}: { + onPick: (file: File) => void; + tone?: "dark"; +}) { + const inputRef = useRef<HTMLInputElement | null>(null); + const noteId = useId(); + return ( + <span className="inline-flex flex-wrap items-center justify-center gap-x-2 gap-y-1" data-tone={tone}> + <button + 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 } 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,23 @@ 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 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; + nudgeLocalOffset: (delta: number) => void; + armLocalSync: (on: boolean) => void; + syncLocalTo: (cueStart: number) => void; }; type PlayerTimeState = { @@ -404,6 +450,48 @@ 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 (key +// ["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. `undefined` while the video is +// in no loaded page (the record's state stands in); null with no query client. +function useFreshSummaryState( + id: string | null, +): { state: VideoState; stateSince?: string } | undefined { + const client = useContext(QueryClientContext); + const [found, setFound] = useState<{ key: string; state: VideoState; stateSince?: string } | undefined>(); + useEffect(() => { + if (!client || !id) return; + const { origin, slug } = splitId(id); + const read = () => { + 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) continue; + const next = { key: `${id}\u0000${summaryState(hit)}\u0000${hit.stateSince ?? ""}`, state: summaryState(hit), ...(hit.stateSince ? { stateSince: hit.stateSince } : {}) }; + setFound((prev) => (prev?.key === next.key ? prev : next)); + return; + } + }; + read(); + return client.getQueryCache().subscribe((event) => { + if (event.type === "updated" && event.query.queryKey[0] === "summaries-page") read(); + }); + }, [client, id]); + if (!found || !id || !found.key.startsWith(`${id}\u0000`)) return undefined; + return { state: found.state, ...(found.stateSince ? { stateSince: found.stateSince } : {}) }; +} + +// 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 +511,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 +573,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 +584,16 @@ export function PlayerProvider({ : (detail.track ?? null), }; }, [detail, detailMatches, urlVt]); + const freshState = useFreshSummaryState(activeSlug); + const sourceGone: SourceGone | null = useMemo(() => { + if (!data) return null; + const state = freshState ? freshState.state : data.state; + const since = freshState ? 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 +678,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 +702,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 +801,68 @@ 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]); + + 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 +903,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 +1101,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 +1165,14 @@ export function PlayerProvider({ copyTranscriptMarkdown, openInPreservetube, seekTo, + sourceGone, + localFile: localActive && local ? { name: local.name, offset: localOffset, error: localError } : null, + localSyncArmed: localActive && localSyncArmed, + openLocalFile, + clearLocalFile, + nudgeLocalOffset, + armLocalSync, + syncLocalTo, }), [ activeSlug, @@ -1007,6 +1200,17 @@ export function PlayerProvider({ copyTranscriptMarkdown, openInPreservetube, seekTo, + sourceGone, + localActive, + local, + localOffset, + localError, + localSyncArmed, + openLocalFile, + clearLocalFile, + nudgeLocalOffset, + armLocalSync, + syncLocalTo, ], ); const timeValue: PlayerTimeState = useMemo( @@ -1043,7 +1247,52 @@ 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} + /> + ) : data.platform === "rumble" ? ( <RumblePlayer key={data.id} ref={(p: RumblePlayerHandle | null) => { @@ -1210,6 +1459,59 @@ 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, +}: { + gone: SourceGone; + platform: Platform; + isLivestream: boolean; + webpageUrl: string; + compact: boolean; + onPick: (file: File) => void; +}) { + 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" + 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> + <a + href={webpageUrl} + target="_blank" + rel="noopener noreferrer" + className="text-sm text-zinc-200 underline hover:text-white" + > + {sourceLinkLabel(platform, gone.state)} + </a> + <LocalFilePicker onPick={onPick} /> + </section> + ); +} + function HiddenControls({ title, onShow, 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/export/e2e/fixtures/missing-source.ts b/export/e2e/fixtures/missing-source.ts @@ -0,0 +1,145 @@ +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 }; +}; + +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" } }, +]; + +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: 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`). +export async function installMissingSourceRoutes(page: Page): 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", (route) => 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,137 @@ +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(); + 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([]); + }); +}); diff --git a/export/e2e/source-missing.spec.ts b/export/e2e/source-missing.spec.ts @@ -0,0 +1,90 @@ +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"); + +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 since 19 Nov 2026). The transcript is kept here.", + ); + 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 since 31 Dec 2025). The transcript is kept here.", + ); + await expect(panel(page).getByRole("link", { name: "Open on YouTube (removed)" })).toBeVisible(); + }); + + 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 }) => { + await installMissingSourceRoutes(page); + await page.goto(`/?v=${slugOf("synthstl001")}`); + await expectModalOpen(page); + await expect(panel(page)).toContainText("(members-only since 1 Oct 2026)"); + + 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", /since 19 Nov 2026$/); + await expect(page.getByTestId("state-badge-private")).toHaveAttribute("title", "Made private on the source platform"); + }); +});