import path from "node:path"; import type { Paths } from "../lib/paths"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; import { indexListing, type ListingIndex } from "./listingMatch"; // WHAT A CHANNEL'S SOURCE HAS ACTUALLY LISTED, AND WHEN (lane verify-resume). // `channels//listing-evidence.json`. // // The pre-clean availability check (verifyBeforeClean) may clean a candidate // only on evidence that the source still has it. Before this file, nothing // recorded "the source listed id X at time T" across attempts: // - availability-verdict.json does, but only for the Quick check's COMPLETE // listing, and each check overwrites it whole; // - roster.json's `lastListedAt` cannot be trusted for it: the roster's // seed (seedRosterIfAbsent) stamps every id of the stored `playlist` file, // of any age, with the seed's time as a "listing"; // - `playlist` has no time, and maybe-missing.json is negative evidence. // So a listing the platform rate-limited part-way lost what it had read, and // every retry began again at entry 1. // // THE ONE RULE OF THIS FILE: an id is written only from an entry a source // RETURNED — what yt-dlp printed in a listing (a complete one, the prefix // before a 429, or a page of the paged sync). Nothing derived, seeded or // assumed. Each id is dated to the START of the listing that returned it (the // earlier time, so its freshness runs out sooner), and the newest such date // wins. `attempts` keeps the last listings' shape, so a listing cut short can // be continued (verifyBeforeClean's resume) rather than restarted. export const LISTING_EVIDENCE_FILENAME = "listing-evidence.json"; // An id not listed for this long is dropped from the file (no window may be // longer: verifyBeforeCleanMaxAgeHours is capped well below it). export const LISTING_EVIDENCE_RETAIN_MS = 30 * 24 * 3_600_000; export const LISTING_ATTEMPTS_KEPT = 20; export type ListingSource = // The Quick availability check (one whole-channel listing). | "quick-check" // The pre-clean check's own listing, possibly continued from an offset. | "clean-check" // Sync's periodic full sweep (one whole-channel listing). | "sync-full" // The channel's Store playlist (one whole-channel listing). | "store-playlist" // A page of Sync's newest-first walk (a prefix of the listing by design). | "sync-paged"; export type ListingAttempt = { // ISO time the listing started; every id it returned is dated to it. at: string; source: ListingSource; // True only when the lister ended NORMALLY at the channel's end from // `start` (yt-dlp exit 0, not cancelled, no range end). A 429 part-way, a // cancel, an early stop (exit 101) or a page range is false. complete: boolean; // The 1-based first entry asked for (`-I :`), 1 for a whole listing. start: number; // Entries it returned. count: number; // The last `Downloading page N` the extractor logged, when it logs pages. pagesReached?: number | null; platform: string; // The channel URL that was listed. url: string; }; export type ListingEvidence = { version: 2; // The channel URL every row and attempt below was taken from. Evidence for // another URL than the channel's current one is not evidence (review 1, F5): // a record whose URL differs, or that names none, reads as empty, and the // first listing of the new URL starts the record again. url: string | null; // Canonical page id → ISO time of the newest listing that returned it. seen: Record; // Rumble embed ids (rumble.com/embed// entries) → time, kept apart so an // embed id is never matched against a directory name (listingMatch.ts). embedSeen: Record; // NEWER EVIDENCE BEATS OLDER (review 1, F1): a directory id → the time a // listing that SHOULD have named it (it covered the video's place) did not. // Written by the pre-clean check from its own listings. A sighting or a // probe older than this does not vouch for the video. absent: Record; // Newest last. attempts: ListingAttempt[]; // THE NEWEST COMPLETE WHOLE-CHANNEL LISTING, kept apart from the capped // `attempts` (review 2, F1), so the omission it records can age out only by // the trust window, never by how many listings came after. Written by any // actor whose listing ended normally from entry 1 (Sync's full sweep, Store // playlist, the Quick check; a paged walk never is one). Its id sets answer // "did it name video X"; on a channel of 8,000 videos they are about 8,000 // ids of ~11 characters, ~120 KB of the file. lastComplete: CompleteListing | null; }; export type CompleteListing = { // When it started and when it ended (ISO). An omission is dated from the // END (review 2, F4): the listing may have passed a video's place at any // moment before it ended, so a sighting during the listing does not beat it. at: string; endedAt: string; source: ListingSource; url: string; count: number; // Canonical page ids and Rumble embed ids it returned, sorted. ids: string[]; embedIds: string[]; }; export function listingEvidencePath(paths: Pick, slug: string): string { return path.join(paths.channelsDir, slug, LISTING_EVIDENCE_FILENAME); } export function emptyEvidence(url: string | null = null): ListingEvidence { return { version: 2, url, seen: {}, embedSeen: {}, absent: {}, attempts: [], lastComplete: null }; } function isCompleteListing(v: unknown): v is CompleteListing { const c = v as Partial | null; return ( !!c && typeof c.at === "string" && Number.isFinite(Date.parse(c.at)) && typeof c.endedAt === "string" && Number.isFinite(Date.parse(c.endedAt)) && typeof c.url === "string" && typeof c.count === "number" && Array.isArray(c.ids) && c.ids.every((x) => typeof x === "string") && Array.isArray(c.embedIds) && c.embedIds.every((x) => typeof x === "string") ); } function stringMap(v: unknown): Record { const out: Record = {}; if (!v || typeof v !== "object") return out; for (const [k, t] of Object.entries(v as Record)) { if (k && typeof t === "string" && Number.isFinite(Date.parse(t))) out[k] = t; } return out; } function isAttempt(v: unknown): v is ListingAttempt { const a = v as Partial | null; return ( !!a && typeof a.at === "string" && Number.isFinite(Date.parse(a.at)) && (a.source === "quick-check" || a.source === "clean-check" || a.source === "sync-full" || a.source === "store-playlist" || a.source === "sync-paged") && typeof a.complete === "boolean" && typeof a.start === "number" && a.start >= 1 && typeof a.count === "number" && a.count >= 0 && typeof a.platform === "string" && typeof a.url === "string" ); } // A hand-edited or half-written file reads as what is valid in it, or empty: // the worst case is evidence lost (the check then asks the source), never // evidence invented. export function normalizeListingEvidence(value: unknown): ListingEvidence { const r = value as Partial | null; if (!r || typeof r !== "object") return emptyEvidence(); return { version: 2, url: typeof r.url === "string" && r.url ? r.url : null, seen: stringMap(r.seen), embedSeen: stringMap(r.embedSeen), absent: stringMap(r.absent), attempts: Array.isArray(r.attempts) ? r.attempts.filter(isAttempt).slice(-LISTING_ATTEMPTS_KEPT) : [], lastComplete: isCompleteListing(r.lastComplete) ? { ...r.lastComplete, ids: [...r.lastComplete.ids].sort(), embedIds: [...r.lastComplete.embedIds].sort() } : null, }; } export async function readListingEvidence( paths: Pick, slug: string, ): Promise { const read = await readJsonFile(listingEvidencePath(paths, slug)); return read.ok ? normalizeListingEvidence(read.value) : emptyEvidence(); } // The record as evidence for a channel listed at `url`: empty when it was // taken from another URL, or names none. export function evidenceForUrl(record: ListingEvidence, url: string): ListingEvidence { return record.url === url ? record : emptyEvidence(url); } export type RecordedListing = { at: string; source: ListingSource; urls: readonly string[]; complete: boolean; start?: number; pagesReached?: number | null; platform: string; // The channel URL that was listed. url: string; // When the listing ended (ISO); its start (`at`) when not given. endedAt?: string; }; // A time later than the clock (plus a minute) is a clock that was wrong when // it was written: never a stamp (review 1, F3). const FUTURE_SLACK_MS = 60_000; function inFuture(at: string, nowMs: number): boolean { const t = Date.parse(at); return !Number.isFinite(t) || t > nowMs + FUTURE_SLACK_MS; } // PURE: drop rows too old to keep and rows dated in the future. function prune(map: Record, nowMs: number): void { for (const [id, t] of Object.entries(map)) { if (inFuture(t, nowMs) || nowMs - Date.parse(t) > LISTING_EVIDENCE_RETAIN_MS) delete map[id]; } } // PURE: fold one listing into the record. A listing of another channel URL // starts the record again. A listing dated in the future is refused whole. export function foldListing(record: ListingEvidence, listing: RecordedListing, nowMs: number): ListingEvidence { const base = record.url === listing.url ? record : emptyEvidence(listing.url); const seen = { ...base.seen }; const embedSeen = { ...base.embedSeen }; const absent = { ...base.absent }; prune(seen, nowMs); prune(embedSeen, nowMs); prune(absent, nowMs); const attempts = base.attempts.filter((a) => !inFuture(a.at, nowMs)); let lastComplete = base.lastComplete && !inFuture(base.lastComplete.endedAt, nowMs) ? base.lastComplete : null; if (inFuture(listing.at, nowMs)) { return { version: 2, url: listing.url, seen, embedSeen, absent, attempts, lastComplete }; } const idx = indexListing(listing.urls); const stamp = (map: Record, id: string) => { const prev = map[id]; if (!prev || Date.parse(prev) < Date.parse(listing.at)) map[id] = listing.at; }; for (const id of idx.ids) stamp(seen, id); for (const id of idx.embedIds) stamp(embedSeen, id); const attempt: ListingAttempt = { at: listing.at, source: listing.source, complete: listing.complete, start: Math.max(1, Math.floor(listing.start ?? 1)), count: idx.entries, ...(listing.pagesReached !== undefined ? { pagesReached: listing.pagesReached } : {}), platform: listing.platform, url: listing.url, }; const endedAt = listing.endedAt && !inFuture(listing.endedAt, nowMs) ? listing.endedAt : listing.at; if ( listing.complete && attempt.start === 1 && listing.source !== "sync-paged" && (!lastComplete || Date.parse(lastComplete.endedAt) <= Date.parse(endedAt)) ) { lastComplete = { at: listing.at, endedAt, source: listing.source, url: listing.url, count: idx.entries, ids: [...idx.ids].sort(), embedIds: [...idx.embedIds].sort(), }; } return { version: 2, url: listing.url, seen, embedSeen, absent, attempts: [...attempts, attempt].slice(-LISTING_ATTEMPTS_KEPT), lastComplete, }; } // Record what a listing returned. Callers treat a failure as best-effort: a // lost write loses evidence (the next check asks again), never invents it. export async function recordListing( paths: Pick, slug: string, listing: RecordedListing, nowMs: number = Date.now(), ): Promise { const file = listingEvidencePath(paths, slug); await withJsonFileLock(file, async () => { const cur = await readListingEvidence(paths, slug); await writeJsonAtomic(file, foldListing(cur, listing, nowMs), { mkdir: true }); }); } // PURE: mark directory ids a listing of `url` at `at` should have named and // did not (the newest such time wins). export function foldAbsent(record: ListingEvidence, url: string, ids: Iterable, at: string, nowMs: number): ListingEvidence { const base = record.url === url ? record : emptyEvidence(url); const absent = { ...base.absent }; prune(absent, nowMs); if (!inFuture(at, nowMs)) { for (const id of ids) if (!absent[id] || Date.parse(absent[id]) < Date.parse(at)) absent[id] = at; } return { ...base, absent }; } export async function recordAbsent( paths: Pick, slug: string, url: string, ids: readonly string[], at: string, nowMs: number = Date.now(), ): Promise { if (ids.length === 0) return; const file = listingEvidencePath(paths, slug); await withJsonFileLock(file, async () => { const cur = await readListingEvidence(paths, slug); await writeJsonAtomic(file, foldAbsent(cur, url, ids, at, nowMs), { mkdir: true }); }); } const HOUR = 3_600_000; // Fresh: listed no longer ago than the window, and not dated in the future // (a clock that jumped is not evidence). export function isFresh(at: string, nowMs: number, maxAgeHours: number): boolean { const t = Date.parse(at); return Number.isFinite(t) && t <= nowMs + FUTURE_SLACK_MS && nowMs - t <= maxAgeHours * HOUR; } // NEWER EVIDENCE BEATS OLDER (review 1, F1; review 2, F1 and F4). When a // video was last contradicted by the source, in ms (-Infinity: never): the // END of the newest complete whole-channel listing inside the window when // that listing does not name the video (`lastComplete`, kept apart from the // capped attempts), or the video's absent mark (a listing of the pre-clean // check that covered its place and did not name it). A sighting or a probe // older than this does not vouch for it — one made while that listing was // still running included: the listing may have passed the video's place after // it. A video the complete listing named is never contradicted by it. export function contradictedSince( record: ListingEvidence, c: { dir: string; embed?: string }, nowMs: number, maxAgeHours: number, ): number { let t = Number.NEGATIVE_INFINITY; const complete = freshCompleteListing(record, nowMs, maxAgeHours); if (complete && !completeNames(complete, c)) t = Date.parse(complete.endedAt); const mark = record.absent[c.dir]; if (mark && !inFuture(mark, nowMs)) t = Math.max(t, Date.parse(mark)); return t; } // PURE: did the complete listing name this candidate (its directory id among // page ids, its embed id among embed ids)? export function completeNames(complete: CompleteListing, c: { dir: string; embed?: string }): boolean { const has = (list: string[], id: string) => { let lo = 0; let hi = list.length - 1; while (lo <= hi) { const mid = (lo + hi) >> 1; if (list[mid] === id) return true; if (list[mid] < id) lo = mid + 1; else hi = mid - 1; } return false; }; return has(complete.ids, c.dir) || (c.embed !== undefined && has(complete.embedIds, c.embed)); } // PURE: the newest fresh stamp of a candidate (its directory id against page // ids, its embed id against embed ids), in ms, or null. export function freshStampOf( record: ListingEvidence, c: { dir: string; embed?: string }, nowMs: number, maxAgeHours: number, ): number | null { if (maxAgeHours <= 0) return null; let best: number | null = null; for (const t of [record.seen[c.dir], c.embed !== undefined ? record.embedSeen[c.embed] : undefined]) { if (t && isFresh(t, nowMs, maxAgeHours)) best = Math.max(best ?? Number.NEGATIVE_INFINITY, Date.parse(t)); } return best; } // PURE: the ids listed inside the window, as a ListingIndex for listingMatch. export function freshListingIndex(record: ListingEvidence, nowMs: number, maxAgeHours: number): ListingIndex { const ids = new Set(); const embedIds = new Set(); if (maxAgeHours > 0) { for (const [id, t] of Object.entries(record.seen)) if (isFresh(t, nowMs, maxAgeHours)) ids.add(id); for (const [id, t] of Object.entries(record.embedSeen)) if (isFresh(t, nowMs, maxAgeHours)) embedIds.add(id); } return { ids, embedIds, entries: ids.size + embedIds.size }; } // PURE: is there a COMPLETE whole-channel listing inside the window? Then a // candidate it does not name is a suspect (unlisted or gone) to confirm by // itself — no second listing is needed to learn that. The record's // `lastComplete`, whatever has been listed since; fresh by its END, the moment it // contradicts from, so a sighting made while it ran never outlives it (review 3). export function freshCompleteListing( record: ListingEvidence, nowMs: number, maxAgeHours: number, ): CompleteListing | null { if (maxAgeHours <= 0) return null; const c = record.lastComplete; return c && isFresh(c.endedAt, nowMs, maxAgeHours) && !inFuture(c.endedAt, nowMs) ? c : null; } // WHERE A CUT-SHORT LISTING CONTINUES, per platform — read from yt-dlp's // channel extractors (the checkout the editor runs, 2026.07), not assumed: // odysee LBRYChannelIE (LBRYBaseIE): OnDemandPagedList(_fetch_page, _PAGE_SIZE 50) // bitchute BitChuteChannelIE returns OnDemandPagedList(page_func, PAGE_SIZE 25) // PlaylistEntries reads a PagedList one index at a time and fetches only the // page holding that index, so `--lazy-playlist -I :` asks nothing for // the pages before `start`. Every other channel extractor is a GENERATOR that // yt-dlp wraps in a LazyList, and `-I :` drives it through pages 1..N // to reach entry N — the same requests as starting over: // rumble RumbleChannelIE.entries: itertools.count(1) over `?page=N` (and // _real_extract strips any `page` from the URL, so none can be passed) // youtube YoutubeTabIE._entries: continuation tokens, page after page // twitch TwitchPlaylistBaseIE._entries: a GraphQL cursor, page after page // kick KickVideosIE._entries: one API answer holding every VOD (nothing // to skip: the listing is one request) // On those a retry starts at entry 1 again; what it gains is the saved // evidence (each attempt's entries count) and the per-video path for the // remainder (verifyBeforeClean). export const LISTING_OFFSET_PAGE_SIZE: Readonly> = { odysee: 50, bitchute: 25 }; // The continuation re-reads this many pages before where the last attempt // stopped: uploads since then push entries down (an entry seen twice is the // same id, counted once), and the overlap is how a shift is noticed. export const LISTING_RESUME_OVERLAP_PAGES = 2; export type ListingResume = { start: number; after: ListingAttempt | null; overlap: number }; // PURE: the first entry the next listing of this channel asks for. export function listingResumeStart( record: ListingEvidence, platform: string, nowMs: number, maxAgeHours: number, ): ListingResume { const pageSize = LISTING_OFFSET_PAGE_SIZE[platform]; if (!pageSize || maxAgeHours <= 0) return { start: 1, after: null, overlap: 0 }; const chain = record.attempts.filter( (a) => (a.source === "quick-check" || a.source === "clean-check") && a.platform === platform, ); const last = chain.at(-1); if (!last || last.complete || last.count === 0 || !isFresh(last.at, nowMs, maxAgeHours)) { return { start: 1, after: null, overlap: 0 }; } const overlap = LISTING_RESUME_OVERLAP_PAGES * pageSize; return { start: Math.max(1, last.start + last.count - overlap), after: last, overlap }; } // HOW MANY ENTRIES ONE LISTING REQUEST RETURNS, per platform — the size of a // page of the channel extractor (yt-dlp, 2026.07): LBRY _PAGE_SIZE 50, // BitChute PAGE_SIZE 25, Twitch's channel videos _PAGE_LIMIT 100, a YouTube // tab continuation about 30. Rumble's channel page sets none in the extractor // (an HTML page of its own size): 25 until measured. Kick lists every VOD in // one answer. A listing that logged its pages measures it instead // (count / pagesReached), which is what a Rumble listing does. export const LISTING_ENTRIES_PER_REQUEST: Readonly> = { youtube: 30, rumble: 25, odysee: 50, bitchute: 25, twitch: 100, kick: Number.POSITIVE_INFINITY, }; const DEFAULT_ENTRIES_PER_REQUEST = 30; // PURE: entries per listing request on this platform, measured when the // record has a listing that logged its pages. export function entriesPerRequest(record: ListingEvidence, platform: string): number { for (let i = record.attempts.length - 1; i >= 0; i--) { const a = record.attempts[i]; if (a.platform === platform && a.start === 1 && a.pagesReached && a.pagesReached > 0 && a.count > 0) { return Math.max(1, a.count / a.pagesReached); } } return LISTING_ENTRIES_PER_REQUEST[platform] ?? DEFAULT_ENTRIES_PER_REQUEST; } // THE FEW-CANDIDATES RULE (lane verify-resume): ask each remaining candidate // by itself, instead of listing the channel, when that costs FEWER requests — // K probes against the pages still to be listed, ceil((L - start + 1) / P), // where L is the channel's size (the larger of the roster, the data // directories and the longest complete listing), P the entries per request // and start the listing's first entry (a continuation's on Odysee/BitChute). // Each probe's verdict is kept (availability.json, checkedBy "check") and // counts as evidence for the window, so a rate limit part-way loses nothing: // the next run asks only the unverified remainder. A channel of a few hundred // videos always lists (one or two pages are cheaper than any probe run); an // 8,000-video Rumble channel (~320 pages at 25 a page) with 350 candidates // lists, and with the 150 a partial listing left, probes. export function preferPerVideo(opts: { candidates: number; listingSize: number; entriesPerRequest: number; start?: number; }): { perVideo: boolean; listingRequests: number } { const left = Math.max(0, opts.listingSize - (opts.start ?? 1) + 1); const listingRequests = Number.isFinite(opts.entriesPerRequest) ? Math.max(1, Math.ceil(left / Math.max(1, opts.entriesPerRequest))) : 1; return { perVideo: opts.candidates > 0 && opts.candidates < listingRequests, listingRequests }; }