import path from "node:path"; import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { isValidChannelSlug, listChannelConfigs, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { isXTrendingChannel, NOT_AN_X_TRENDING_LIBRARY } from "yt-dlp-transcript-common/lib/xTrending/config"; import { listXTrending, summarizeXTrending, X_TRENDING_LIST_MAX, X_TRENDING_LIST_STATES, type XTrendingListFilter, type XTrendingListState, } from "yt-dlp-transcript-common/lib/xTrending/store"; import { readXTrendingAccounts } from "yt-dlp-transcript-common/controller/xSearchLeads"; import { X_TRENDING_ACCOUNTS_MAX } from "yt-dlp-transcript-common/lib/xTrending/accounts"; import { readXTrendingPublished } from "yt-dlp-transcript-common/lib/xTrending/published"; import { opsAuth, opsFail } from "../_lib"; import { withAttention } from "../_attention"; export const dynamic = "force-dynamic"; // GET /api/ops/trending?slug=[&topic=][&limit=] // -> { ok, slug, name, topics: [{id, title, posts, sources: [{trendId, url, // title?, summary?, lastUpdatedAt?, tabs?, lastReadTab?, reads, // lastReadAt}], watch?}], // posts: [{id, author, authorName?, createdAt, url, text, // media: {count, kinds, thumbnail?}, topic, // reads: [{read, trendId, at, tab?}], gone?, capture?, thread, // judgement?}], // total, reads: [, …] } // // An X trending library's topics and posts (lane x-trending) — `pnpm ops get // trending ` and the MCP's x_trending_topics / x_trending_posts. Read // from the library's own files and its posts shards (lib/xTrending/store.ts): // a library is in no index build, so nothing here needs one. `topic` narrows // the posts to one topic; `limit` (default 100, at most 500) caps them, the // newest read's first, in page order; `total` is the count before the cap. // // Everything a list view needs per post. `media.thumbnail` is the first // captured picture's path relative to the channel // (`trending/posts-media//` — a library's media is kept under trending/, // and no route serves it yet), present once the post is captured; `thread` is // the root post id of the thread it belongs to; `judgement` ({state: keep | // drop | later, note?, by: agent | operator, at, from?}) is its own, else its // thread's (`from: "thread"`), written by `judge-trending`; a post with none // is undecided. `gone` ({at, read, trendId}) says a page that showed the post // before did not show it at `at`, a read that reached the page's end: gone // FROM THE PAGE, which is not deleted. `capture` ({at, state, shot, files, // mediaState, mediaOwed?}) is what its capture holds; `mediaOwed` "next" is // asked for again by a later capture, "kept" once the post is marked keep. // A topic's `watch` ({on, intervalMinutes, until, shots, lastTickAt?, // nextTickAt?, ticks, paused?: {reason, since, sentence}, ended?, sentence}) is // there once it has been watched (`watch-trending`); `sentence` says what it // is doing. NEVER the raw capture, a cookie or a token. // // THE JUDGE VIEW'S ASKS (lane posts-library: umtool's Posts library page and // `umtool library`). With none of them the answer above is unchanged. // // accounts=1 -> { ok, slug, accounts: [{handle, key, name?, posts, kept, // keptByOperator, topics: [ids], last, archivedAs?}], // total, posts, more } — THE LIBRARY'S ACCOUNTS (lane // x-trending-publish), like an X search channel's leads: // who wrote its posts, most posts first; `kept` by the // judgement in force; `archivedAs` the X channels that // already archive the account. Takes `topic` and `limit` // (default 100, at most 500) and nothing else. Archive // one with `pnpm ops x-search-lead` (action "archive"). // (no slug) -> { ok, libraries: [{slug, name, topics, posts, unjudged}] } // every library, by its marker // offset= the posts after the first n (pages with `limit`) // state= unjudged | keep | drop | later: the judgement IN FORCE // gone=1 only posts gone from the page // media=1 only posts carrying media // author= one account's posts (any case, with or without "@") // q= every word, any case, in the words, handle or display name // since= only posts a read FIRST showed after that time // by= agent | operator: the hand whose judgement is in force // seen= with detail=1: {"": "", …}, when each topic // was last marked seen (the judge view's own state); each // topic then answers `fresh`, its posts a read first showed // after its mark (all of them for a topic with no mark) — // every topic's count in this one read // ids=1 -> `ids`: every matching post's id in listing order, // uncapped, and no rows (what a bulk press judges) // detail=1 each topic gains `counts` {unjudged, keep, drop, later, // gone}; the answer gains `authors` [{author, posts}] (of the // topic asked for); each row gains `detail` {post: {isReply, // isRepost, replyTo?, quoted?, links, engagement?, // mediaCount?}, firstSeenAt, ownJudgement?, threadJudgement?, capture?: {shot?, // threadShot?, media: [{name, kind, bytes}], context?: // {parent?, quoted?}}}. A capture's files are NAMES under // trending/posts-media//: this route serves no bytes. const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "by", "seen", "ids", "detail", "accounts"]; const FLAGS = new Set(["1", "true"]); async function get(request: Request) { const denied = opsAuth(request); if (denied) return denied; const sp = new URL(request.url).searchParams; for (const key of sp.keys()) { if (!PARAMS.includes(key)) return opsFail(`unknown parameter "${key}" (${PARAMS.join(", ")})`); } const paths = getPaths(); if (sp.get("slug") === null) { if ([...sp.keys()].length) return opsFail(`without "slug" this lists the libraries and takes no other parameter`); const libraries = []; for (const { slug, config } of await listChannelConfigs(paths)) { if (!isXTrendingChannel(config)) continue; libraries.push({ slug, name: config.name ?? slug, ...(await summarizeXTrending(path.join(paths.channelsDir, slug))) }); } return NextResponse.json({ ok: true, libraries }); } const slug = sp.get("slug") ?? ""; if (!isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); const topic = sp.get("topic") ?? undefined; // THE LIBRARY'S ACCOUNTS (lane x-trending-publish): its own answer. if (sp.get("accounts") !== null) { if (!FLAGS.has(sp.get("accounts")!)) return opsFail(`"accounts" is 1 when given`); const extra = [...sp.keys()].filter((k) => !["slug", "topic", "limit", "accounts"].includes(k)); if (extra.length) return opsFail(`with accounts=1 the listing takes slug, topic and limit only (not "${extra[0]}")`); let cap: number | undefined; if (sp.get("limit") !== null) { cap = Number(sp.get("limit")); if (!Number.isInteger(cap) || cap < 1 || cap > X_TRENDING_ACCOUNTS_MAX) return opsFail(`"limit" is a whole number, 1–${X_TRENDING_ACCOUNTS_MAX}`); } const view = await readXTrendingAccounts(paths, slug, { ...(topic ? { topic } : {}), ...(cap !== undefined ? { limit: cap } : {}) }); if (!view.ok) return opsFail(view.error, /^No such channel/.test(view.error) ? 404 : 400); return NextResponse.json(view); } let limit: number | undefined; if (sp.get("limit") !== null) { limit = Number(sp.get("limit")); if (!Number.isInteger(limit) || limit < 1 || limit > X_TRENDING_LIST_MAX) { return opsFail(`"limit" is a whole number, 1–${X_TRENDING_LIST_MAX}`); } } let offset: number | undefined; if (sp.get("offset") !== null) { offset = Number(sp.get("offset")); if (!Number.isInteger(offset) || offset < 0) return opsFail(`"offset" is a whole number, 0 or more`); } const filter: XTrendingListFilter = {}; const state = sp.get("state"); if (state !== null) { if (!X_TRENDING_LIST_STATES.includes(state as XTrendingListState)) return opsFail(`"state" is one of ${X_TRENDING_LIST_STATES.join(", ")}`); filter.state = state as XTrendingListState; } const flags: Record = {}; for (const key of ["gone", "media", "ids", "detail"]) { const v = sp.get(key); if (v !== null && !FLAGS.has(v)) return opsFail(`"${key}" is 1 when given`); flags[key] = v !== null; } if (flags.gone) filter.gone = true; if (flags.media) filter.media = true; const author = sp.get("author"); if (author !== null) { if (!/^@?[A-Za-z0-9_]{1,30}$/.test(author)) return opsFail(`"author" is an account's handle`); filter.author = author; } const q = sp.get("q"); if (q !== null) { if (q.length > 200) return opsFail(`"q" is at most 200 characters`); filter.q = q; } const since = sp.get("since"); if (since !== null) { if (!Number.isFinite(Date.parse(since))) return opsFail(`"since" is a time (ISO)`); filter.since = since; } const by = sp.get("by"); if (by !== null) { if (by !== "agent" && by !== "operator") return opsFail(`"by" is "agent" or "operator"`); filter.by = by; } let seen: Record | undefined; if (sp.get("seen") !== null) { if (!flags.detail) return opsFail(`"seen" goes with detail=1`); let parsed: unknown; try { parsed = JSON.parse(sp.get("seen")!); } catch { parsed = null; } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === "string" && Number.isFinite(Date.parse(v)))) { return opsFail(`"seen" is a JSON object of topic id to time (ISO)`); } seen = parsed as Record; } const config = await readChannelConfig(paths, slug); if (!config) return opsFail(`No such channel: ${slug}`, 404); if (!isXTrendingChannel(config)) return opsFail(NOT_AN_X_TRENDING_LIBRARY(slug)); const listing = await listXTrending(path.join(paths.channelsDir, slug), { ...(topic ? { topic } : {}), ...(limit !== undefined ? { limit } : {}), ...(offset !== undefined ? { offset } : {}), ...(Object.keys(filter).length ? { filter } : {}), ...(flags.detail ? { detail: true } : {}), ...(flags.ids ? { ids: true } : {}), ...(seen ? { seen } : {}), }); if (topic && !listing.topics.some((t) => t.id === topic || t.aliases?.includes(topic))) { return opsFail(`${slug} has no topic "${topic}" (its topics: ${listing.topics.map((t) => t.id).join(", ") || "none yet"})`); } // With `detail`: where each topic was published, when it was. if (flags.detail) { const published = await readXTrendingPublished(path.join(paths.channelsDir, slug)); const topics = listing.topics.map((t) => { const p = published[t.id]; return p ? { ...t, published: { channel: p.slug, firstAt: p.firstAt, lastAt: p.lastAt, posts: Object.keys(p.posts).length } } : t; }); return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing, topics }); } return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing }); } // Every answer says what needs a person (../_attention.ts), as ops() and // readRoute() do. export async function GET(request: Request) { return withAttention(await get(request)); }