import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { isXRunId, xRunConsole } from "yt-dlp-transcript-common/controller/xRun"; import { xRunAction } from "../../../review/xRunActions"; import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqSlugs } from "../_lib"; import { readRoute } from "../_read"; export const dynamic = "force-dynamic"; // THE X RUN (common/controller/xRun.ts; /review's X run console): fetch-posts // for several X posts channels IN SEQUENCE, as one `x-run` job on X's queue — // X's gap between two channels, at most 200 posts each, the cookie jar checked // before EACH channel. A stale jar (social.x.maxCookieAgeMinutes) or a raised // X alert stops the run and defers the rest until the next refresh; nothing // here refreshes the jar. // // POST { channels: [slug, …], limit? } a new run, in this order -> { ok, jobId, run } // POST { resume: "", limit? } its deferred channels -> { ok, jobId, run } // Refused before any job: nothing picked, a channel that is not an X posts // channel, a run already queued or running, a stale jar (the new run's file // is kept, deferred, for a Resume), a run with nothing to resume. // GET [?run=] -> { ok, run, candidates, jar, gapSeconds, maxPosts } // The run (the latest when none is named) as the console shows it, the X // posts channels in the default order, and the jar's age against the limit. // Nothing is asked of X and nothing is written. export async function POST(request: Request) { return ops(request, ["channels", "limit", "resume"], async (body) => { const resume = optString(body, "resume"); const limit = optPositiveInt(body, "limit"); if (resume !== undefined && body.channels !== undefined) { throw new OpsInputError('"resume" and "channels" are one at a time.'); } if (resume === undefined && body.channels === undefined) { throw new OpsInputError('"channels" (a new run) or "resume" (a run id) is required.'); } const res = await xRunAction({ ...(resume !== undefined ? { resume } : { channels: reqSlugs(body, "channels") }), ...(limit !== undefined ? { limit } : {}), }); if (!res.ok) return opsFail(res.error, 400, res.run ? { run: res.run } : undefined); void res.stream.cancel(); return NextResponse.json({ ok: true, jobId: res.jobId, run: res.run }); }); } export async function GET(request: Request) { return readRoute(request, ["run"], async (q) => { const run = q.get("run")?.trim() || undefined; if (run && !isXRunId(run)) return opsFail(`"${run}" is not an X run id`); const out = await xRunConsole(getPaths(), run); if (run && !out.run) return opsFail(`No X run ${run}`, 404); return { ...out }; }); }