// ONE PRESS AT A TIME PER SERVICE, AND ITS RESULT REMEMBERED (the /cookies // screen, plans/cookie-screen.md). Every button that refreshes, connects or // rechecks a service's cookies — /cookies, the dashboard banner's Recheck, // /settings' Refresh cookies and Connect, a forum channel's Connect, `pnpm ops // recheck-service` — runs through `withCookieAction`: // // - a second press while one is in flight for that service is REFUSED with a // sentence saying so (never queued behind it): an in-process mark per // service, and a `recheck-service-cookies` job already queued or running // on the service's queue (the proactive timer's) counts as in flight too; // - the outcome is recorded as the service's last press // (noteServiceCookieAction, `.service-cookies.json` `actions`), which the // screen shows as "last result". // // // THE X PROFILE HAS ONE BROWSER AT A TIME (lane x-trending). X's Connect and // Refresh open the connected profile; so do the jobs that read X through it // (a trending-page read, a post capture: X_PROFILE_BROWSER_JOB_KINDS), which // X's queue already keeps one at a time among themselves. Two browsers on one // profile is a launch that fails with Chromium's own error, so each side is // refused with a sentence instead: a Connect or Refresh while such a job is // RUNNING (`xProfileJobRunning`; a queued one blocks nothing), and such a job // while a Connect or Refresh is in flight (`xPressInFlight`: the trending read // at enqueue and at its start, a post capture at its start). // Nothing else about Connect or Refresh changes. // // The mark lives on globalThis (one per server process, like the registry). import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { noteServiceCookieAction } from "yt-dlp-transcript-common/lib/serviceCookies-server"; import { serviceLabel, type ServiceCookieActionKind } from "yt-dlp-transcript-common/lib/serviceCookies"; import type { CookieRunning } from "yt-dlp-transcript-common/lib/cookieStatus"; import { RECHECK_JOB_KIND } from "yt-dlp-transcript-common/controller/serviceCookieTimer"; import path from "node:path"; import { READ_X_TRENDING_KIND, xRateLimitHoldSentence, } from "yt-dlp-transcript-common/lib/xTrending/config"; import { readJsonFileSync } from "yt-dlp-transcript-common/lib/jsonFile-server"; import { detectPlatform } from "yt-dlp-transcript-common/lib/platform"; import { jobKindLabel } from "yt-dlp-transcript-common/jobs/jobKinds"; const QUEUE_PREFIX = "service-cookies:"; const KEY = Symbol.for("archilyzer.cookieRefresh.inflight"); function inflight(): Map { const g = globalThis as unknown as Record>; return (g[KEY] ??= new Map()); } type JobLike = { id: string; kind: string; queueKey: string; status: string; queuedAt?: number; startedAt?: number; channelSlug?: string; spec?: { params?: Record }; }; // The platform a job's channel is on, by its config.json (its `platform`, // else its URL's) — or null. What decides whether a capture is X's: the JOB'S // PLATFORM, never its queue key, which a caller may override (review 2 N6). export type PlatformOf = (channelSlug: string | undefined) => string | null; export const channelPlatformOf: PlatformOf = (slug) => { if (!slug || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) return null; const raw = readJsonFileSync(path.join(getPaths().channelsDir, slug, "config.json")); if (!raw.ok || !raw.value || typeof raw.value !== "object") return null; const c = raw.value as { platform?: unknown; url?: unknown }; if (typeof c.platform === "string" && c.platform) return c.platform; return typeof c.url === "string" ? detectPlatform(c.url) : null; }; // Whether a capture opens the X profile's browser: a shot (the default), the // avatars alone or the context alone. One that takes no shot only downloads // media with the exported jar. export function captureOpensBrowser(params: { shots?: unknown; avatarsOnly?: unknown; contextOnly?: unknown } | undefined): boolean { return params?.shots !== false || params?.avatarsOnly === true || params?.contextOnly === true; } // What is running per service now: the presses in flight here, and any // recheck job queued or running on a service's queue. export function runningCookieActions( jobs: readonly JobLike[] = getRegistry().list(), ): Record { const out: Record = {}; for (const j of jobs) { if (j.kind !== RECHECK_JOB_KIND || !j.queueKey.startsWith(QUEUE_PREFIX)) continue; if (j.status !== "queued" && j.status !== "running") continue; const since = j.startedAt ?? j.queuedAt; out[j.queueKey.slice(QUEUE_PREFIX.length)] = { action: "recheck", since: new Date(since ?? Date.now()).toISOString(), jobId: j.id, }; } for (const [service, r] of inflight()) out[service] = r; return out; } // A job that holds the connected X profile's browser now: RUNNING (a queued // one holds nothing yet), and either a trending read, or a post capture of an // X channel that opens a browser — whatever queue it was put on. export function xProfileJobRunning( jobs: readonly JobLike[] = getRegistry().list(), platformOf: PlatformOf = channelPlatformOf, ): { kind: string; since: string; jobId: string } | null { for (const j of jobs) { if (j.status !== "running") continue; const holds = j.kind === READ_X_TRENDING_KIND || (j.kind === "capture-posts" && captureOpensBrowser(j.spec?.params) && platformOf(j.channelSlug) === "twitter"); if (!holds) continue; return { kind: j.kind, since: new Date(j.startedAt ?? j.queuedAt ?? Date.now()).toISOString(), jobId: j.id }; } return null; } export function xProfileJobSentence(action: string, job: { kind: string; since: string; jobId: string }): string { return ( `X's ${action} opens the connected profile, and a job is using it: ${jobKindLabel(job.kind)} ` + `(${job.jobId}, running since ${job.since.slice(11, 19)} UTC). Cancel it on /jobs or wait for it to finish, then press again.` ); } // Why a job may not open the X profile now — a Connect or a Refresh of X is // in flight — or null. (A recheck opens no profile.) export function xPressInFlight(what = "read the trending page"): string | null { const r = inflight().get("x"); if (!r || (r.action !== "connect" && r.action !== "refresh")) return null; return ( `X's ${r.action} is running (since ${r.since.slice(11, 19)} UTC) and holds the connected profile: ` + `${what} once it has finished.` ); } // WHY AN X POST CAPTURE DOES NOT START NOW, or null — asked at the job's // start (channels/[slug]/socialActions.ts), by the channel's PLATFORM: // - X is cooling down after a rate limit (review 2 N5; `cooldownMs` is // platformCooldownRemainingMs("twitter")): any X capture, shot or not — // its media comes from X too; // - X's Connect or Refresh holds the profile, and this capture would open // its browser. // A capture of another platform's posts is never held by either. export function xCaptureStartRefusal( job: { platform: string | null | undefined; shots?: unknown; avatarsOnly?: unknown; contextOnly?: unknown }, cooldownMs: number, now: number = Date.now(), ): string | null { if (job.platform !== "twitter") return null; if (cooldownMs > 0) return xRateLimitHoldSentence("X capture", cooldownMs, now); return captureOpensBrowser(job) ? xPressInFlight("capture these posts") : null; } export function busySentence(service: string, r: CookieRunning): string { return `${serviceLabel(service)}'s ${r.action} is already running (since ${r.since.slice(11, 19)} UTC) — wait for it to finish.`; } export type CookieActionOutcome = { ok: boolean; message: string; result?: "clean" | "stale" | "failed"; jobId?: string; }; // The recorded outcome of a recheck (operations/serviceCookiesActions.ts): ok // only when the service answered cleanly — a "stale" or "failed" answer is // remembered as not ok, as the press's own note in the row says it. export function recheckOutcome( r: | { ok: true; jobId: string; result: "clean" | "stale" | "failed"; message: string } | { ok: false; error: string; jobId?: string }, ): CookieActionOutcome { return r.ok ? { ok: r.result === "clean", result: r.result, message: r.message, jobId: r.jobId } : { ok: false, message: r.error, ...(r.jobId ? { jobId: r.jobId } : {}) }; } // Run `fn` as the one press for `service`, or refuse. `describe` turns its // answer into the recorded outcome. export async function withCookieAction( service: string, action: ServiceCookieActionKind, fn: () => Promise, describe: (r: T) => CookieActionOutcome, opts: { paths?: Paths; jobs?: () => readonly JobLike[]; platformOf?: PlatformOf } = {}, ): Promise { const running = runningCookieActions(opts.jobs ? opts.jobs() : undefined)[service]; if (running) return { ok: false, error: busySentence(service, running), busy: true }; if (service === "x" && (action === "connect" || action === "refresh")) { const job = xProfileJobRunning(opts.jobs ? opts.jobs() : undefined, opts.platformOf); if (job) return { ok: false, error: xProfileJobSentence(action, job), busy: true }; } const map = inflight(); map.set(service, { action, since: new Date().toISOString() }); // Everything after the mark is inside the try: whatever throws, the finally // releases it, so a service is never left marked busy. try { const paths = opts.paths ?? getPaths(); let r: T; try { r = await fn(); } catch (e) { await noteServiceCookieAction(paths, service, { action, ok: false, message: (e as Error).message }); throw e; } // A describe that throws only costs the record: the press itself succeeded // and its answer is returned as it came. let o: CookieActionOutcome | null = null; try { o = describe(r); } catch { o = null; } if (o) { await noteServiceCookieAction(paths, service, { action, ok: o.ok, message: o.message, ...(o.result ? { result: o.result } : {}), ...(o.jobId ? { jobId: o.jobId } : {}), }); } return r; } finally { map.delete(service); } }