// AN X SEARCH CHANNEL (release 38 lane S, plans/release-38/x-search.md): a saved // X search across accounts — a posts channel on platform "twitter", // `sourceKind: "social"`, whose records are the posts that match ONE query, // from any author. `config.xSearch` holds the query and the dates it is walked // between; the walk itself (search windows, newest first, resumable) is the // older-posts backfill's, with the operator's query in place of `from:`. // // Client-safe and a LEAF (no imports): lib/channelConfig.ts composes the // coercion below into its one set of coercions, and the channel form imports // the URL and query helpers. export type XSearchConfig = { // The query, as X's search box takes it: words, "quoted phrases", OR, // -term, from:/to:/@mention, url:, filter:, lang:, … — passed through as // typed. Never since:/until: (the windows add those) or max_id: and its // kin (the walk pages with max_id). query: string; // The earliest day searched (YYYY-MM-DD, inclusive): the walk stops there. // Absent: it stops after a year of windows in a row with no match. since?: string; // The day the walk starts below (YYYY-MM-DD, exclusive, as X's until:). // Absent: tomorrow — and each later fetch searches what is new since. until?: string; // Each search window's span in months (1–12). Absent: 3, the older walk's. windowMonths?: number; // A language code (en, de, pt-br …): `lang:` is added to the query // unless it names a lang: of its own. lang?: string; // Authors hidden from the leads view ("Never archive"), bare handles in // lower case. The search itself is not narrowed by them. exclude?: string[]; }; export const X_SEARCH_QUERY_MAX = 500; export const X_SEARCH_WINDOW_MONTHS_MAX = 12; // The operators the walk writes itself, refused in a query. since:/until: // bound the windows; max_id: is the walk's resume point (gallery-dl rewrites // it after every page); the others would fight both. const RESERVED_OPERATORS = ["since", "until", "max_id", "since_id", "until_id", "since_time", "until_time"]; const DAY_RE = /^\d{4}-\d{2}-\d{2}$/; const HANDLE_RE = /^[A-Za-z0-9_]{1,50}$/; const LANG_RE = /^[a-z]{2,3}(?:-[a-z]{2,4})?$/; function isDay(v: unknown): v is string { if (typeof v !== "string" || !DAY_RE.test(v)) return false; const ms = Date.parse(`${v}T00:00:00Z`); return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === v; } // The query's terms, split on whitespace OUTSIDE double quotes: a quoted // phrase is one term, quotes kept. Null when a quote is left open. export function xQueryTerms(query: string): string[] | null { const terms: string[] = []; let cur = ""; let quoted = false; for (const ch of query) { if (ch === '"') { quoted = !quoted; cur += ch; continue; } if (!quoted && /\s/.test(ch)) { if (cur) terms.push(cur); cur = ""; continue; } cur += ch; } if (quoted) return null; if (cur) terms.push(cur); return terms; } // The operator name a term uses (`-from:x` → "from"), or null for a plain word // or a phrase. function operatorOf(term: string): string | null { const m = /^[-(]*([A-Za-z_]+):/.exec(term); return m ? m[1].toLowerCase() : null; } // Why this query cannot be an X search channel's, as a sentence — or null. export function xSearchQueryProblem(query: unknown): string | null { if (typeof query !== "string" || !query.trim()) { return "An X search channel needs a query (what you would type in X's search box)."; } const q = query.trim(); if (q.length > X_SEARCH_QUERY_MAX) { return `An X search query is at most ${X_SEARCH_QUERY_MAX} characters (this one is ${q.length}).`; } if (/[\r\n]/.test(q)) return "An X search query is one line."; const terms = xQueryTerms(q); if (!terms) return "The X search query leaves a quote open."; const reserved = [ ...new Set( terms .map(operatorOf) .filter((op): op is string => op !== null && RESERVED_OPERATORS.includes(op)), ), ]; if (reserved.length > 0) { return ( `Take ${reserved.map((op) => `${op}:`).join(", ")} out of the query: ` + "the channel's since and until dates set the search windows, and the walk adds them itself." ); } return null; } // True when the query names a lang: of its own. export function xQueryHasLang(query: string): boolean { return (xQueryTerms(query) ?? []).some((t) => operatorOf(t) === "lang" && !t.startsWith("-")); } // A bare X handle in lower case, or null. export function xLeadHandle(input: unknown): string | null { if (typeof input !== "string") return null; const bare = input.trim().replace(/^@/, ""); return HANDLE_RE.test(bare) ? bare.toLowerCase() : null; } // `config.xSearch`: an object with a valid query, else omitted. The optional // members are omitted one by one when invalid, never repaired; an `until` at // or before `since` drops `until`. export function coerceXSearchConfig(v: unknown): XSearchConfig | undefined { if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; const r = v as Record; if (xSearchQueryProblem(r.query) !== null) return undefined; const out: XSearchConfig = { query: (r.query as string).trim() }; if (isDay(r.since)) out.since = r.since; if (isDay(r.until) && !(out.since && r.until <= out.since)) out.until = r.until; if ( typeof r.windowMonths === "number" && Number.isInteger(r.windowMonths) && r.windowMonths >= 1 && r.windowMonths <= X_SEARCH_WINDOW_MONTHS_MAX ) { out.windowMonths = r.windowMonths; } if (typeof r.lang === "string" && LANG_RE.test(r.lang.trim().toLowerCase())) { out.lang = r.lang.trim().toLowerCase(); } if (Array.isArray(r.exclude)) { const handles = [...new Set(r.exclude.map(xLeadHandle).filter((h): h is string => h !== null))]; if (handles.length > 0) out.exclude = handles; } return out; } // An X search channel: a posts channel on platform "twitter" with a query. // Structural, so this leaf needs no import of the channel config's type. export function isXSearchChannel( config: { sourceKind?: string; platform?: string; xSearch?: unknown } | null | undefined, ): boolean { return config?.sourceKind === "social" && config.platform === "twitter" && Boolean(config.xSearch); } const X_HOST_RE = /^(?:www\.|mobile\.)?(?:x|twitter)\.com$/i; // X's search page for a query — the URL a search channel stores, and the one // gallery-dl's search extractor matches. The query is percent-encoded whole // (gallery-dl turns "+" into a space BEFORE it unquotes, so an encoded "+" // survives); `f=live` is X's "Latest" tab. export function xSearchUrl(query: string): string { return `https://x.com/search?q=${encodeURIComponent(query)}&f=live`; } // The query of an X search page URL (x.com or twitter.com /search?q=…), or // null. `+` reads as a space, as X writes it. export function xSearchQueryOfUrl(input: string | undefined | null): string | null { if (!input) return null; let u: URL; try { u = new URL(input.trim()); } catch { return null; } if (!X_HOST_RE.test(u.hostname)) return null; if (u.pathname.replace(/\/+$/, "") !== "/search") return null; const q = u.searchParams.get("q"); return q && q.trim() ? q.trim() : null; } export function isXSearchUrl(input: string | undefined | null): boolean { return xSearchQueryOfUrl(input) !== null; } // A search channel's config from a URL copied out of X: its query, with any // one since:/until: day lifted out into the channel's dates (X writes them in // the query; the channel keeps them apart). Anything else stays in the query, // to be refused or kept by xSearchQueryProblem. export function xSearchFromUrl(input: string | undefined | null): XSearchConfig | null { const raw = xSearchQueryOfUrl(input); if (raw === null) return null; const terms = xQueryTerms(raw); if (!terms) return { query: raw }; const out: XSearchConfig = { query: "" }; const kept: string[] = []; for (const term of terms) { const m = /^(since|until):(\d{4}-\d{2}-\d{2})$/i.exec(term); const key = m?.[1].toLowerCase() as "since" | "until" | undefined; if (m && key && isDay(m[2]) && out[key] === undefined) { out[key] = m[2]; continue; } kept.push(term); } out.query = kept.join(" "); return out; } // What the walk's saved state belongs to: a change of query or language starts // the walk afresh. The dates are not in it — widening them walks only what is // newly in range. export function xSearchQueryKey(config: Pick): string { return `${config.query.trim()}${config.lang ? ` lang:${config.lang}` : ""}`; } // The query for ONE window: the operator's terms, the language, the window's // days and, inside a window, the resume point. Throws on a query the channel // could not hold (the fetcher never runs one). export function xSearchWindowQuery( config: Pick, position: { since: string; until: string; maxId?: string }, ): string { const problem = xSearchQueryProblem(config.query); if (problem) throw new Error(problem); if (!isDay(position.since) || !isDay(position.until)) { throw new Error(`"${position.since} – ${position.until}" is not a window of days`); } const terms = [config.query.trim()]; if (config.lang && !xQueryHasLang(config.query)) terms.push(`lang:${config.lang}`); terms.push(`since:${position.since}`, `until:${position.until}`); if (position.maxId) { if (!/^\d+$/.test(position.maxId)) throw new Error(`"${position.maxId}" is not a post id`); terms.push(`max_id:${position.maxId}`); } return terms.join(" "); } // One line for the channel page and the ops read. export function describeXSearch(config: XSearchConfig): string { const range = config.since && config.until ? `${config.since} – ${config.until}` : config.since ? `since ${config.since}` : config.until ? `before ${config.until}` : "all dates"; return `${config.query}${config.lang ? ` (lang ${config.lang})` : ""} · ${range}`; }