// An X SEARCH channel's fetch (release 38 lane S): one walk of search windows // over the channel's query, newest first, resumable, landing the matching // posts — from any author — in the channel's own posts archive (the same shard // writer, deduped by status id within the channel, as every posts channel). // The walk is the older walk's (fetcher.fetchSearch; xGalleryDlFetcher.ts): // the same windows, the same 45–120 s between them and 4–10 s between // requests, the same login, the same 3-hour budget, a 429 waited out by // gallery-dl as there. lib/xSearch/walk.ts plans which stretch a run walks. // // Called by fetchPosts for a channel with `config.xSearch`, after its own // checks (the channel exists, is social, has a fetcher); the walk's state is // posts-state.json's `search`, every other field carried as it was. import path from "node:path"; import type { Paths } from "../lib/paths"; import type { Post } from "../lib/posts"; import type { ChannelConfig } from "../lib/channelConfig"; import { readPostFetchState, readSeenPostIds, writePostFetchState, writePosts, type OlderBackfillPosition, type XSearchWalkState, } from "../lib/posts-server"; import { describeXSearch, type XSearchConfig } from "../lib/xSearch/config"; import { coverAfterWalk, planXSearchWalk, xSearchStateFor, type XSearchWalk, } from "../lib/xSearch/walk"; import type { SocialFetcher } from "../social/fetchers"; import type { XCookieSource } from "../social/xCookieSource"; import { patchChannelConfig } from "./channels"; // Refused for a search channel, before any job: it has no timeline and no // older walk — its fetch IS the window walk. export const X_SEARCH_OLDER_REFUSAL = "An X search channel has one walk, its search windows: run a plain fetch. " + "Its dates are the channel's since and until (Configure)."; export function xSearchFetcherProblem( fetcher: Pick | undefined, ): string | null { if (!fetcher) return "This channel has no post fetcher."; return typeof fetcher.fetchSearch === "function" ? null : `${fetcher.label} cannot walk an X search (use x-gallery-dl).`; } export type FetchXSearchOptions = { paths: Paths; slug: string; config: ChannelConfig & { xSearch: XSearchConfig }; fetcher: SocialFetcher; // Start the walk afresh: forget what was covered (posts are kept and // deduped, so this re-reads, never duplicates). full?: boolean; limit?: number; cookies?: string; cookieSource?: XCookieSource; browserCookies?: string; windowPauseMs?: number; now?: Date; onLog?: (line: string) => void; signal?: AbortSignal; drain?: AbortSignal; }; export type FetchXSearchResult = { ok: boolean; written: number; skipped: number; complete: boolean; error?: string; needsCookies?: boolean; drained?: boolean; }; export async function fetchXSearchPosts(opts: FetchXSearchOptions): Promise { const { paths, slug, config, fetcher } = opts; const log = (line: string) => opts.onLog?.(line); const search = config.xSearch; const channelRoot = path.join(paths.channelsDir, slug); const problem = xSearchFetcherProblem(fetcher); if (problem) return { ok: false, written: 0, skipped: 0, complete: false, error: problem }; const priorState = await readPostFetchState(channelRoot); const stored = opts.full ? undefined : priorState?.search; let state: XSearchWalkState = xSearchStateFor(search, stored); if (priorState?.search && state !== priorState.search) { log( opts.full ? "Starting the search walk afresh, as asked (posts already archived are kept)." : "The query changed since the last walk: starting it afresh (posts already archived are kept).", ); } const plan = planXSearchWalk(search, state, opts.now); const seenIds = await readSeenPostIds(channelRoot); const startedAt = new Date().toISOString(); const stateNow = (extra: Partial = {}): XSearchWalkState => ({ ...state, lastRunAt: startedAt, ...extra, }); // Every field but the search walk's (and the run stamps) is carried as it // was. const save = (search: XSearchWalkState, more: { lastFetchedCount?: number; lastError?: string; needsCookies?: boolean } = {}) => writePostFetchState(channelRoot, { ...(priorState ?? {}), lastFetchedAt: startedAt, ...(more.lastFetchedCount !== undefined ? { lastFetchedCount: more.lastFetchedCount } : {}), lastError: more.lastError, needsCookies: more.needsCookies, search, }); if (plan.kind === "none") { log(`X search ${describeXSearch(search)}: ${plan.reason}. Nothing to walk.`); await save(stateNow({ lastWritten: 0 }), { lastFetchedCount: 0 }); await patchChannelConfig(paths, slug, { lastSyncedAt: new Date().toISOString() }); return { ok: true, written: 0, skipped: 0, complete: true }; } const walk: XSearchWalk = plan.walk; log( `Fetching X search ${describeXSearch(search)} for ${slug} via ${fetcher.label}: ` + ({ resume: "resuming the walk at ", first: "the first walk, starting at ", new: "the new days, starting at ", earlier: "the earlier days, starting at ", } as const)[plan.kind] + `${walk.since} – ${walk.until}` + (walk.floor ? `, down to ${walk.floor}` : ", until a year of windows holds no match") + `; ${seenIds.size} already archived.`, ); let written = 0; let skipped = 0; const shards = new Set(); const walkAt = (at: OlderBackfillPosition): XSearchWalk => ({ top: walk.top, ...(walk.floor !== undefined ? { floor: walk.floor } : {}), since: at.since, until: at.until, emptyWindows: at.emptyWindows, ...(at.maxId ? { maxId: at.maxId } : {}), }); const onCheckpoint = async (cp: { posts: Post[]; position: OlderBackfillPosition }) => { const w = await writePosts(channelRoot, cp.posts); written += w.written; skipped += w.skipped; for (const shard of w.shards) shards.add(shard); state = { ...state, walk: walkAt(cp.position) }; await save(stateNow({ lastWritten: written }), { lastFetchedCount: written }); if (w.written > 0) log(`Saved ${w.written} matching post(s) (${written} so far this run); resume point recorded.`); }; const controller = new AbortController(); let result; try { result = await fetcher.fetchSearch!({ channelSlug: slug, seenIds, cookies: opts.cookies, cookieSource: opts.cookieSource, browserCookies: opts.browserCookies, limit: opts.limit, signal: opts.signal ?? controller.signal, drain: opts.drain, onLog: log, position: { since: walk.since, until: walk.until, emptyWindows: walk.emptyWindows, ...(walk.maxId ? { maxId: walk.maxId } : {}) }, ...(walk.floor !== undefined ? { floor: walk.floor } : {}), ...(search.windowMonths ? { months: search.windowMonths } : {}), search: { query: search.query, ...(search.lang ? { lang: search.lang } : {}) }, windowPauseMs: opts.windowPauseMs, onCheckpoint, }); } catch (err) { const message = (err as Error).message; log(`[error] ${message}`); // Whatever was checkpointed is on disk with its position; keep that one. state = { ...state, walk: state.walk ?? walk }; await save(stateNow({ lastWritten: written, lastError: message }), { lastFetchedCount: written, lastError: message }); return { ok: false, written, skipped, complete: false, error: message }; } const final = await writePosts(channelRoot, result.posts); written += final.written; skipped += final.skipped; for (const shard of final.shards) shards.add(shard); if (result.complete) { const covered = coverAfterWalk(state, walk, result.position.since); const reason = plan.kind === "new" || (plan.kind === "resume" && state.coveredUntil) ? `searched down to ${walk.floor ?? result.position.since}` : (result.completeReason ?? "walked to its end"); const { walk: _done, ...rest } = state; void _done; state = { ...rest, ...covered, completeReason: reason, completedAt: new Date().toISOString() }; } else { state = { ...state, walk: walkAt(result.position) }; } log( `Wrote ${written} matching post(s), skipped ${skipped} already archived` + (shards.size > 0 ? ` (shards: ${[...shards].join(", ")})` : "") + (result.complete ? ` — searched ${state.coveredSince} – ${state.coveredUntil}.` : ` — the next fetch resumes at ${state.walk!.since} – ${state.walk!.until}.`), ); if (result.error) log(`[error] ${result.error}`); await save( stateNow({ lastWritten: written, ...(result.error ? { lastError: result.error } : { lastError: undefined }) }), { lastFetchedCount: written, ...(result.error ? { lastError: result.error } : {}), ...(result.needsCookies ? { needsCookies: true } : {}), }, ); // The scheduler paces a search channel as any posts channel: by its // lastSyncedAt. A patch, re-read at write time (fetchPosts' rule). await patchChannelConfig(paths, slug, { lastSyncedAt: new Date().toISOString() }); return { ok: !result.error, written, skipped, complete: result.complete, ...(result.needsCookies ? { needsCookies: true } : {}), ...(result.error ? { error: result.error } : {}), ...(result.drained ? { drained: true } : {}), }; }