Archilyzer · Source

archilyzer

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

commit 220fe7082b2e430922f6c01151f5c718e8c0e04c
parent b059c992f34ea8426f12267c509787df2f069705
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 06:32:52 -0500

common, editor: a trending library's listing answers the judge view -- `listXTrending` takes a filter (the judgement in force, gone from the page, has media, one account, words, first seen since a time), an offset, `ids` (every matching id, uncapped, no rows) and `detail` (a topic's counts, the accounts, the rest of the post's record, its first sighting, its own judgement, its capture's files by name and the context the capture read); `GET /api/ops/trending` passes them and, with no slug, lists the libraries by their marker; asked as before, the answer is as before

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

Diffstat:
Mcommon/lib/xTrending/store.test.ts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/xTrending/store.ts | 200++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aeditor/app/api/ops/trending/route.test.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/trending/route.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
4 files changed, 482 insertions(+), 15 deletions(-)

diff --git a/common/lib/xTrending/store.test.ts b/common/lib/xTrending/store.test.ts @@ -6,6 +6,7 @@ import path from "node:path"; import { xTrendingThreadKey, listXTrending, + summarizeXTrending, readXTrendingMembership, readXTrendingTopics, recordXTrendingRead, @@ -369,3 +370,122 @@ test("a thread's key ignores a threadId that only repeats the post's id, and doe assert.deepEqual(rows, { "902": "901", "903": "902" }); assert.equal((await readXTrendingMembership(dir))["903"].thread, "902"); }); + +// ── lane posts-library: what the judge view asks of the listing ───────────── + +async function judgeLibrary(name: string): Promise<string> { + const dir = root(name); + const reply: Post = { ...post("903", "saucer_fan", "A reply about spouts."), isReply: true, replyTo: { platform: "twitter", id: "901", author: "teapot_news" }, threadId: "901" }; + await writeXTrendingPosts(dir, [ + { ...post("901", "teapot_news", "The Kettle festival opens."), authorName: "Teapot News", mediaCount: 1, links: ["https://example.org/a"], engagement: { likes: 4 } }, + post("902", "saucer_fan", "Saucers are underrated."), + reply, + post("904", "Lid_Watch", "A lid fell off a kettle."), + post("905", "cup_other", "Other topic."), + ]); + await recordXTrendingRead(dir, { readId: READ_A, at: "2026-11-17T10:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["901", "902", "903"], added: 3, media: { "901": { count: 1, kinds: ["image"] } }, threads: { "903": "901" }, complete: true }); + await recordXTrendingRead(dir, { readId: READ_B, at: "2026-11-17T11:00:00.000Z", ref: REF, topic: "Kettles", postIds: ["901", "903", "904"], added: 1, complete: true }); + await recordXTrendingRead(dir, { readId: READ_C, at: "2026-11-17T12:00:00.000Z", ref: REF_2, topic: "Cups", postIds: ["905"], added: 1 }); + writeFileSync( + path.join(dir, "trending", "judgements.json"), + JSON.stringify({ + version: 1, + posts: { "902": { state: "drop", by: "operator", at: "2026-11-17T12:30:00.000Z" }, "904": { state: "later", by: "agent", at: "2026-11-17T12:30:00.000Z" } }, + threads: { "901": { state: "keep", note: "the opening", by: "operator", at: "2026-11-17T12:31:00.000Z" } }, + }), + ); + const cap = path.join(dir, "trending", "posts-media", "901"); + mkdirSync(cap, { recursive: true }); + for (const [f, body] of [["shot.png", "s"], ["shot-thread.png", "st"], ["901_1.jpg", "abc"], ["901_2.mp4", "abcde"], ["article.png", "a"], ["notes.txt", "n"]] as const) writeFileSync(path.join(cap, f), body); + writeFileSync( + path.join(cap, "capture.json"), + JSON.stringify({ version: 1, id: "901", capturedAt: "2026-11-17T12:40:00.000Z", state: "captured", mediaState: "ok", media: [], context: { readAt: "x", quoted: { text: "a quoted line", handle: "spout_co", media: [{ kind: "image", url: "https://example.org/p.jpg" }] } } }), + ); + return dir; +} + +test("with no new option the listing is what it was: no detail, no counts, no authors, no ids", async () => { + const dir = await judgeLibrary("judge-plain"); + const plain = await listXTrending(dir); + assert.deepEqual(Object.keys(plain).sort(), ["posts", "reads", "topics", "total"]); + assert.ok(plain.topics.every((t) => !("counts" in t))); + assert.ok(plain.posts.every((p) => !("detail" in p))); +}); + +test("the filters: the judgement in force, gone, media, author, words, first seen since; offset pages them", async () => { + const dir = await judgeLibrary("judge-filters"); + const ids = async (filter: Parameters<typeof listXTrending>[1]) => (await listXTrending(dir, filter)).posts.map((p) => p.id).sort(); + assert.deepEqual(await ids({ topic: "kettles" }), ["901", "902", "903", "904"]); + // 903 has no judgement of its own: its thread's (keep) is in force. + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "keep" } }), ["901", "903"]); + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "drop" } }), ["902"]); + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "later" } }), ["904"]); + assert.deepEqual(await ids({ filter: { state: "unjudged" } }), ["905"]); + // 902 was on the page at the first read and not at the second, which reached its end. + assert.deepEqual(await ids({ filter: { gone: true } }), ["902"]); + assert.deepEqual(await ids({ filter: { media: true } }), ["901"]); + assert.deepEqual(await ids({ filter: { author: "@LID_watch" } }), ["904"]); + assert.deepEqual(await ids({ filter: { author: "saucer_fan" } }), ["902", "903"]); + // Every word, any case, over the words, the handle and the display name. + assert.deepEqual(await ids({ filter: { q: "KETTLE" } }), ["901", "904"]); + assert.deepEqual(await ids({ filter: { q: "kettle lid" } }), ["904"]); + assert.deepEqual(await ids({ filter: { q: "teapot news" } }), ["901"]); + assert.deepEqual(await ids({ filter: { q: "nothinghere" } }), []); + assert.deepEqual(await ids({ filter: { since: "2026-11-17T10:30:00.000Z" } }), ["904", "905"]); + assert.deepEqual(await ids({ topic: "kettles", filter: { state: "keep", q: "spouts" } }), ["903"]); + // Pages: the same order, cut. + const all = (await listXTrending(dir)).posts.map((p) => p.id); + const two = await listXTrending(dir, { limit: 2, offset: 2 }); + assert.deepEqual(two.posts.map((p) => p.id), all.slice(2, 4)); + assert.equal(two.total, 5); + assert.deepEqual((await listXTrending(dir, { offset: 99 })).posts, []); +}); + +test("ids: every matching id in listing order, uncapped, and no rows", async () => { + const dir = await judgeLibrary("judge-ids"); + const all = (await listXTrending(dir, { topic: "kettles" })).posts.map((p) => p.id); + const out = await listXTrending(dir, { topic: "kettles", ids: true, limit: 1 }); + assert.deepEqual(out.ids, all); + assert.deepEqual(out.posts, []); + assert.equal(out.total, 4); + assert.deepEqual((await listXTrending(dir, { ids: true, filter: { state: "drop" } })).ids, ["902"]); +}); + +test("detail: a topic's counts, the accounts, the rest of the record, the first sighting, the own judgement and the capture's files by name", async () => { + const dir = await judgeLibrary("judge-detail"); + const out = await listXTrending(dir, { topic: "kettles", detail: true }); + const topics = Object.fromEntries(out.topics.map((t) => [t.id, t.counts])); + assert.deepEqual(topics.kettles, { unjudged: 0, keep: 2, drop: 1, later: 1, gone: 1 }); + assert.deepEqual(topics.cups, { unjudged: 1, keep: 0, drop: 0, later: 0, gone: 0 }); + assert.deepEqual(out.authors, [ + { author: "saucer_fan", posts: 2 }, + { author: "Lid_Watch", posts: 1 }, + { author: "teapot_news", posts: 1 }, + ]); + const by = Object.fromEntries(out.posts.map((p) => [p.id, p])); + assert.deepEqual(by["901"].detail?.post, { isReply: false, isRepost: false, links: ["https://example.org/a"], engagement: { likes: 4 }, mediaCount: 1 }); + assert.deepEqual(by["903"].detail?.post.replyTo, { platform: "twitter", id: "901", author: "teapot_news" }); + assert.equal(by["901"].detail?.firstSeenAt, "2026-11-17T10:00:00.000Z"); + assert.equal(by["904"].detail?.firstSeenAt, "2026-11-17T11:00:00.000Z"); + // 903: the thread's judgement is in force, and it has none of its own. + assert.equal(by["903"].judgement?.from, "thread"); + assert.equal(by["903"].detail?.ownJudgement, undefined); + assert.equal(by["902"].detail?.ownJudgement?.state, "drop"); + // The capture: names and sizes, pictures and videos only; the context without its media addresses. + assert.deepEqual(by["901"].detail?.capture, { + shot: "shot.png", + threadShot: "shot-thread.png", + media: [ + { name: "901_1.jpg", kind: "image", bytes: 3 }, + { name: "901_2.mp4", kind: "video", bytes: 5 }, + ], + context: { quoted: { text: "a quoted line", handle: "spout_co" } }, + }); + assert.equal(by["902"].detail?.capture, undefined); + assert.doesNotMatch(JSON.stringify(out), /example\.org\/p\.jpg|notes\.txt|capture\.json/); +}); + +test("a library in one line: its topics, its posts and how many are undecided", async () => { + assert.deepEqual(await summarizeXTrending(await judgeLibrary("judge-summary")), { topics: 2, posts: 5, unjudged: 1 }); + assert.deepEqual(await summarizeXTrending(root("judge-summary-empty")), { topics: 0, posts: 0, unjudged: 0 }); +}); diff --git a/common/lib/xTrending/store.ts b/common/lib/xTrending/store.ts @@ -43,10 +43,10 @@ // SERVER-ONLY (node:fs). import path from "node:path"; -import { mkdir, readFile, readdir } from "node:fs/promises"; +import { mkdir, readFile, readdir, stat } from "node:fs/promises"; import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; import { readAllPosts, readSeenPostIds, writePosts, type WritePostsResult } from "../posts-server"; -import type { Post } from "../posts"; +import type { Post, PostEngagement, PostRef } from "../posts"; import type { XTrendingRef } from "./config"; // (./watch imports only TYPES of this module: no cycle.) import { describeXTrendingWatch, readXTrendingWatches, type XTrendingWatch } from "./watch"; @@ -658,6 +658,54 @@ export async function readXTrendingReadRecord( return r as XTrendingReadRecord; } +const VIDEO_FILE = /\.(mp4|webm|mov|m4v)$/i; + +function contextPost(raw: unknown): XTrendingContextPost | undefined { + if (!raw || typeof raw !== "object") return undefined; + const r = raw as Record<string, unknown>; + if (typeof r.text !== "string") return undefined; + const out: XTrendingContextPost = { text: r.text }; + for (const k of ["id", "url", "handle", "author", "date"] as const) { + if (typeof r[k] === "string" && r[k]) out[k] = r[k] as string; + } + return out; +} + +// The files of a captured post BY NAME, as its directory holds them: the +// shot, the thread shot, and each picture and video with its size; and the +// context its capture read. Undefined while the post has no capture +// directory. Names only: a file that is neither a picture nor a video (the +// record, an article's files) is not listed. +export async function xTrendingCaptureFiles(channelRoot: string, id: string): Promise<XTrendingPostDetail["capture"] | undefined> { + if (!/^\d+$/.test(id)) return undefined; + const dir = path.join(xTrendingPostsMediaDir(channelRoot), id); + let names: string[]; + try { + names = (await readdir(dir)).sort(); + } catch { + return undefined; + } + const media: XTrendingCaptureFile[] = []; + for (const name of names) { + if (name.startsWith("shot") || name.startsWith("article") || name.startsWith(".")) continue; + const kind = IMAGE_FILE.test(name) ? "image" : VIDEO_FILE.test(name) ? "video" : null; + if (!kind) continue; + const st = await stat(path.join(dir, name)).catch(() => null); + if (!st?.isFile()) continue; + media.push({ name, kind, bytes: st.size }); + } + const read = await readJsonFile(path.join(dir, "capture.json")); + const ctx = read.ok && read.value && typeof read.value === "object" ? (read.value as { context?: { parent?: unknown; quoted?: unknown } }).context : undefined; + const parent = contextPost(ctx?.parent); + const quoted = contextPost(ctx?.quoted); + return { + ...(names.includes(LIBRARY_SHOT_FILENAME) ? { shot: LIBRARY_SHOT_FILENAME } : {}), + ...(names.includes("shot-thread.png") ? { threadShot: "shot-thread.png" } : {}), + media, + ...(parent || quoted ? { context: { ...(parent ? { parent } : {}), ...(quoted ? { quoted } : {}) } } : {}), + }; +} + // ── the listing ──────────────────────────────────────────────────────────── export type XTrendingTopicRow = { @@ -667,6 +715,9 @@ export type XTrendingTopicRow = { // Its watch, once it has been watched (lib/xTrending/watch.ts), with what it // is doing as one sentence. watch?: XTrendingWatch & { sentence: string }; + // With `detail`: its posts by the judgement in force, and how many are gone + // from the page. + counts?: XTrendingCounts; sources: Array<{ trendId: string; url: string; @@ -701,8 +752,43 @@ export type XTrendingPostRow = { // The judgement in force (xTrendingEffectiveJudgement): its own, or its // thread's (`from: "thread"`). Absent: undecided. judgement?: XTrendingJudgement & { from?: "thread" }; + // Only when the listing is asked with `detail` (the Posts library page). + detail?: XTrendingPostDetail; }; +// What a judge view needs beyond a list row (lane posts-library), given only +// when asked for (`detail`): the rest of the post's record, when a read first +// showed it, its OWN judgement beside the one in force, and the files of its +// capture BY NAME (never a path: the names are served from +// trending/posts-media/<id>/ by the door that shows them). +export type XTrendingCaptureFile = { name: string; kind: "image" | "video"; bytes: number }; +export type XTrendingPostDetail = { + post: { + isReply: boolean; + isRepost: boolean; + replyTo?: PostRef; + quoted?: PostRef; + links: string[]; + engagement?: PostEngagement; + mediaCount?: number; + }; + firstSeenAt: string; + ownJudgement?: XTrendingJudgement; + capture?: { + shot?: string; + threadShot?: string; + media: XTrendingCaptureFile[]; + // The capture's reading of the post's page: the post it answers and the + // post it quotes ({handle?, author?, date?, text, url?}), as recorded. + context?: { parent?: XTrendingContextPost; quoted?: XTrendingContextPost }; + }; +}; +export type XTrendingContextPost = { id?: string; url?: string; handle?: string; author?: string; date?: string; text: string }; + +export type XTrendingListState = "unjudged" | XTrendingJudgementState; +export const X_TRENDING_LIST_STATES: readonly XTrendingListState[] = ["unjudged", "keep", "drop", "later"]; +export type XTrendingCounts = { unjudged: number; keep: number; drop: number; later: number; gone: number }; + export type XTrendingListing = { topics: XTrendingTopicRow[]; posts: XTrendingPostRow[]; @@ -710,8 +796,35 @@ export type XTrendingListing = { total: number; // Reads on disk (probes included), newest first. reads: string[]; + // With `detail`: the accounts of the posts the topic narrowing leaves, most + // posts first (before any other filter). + authors?: Array<{ author: string; posts: number }>; + // With `ids`: every matching post's id, uncapped, in listing order (and + // `posts` is empty): what a bulk press over a filter judges. + ids?: string[]; +}; + +// What narrows a listing beyond its topic (lane posts-library). Every one is +// optional, and with none of them the listing is what it always was. +export type XTrendingListFilter = { + // The judgement in force, or none. + state?: XTrendingListState; + // Only posts gone from the page. + gone?: boolean; + // Only posts carrying media. + media?: boolean; + // One account's posts (its handle, any case, with or without "@"). + author?: string; + // Every word, any case, in the post's words, handle or display name. + q?: string; + // Only posts a read FIRST showed after this time (ISO). + since?: string; }; +export function xTrendingSearchWords(q: string | undefined): string[] { + return String(q ?? "").toLowerCase().split(/\s+/).filter(Boolean); +} + export const X_TRENDING_LIST_DEFAULT = 100; export const X_TRENDING_LIST_MAX = 500; @@ -730,7 +843,16 @@ const lastSeen = (m: XTrendingMember) => m.seen.reduce((a, s) => (s.at > a ? s.a // id); `limit` caps them (the newest read's first, in page order). export async function listXTrending( channelRoot: string, - opts: { topic?: string; limit?: number; posts?: ReadonlyArray<Post>; now?: number } = {}, + opts: { + topic?: string; + limit?: number; + posts?: ReadonlyArray<Post>; + now?: number; + offset?: number; + filter?: XTrendingListFilter; + detail?: boolean; + ids?: boolean; + } = {}, ): Promise<XTrendingListing> { const now = opts.now ?? Date.now(); const watches = await readXTrendingWatches(channelRoot); @@ -745,12 +867,37 @@ export async function listXTrending( for (const [id, m] of Object.entries(membership)) { if (archived.has(id)) count.set(m.topic, (count.get(m.topic) ?? 0) + 1); } + const filter = opts.filter ?? {}; + const words = xTrendingSearchWords(filter.q); + const wantAuthor = filter.author ? filter.author.replace(/^@/, "").toLowerCase() : null; + const sinceMs = filter.since ? Date.parse(filter.since) : NaN; + const counts = new Map<string, XTrendingCounts>(); + const authors = new Map<string, number>(); const rows: XTrendingPostRow[] = []; for (const [id, m] of Object.entries(membership)) { - if (opts.topic && m.topic !== opts.topic) continue; const post = archived.get(id); if (!post) continue; const thread = xTrendingThreadOf(post, membership, archived); + const effective = xTrendingEffectiveJudgement(judgements.posts[id], judgements.threads[thread]); + if (opts.detail) { + const c = counts.get(m.topic) ?? { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 }; + c[effective?.state ?? "unjudged"]++; + if (m.gone) c.gone++; + counts.set(m.topic, c); + } + if (opts.topic && m.topic !== opts.topic) continue; + if (opts.detail) authors.set(post.author, (authors.get(post.author) ?? 0) + 1); + const media = m.media ?? { count: post.mediaCount ?? 0, kinds: [] }; + const firstSeenAt = m.seen.reduce((a, s) => (a === "" || s.at < a ? s.at : a), ""); + if (filter.state && (effective?.state ?? "unjudged") !== filter.state) continue; + if (filter.gone && !m.gone) continue; + if (filter.media && !(media.count > 0)) continue; + if (wantAuthor !== null && post.author.toLowerCase() !== wantAuthor) continue; + if (Number.isFinite(sinceMs) && !(Date.parse(firstSeenAt) > sinceMs)) continue; + if (words.length) { + const hay = `${post.text} ${post.author} ${post.authorName ?? ""}`.toLowerCase(); + if (!words.every((w) => hay.includes(w))) continue; + } rows.push({ id, author: post.author, @@ -758,15 +905,29 @@ export async function listXTrending( createdAt: post.createdAt, url: post.url, text: post.text, - media: m.media ?? { count: post.mediaCount ?? 0, kinds: [] }, + media, topic: m.topic, reads: m.seen.map((s) => ({ read: s.read, trendId: s.trendId, at: s.at })), ...(m.gone ? { gone: m.gone } : {}), thread, - ...(() => { - const judgement = xTrendingEffectiveJudgement(judgements.posts[id], judgements.threads[thread]); - return judgement ? { judgement } : {}; - })(), + ...(effective ? { judgement: effective } : {}), + ...(opts.detail + ? { + detail: { + post: { + isReply: post.isReply, + isRepost: post.isRepost, + ...(post.replyTo ? { replyTo: post.replyTo } : {}), + ...(post.quoted ? { quoted: post.quoted } : {}), + links: post.links, + ...(post.engagement ? { engagement: post.engagement } : {}), + ...(post.mediaCount !== undefined ? { mediaCount: post.mediaCount } : {}), + }, + firstSeenAt, + ...(judgements.posts[id] ? { ownJudgement: judgements.posts[id] } : {}), + }, + } + : {}), }); } const rank = (id: string) => { @@ -780,12 +941,15 @@ export async function listXTrending( return rank(a.id) - rank(b.id) || (a.id < b.id ? -1 : 1); }); const limit = Math.min(Math.max(1, opts.limit ?? X_TRENDING_LIST_DEFAULT), X_TRENDING_LIST_MAX); + const offset = Math.max(0, Math.floor(opts.offset ?? 0)); + const page = opts.ids ? [] : rows.slice(offset, offset + limit); return { topics: topics.map((t) => ({ id: t.id, title: t.title, posts: count.get(t.id) ?? 0, ...(watches[t.id] ? { watch: { ...watches[t.id], sentence: describeXTrendingWatch(watches[t.id], now) } } : {}), + ...(opts.detail ? { counts: counts.get(t.id) ?? { unjudged: 0, keep: 0, drop: 0, later: 0, gone: 0 } } : {}), sources: t.sources.map((s) => ({ trendId: s.trendId, url: s.url, @@ -797,19 +961,33 @@ export async function listXTrending( })), // The thumbnail is looked up for the rows returned only (one readdir each). posts: await Promise.all( - rows.slice(0, limit).map(async (row) => { - const [thumbnail, capture] = await Promise.all([ + page.map(async (row) => { + const [thumbnail, capture, files] = await Promise.all([ firstCapturedThumbnail(channelRoot, row.id), xTrendingCaptureSummary(channelRoot, row.id), + opts.detail ? xTrendingCaptureFiles(channelRoot, row.id) : undefined, ]); return { ...row, ...(thumbnail ? { media: { ...row.media, thumbnail } } : {}), ...(capture ? { capture } : {}), + ...(row.detail && files ? { detail: { ...row.detail, capture: files } } : {}), }; }), ), total: rows.length, reads, + ...(opts.detail ? { authors: [...authors].map(([author, posts]) => ({ author, posts })).sort((a, b) => b.posts - a.posts || (a.author < b.author ? -1 : 1)) } : {}), + ...(opts.ids ? { ids: rows.map((r) => r.id) } : {}), + }; +} + +// A library in one line, for the list of libraries (lane posts-library). +export async function summarizeXTrending(channelRoot: string): Promise<{ topics: number; posts: number; unjudged: number }> { + const listing = await listXTrending(channelRoot, { detail: true, ids: true }); + return { + topics: listing.topics.length, + posts: listing.total, + unjudged: listing.topics.reduce((n, t) => n + (t.counts?.unjudged ?? 0), 0), }; } diff --git a/editor/app/api/ops/trending/route.test.ts b/editor/app/api/ops/trending/route.test.ts @@ -0,0 +1,89 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/trending/route.test.ts" +// +// The library's listing over ops, as the judge view asks it (lane +// posts-library), against a temp corpus: the libraries by their marker, the +// filters and pages, ids, detail — and the answer unchanged when none of +// them is asked. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-trending-list-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); + +const READ = "tr-01JA0000000000000000000000"; +const A = "1900000000000001001"; +const B = "1900000000000001002"; + +async function channel(slug: string, config: Record<string, unknown>): Promise<string> { + const dir = path.join(ROOT, "channels", slug); + await mkdir(path.join(dir, "trending", "posts"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); + return dir; +} + +const lib = await channel("trending", { sourceKind: "social", platform: "twitter", xTrending: {}, name: "Trending" }); +await channel("account-x", { sourceKind: "social", platform: "twitter", postFetcher: "x-gallery-dl", socialHandle: "example", url: "https://x.com/example" }); +const row = (id: string, author: string, text: string) => + JSON.stringify({ id, slug: `trending/${id}`, channelSlug: "trending", author, createdAt: "2026-11-16T12:00:00.000Z", uploadDate: "20261116", text, url: `https://x.com/${author}/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [] }); +await writeFile(path.join(lib, "trending", "posts", "2026-11.jsonl"), `${row(A, "teapot_news", "The kettle festival opens.")}\n${row(B, "saucer_fan", "Saucers.")}\n`); +await writeFile(path.join(lib, "trending", "posts-archive"), `twitter ${A}\ntwitter ${B}\n`); +const seen = (rank: number) => [{ read: READ, trendId: "1900000000000000001", at: "2026-11-17T10:00:00.000Z", rank }]; +await writeFile(path.join(lib, "trending", "topics.json"), JSON.stringify({ version: 1, topics: [{ id: "kettles", title: "Kettles", createdAt: "2026-11-17T10:00:00.000Z", sources: [] }] })); +await writeFile(path.join(lib, "trending", "membership.json"), JSON.stringify({ version: 1, posts: { [A]: { topic: "kettles", seen: seen(1) }, [B]: { topic: "kettles", seen: seen(2) } } })); +await writeFile(path.join(lib, "trending", "judgements.json"), JSON.stringify({ version: 1, posts: { [B]: { state: "drop", by: "operator", at: "2026-11-17T12:00:00.000Z" } }, threads: {} })); + +const GET = (await import("./route")).GET; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function get(query: string, token = "test-token") { + const res = await GET(new Request(`http://localhost/api/ops/trending${query}`, { headers: { authorization: `Bearer ${token}` } })); + return { status: res.status, body: (await res.json()) as Record<string, any> }; +} + +test("without a slug: the libraries, by their marker, each in one line; and no other parameter", async () => { + const all = await get(""); + assert.equal(all.status, 200); + assert.deepEqual(all.body, { ok: true, libraries: [{ slug: "trending", name: "Trending", topics: 1, posts: 2, unjudged: 1 }] }); + assert.match((await get("?detail=1")).body.error, /lists the libraries/); + assert.equal((await get("", "wrong")).status, 401); +}); + +test("asked as before, the answer is as before", async () => { + const plain = await get("?slug=trending"); + assert.deepEqual(Object.keys(plain.body).sort(), ["name", "ok", "posts", "reads", "slug", "topics", "total"]); + assert.ok(plain.body.posts.every((p: object) => !("detail" in p))); + assert.ok(plain.body.topics.every((t: object) => !("counts" in t))); +}); + +test("filters, pages, ids and detail", async () => { + assert.deepEqual((await get("?slug=trending&state=drop")).body.posts.map((p: { id: string }) => p.id), [B]); + assert.deepEqual((await get("?slug=trending&state=unjudged")).body.posts.map((p: { id: string }) => p.id), [A]); + assert.deepEqual((await get("?slug=trending&q=KETTLE+festival")).body.posts.map((p: { id: string }) => p.id), [A]); + assert.deepEqual((await get("?slug=trending&author=%40Saucer_Fan")).body.posts.map((p: { id: string }) => p.id), [B]); + assert.deepEqual((await get("?slug=trending&limit=1&offset=1")).body.posts.map((p: { id: string }) => p.id), [B]); + const ids = await get("?slug=trending&ids=1"); + assert.deepEqual(ids.body.ids, [A, B]); + assert.deepEqual(ids.body.posts, []); + const detail = await get("?slug=trending&detail=1"); + assert.deepEqual(detail.body.topics[0].counts, { unjudged: 1, keep: 0, drop: 1, later: 0, gone: 0 }); + assert.equal(detail.body.posts[0].detail.firstSeenAt, "2026-11-17T10:00:00.000Z"); + assert.deepEqual(detail.body.authors, [{ author: "saucer_fan", posts: 1 }, { author: "teapot_news", posts: 1 }]); +}); + +test("refused with a sentence: an unknown parameter, a state, a flag, an author, a time, an offset, a channel that is no library", async () => { + assert.match((await get("?slug=trending&nope=1")).body.error, /unknown parameter "nope"/); + assert.match((await get("?slug=trending&state=maybe")).body.error, /"state" is one of unjudged, keep, drop, later/); + assert.match((await get("?slug=trending&gone=yes")).body.error, /"gone" is 1/); + assert.match((await get("?slug=trending&author=a/b")).body.error, /handle/); + assert.match((await get("?slug=trending&since=soon")).body.error, /"since" is a time/); + assert.match((await get("?slug=trending&offset=-1")).body.error, /"offset"/); + assert.match((await get("?slug=account-x")).body.error, /library/i); + assert.equal((await get("?slug=nope")).status, 404); +}); diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -1,9 +1,16 @@ import path from "node:path"; import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +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, X_TRENDING_LIST_MAX } from "yt-dlp-transcript-common/lib/xTrending/store"; +import { + listXTrending, + summarizeXTrending, + X_TRENDING_LIST_MAX, + X_TRENDING_LIST_STATES, + type XTrendingListFilter, + type XTrendingListState, +} from "yt-dlp-transcript-common/lib/xTrending/store"; import { opsAuth, opsFail } from "../_lib"; export const dynamic = "force-dynamic"; @@ -40,12 +47,48 @@ export const dynamic = "force-dynamic"; // 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. +// +// (no slug) -> { ok, libraries: [{slug, name, topics, posts, unjudged}] } +// every library, by its marker +// offset=<n> 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=<h> one account's posts (any case, with or without "@") +// q=<words> every word, any case, in the words, handle or display name +// since=<ISO> only posts a read FIRST showed after that time +// 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?, capture?: {shot?, +// threadShot?, media: [{name, kind, bytes}], context?: +// {parent?, quoted?}}}. A capture's files are NAMES under +// trending/posts-media/<id>/: this route serves no bytes. +const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "ids", "detail"]; +const FLAGS = new Set(["1", "true"]); + export 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 (!["slug", "topic", "limit"].includes(key)) return opsFail(`unknown parameter "${key}" (slug, topic, limit)`); + 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`); @@ -57,13 +100,50 @@ export async function GET(request: Request) { return opsFail(`"limit" is a whole number, 1–${X_TRENDING_LIST_MAX}`); } } - const paths = getPaths(); + 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<string, boolean> = {}; + 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 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 } : {}), }); if (topic && !listing.topics.some((t) => t.id === topic)) { return opsFail(`${slug} has no topic "${topic}" (its topics: ${listing.topics.map((t) => t.id).join(", ") || "none yet"})`);