// IMPORT ONE POST (release 27 S3b, the editor's `import-post`): one X status // or one Bluesky post, by its URL, into the posts archive of a channel that // archives THAT account on THAT platform — through the channel's own fetcher // (`SocialFetcher.fetchOne`: gallery-dl on the status URL for X, the public // AppView for Bluesky), with the channel's login, written as a fetch writes // (lib/posts-server.ts writePosts: the month shards and the posts archive). // // Refused before any request, with the sentence a caller shows: // - a URL that is not an X status or a Bluesky post; // - no such channel, or one that is not a posts channel; // - a posts channel of another platform, or whose fetcher cannot read one // post; // - a post the URL names as another account's (and, after the read, one the // platform says is another account's); // - the platform held or cooling down after a rate limit (the same holds a // manual download respects) — polite, and the editor runs the read on the // platform's queue, so it never runs beside a fetch of the same source. // A post already archived is not read again. import { xJobContextRefusal } from "../lib/xJobRule"; import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { Post } from "../lib/posts"; import type { ChannelConfig } from "../lib/channelConfig"; import { isSocialChannel } from "../lib/channelConfig"; import { readChannelConfig } from "../controller/channels"; import { alwaysCookies, resolveCookiePolicy, type CookiePolicyInputs } from "../lib/cookiePolicy"; import { readSeenPostIds, writePosts } from "../lib/posts-server"; import { heldPlatformRefusal, platformCooldownRemainingMs } from "../jobs/downloadBackoff"; import { handleFromAccountUrl, parsePostUrl, resolveSocialFetcher, type PostUrlRef, type SocialFetcher, } from "./fetchers"; import { resolveXCookieSourceFor, type XLoginSettings } from "./xBrowserLogin"; // The built-in fetchers register themselves on import, in fetchPosts' order. import "./blueskyFetcher"; import "./xGalleryDlFetcher"; import "./xPlaywrightFetcher"; import "./xNitterFetcher"; import "./xenforoFetcher"; export const IMPORT_POST_RESULT_MARKER = "@@import-post "; export const NOT_A_POST_URL = "not a post URL: give an X status (https://x.com//status/) or a Bluesky post " + "(https://bsky.app/profile//post/, or its at:// URI)"; const PLATFORM_LABEL: Record = { twitter: "X", bluesky: "Bluesky", xenforo: "forum", instagram: "Instagram" }; export type ImportPostPlan = { config: ChannelConfig; fetcher: SocialFetcher; ref: PostUrlRef; handle: string; }; const sameAccount = (a: string, b: string) => a.replace(/^@/, "").toLowerCase() === b.replace(/^@/, "").toLowerCase(); // Everything checked before a job: the plan, or the refusal. `fetcherFor` // is injectable for tests (default: the channel's own, as a fetch resolves it). export async function planImportPost( paths: Paths, slug: string, url: string, opts: { fetcherFor?: (config: ChannelConfig) => SocialFetcher | undefined } = {}, ): Promise<{ ok: true; plan: ImportPostPlan } | { ok: false; error: string; info?: boolean }> { const ref = parsePostUrl(url); if (!ref) return { ok: false, error: NOT_A_POST_URL }; const config = await readChannelConfig(paths, slug); if (!config) return { ok: false, error: `No such channel: ${slug}` }; if (!isSocialChannel(config)) { return { ok: false, error: `${slug} is not a posts channel; import-post imports into a channel that archives an account's posts` }; } // Posts published from a private library: nothing is asked of X for it. if (isSourcelessPostsChannel(config)) return { ok: false, error: SOURCELESS_POSTS_CHANNEL(slug) }; const fetcher = (opts.fetcherFor ?? ((c) => resolveSocialFetcher(c.postFetcher, c.url)))(config); if (!fetcher) return { ok: false, error: `${slug} has no post fetcher` }; const want = PLATFORM_LABEL[ref.platform] ?? ref.platform; const have = PLATFORM_LABEL[fetcher.platform] ?? fetcher.platform; const an = (w: string) => `${/^[aeiox]/i.test(w) ? "an" : "a"} ${w}`; if (fetcher.platform !== ref.platform) { return { ok: false, error: `${slug} is ${an(have)} posts channel, not ${an(want)} one: import ${an(want)} post into ${an(want)} channel`, }; } if (!fetcher.fetchOne) return { ok: false, error: `${slug}'s fetcher (${fetcher.label}) cannot import one post` }; const handle = config.socialHandle ?? handleFromAccountUrl(config.url ?? "") ?? ""; if (!handle) return { ok: false, error: `Could not determine an account handle for ${slug}` }; const named = ref.platform === "twitter" || ref.platform === "instagram" ? ref.handle : ref.actor.startsWith("did:") ? undefined : ref.actor; if (named && !sameAccount(named, handle)) { return { ok: false, error: `the post is @${named}'s; ${slug} archives @${handle}'s posts` }; } return { ok: true, plan: { config, fetcher, ref, handle } }; } // The platform's hold or cooldown, as a manual download meets it, or null. export async function importPostHeld(paths: Paths, platform: string): Promise { const held = await heldPlatformRefusal(platform, "This post import", paths); if (held) return held; const ms = await platformCooldownRemainingMs(platform, paths); return ms > 0 ? `${platform} is in a rate-limit cooldown (${Math.ceil(ms / 1000)}s remaining); the post import will run once it ends` : null; } export type ImportPostResult = { ok: boolean; slug: string; url: string; id: string; written: number; // The post was already in the archive; nothing was read. already?: boolean; post?: Pick; needsCookies?: boolean; error?: string; }; export async function importPost(opts: { paths: Paths; slug: string; url: string; settings: CookiePolicyInputs & XLoginSettings; onLog?: (line: string) => void; signal?: AbortSignal; fetcherFor?: (config: ChannelConfig) => SocialFetcher | undefined; }): Promise { const log = (line: string) => opts.onLog?.(line); const planned = await planImportPost(opts.paths, opts.slug, opts.url, opts.fetcherFor ? { fetcherFor: opts.fetcherFor } : {}); const base = { slug: opts.slug, url: opts.url, id: parsePostUrl(opts.url)?.id ?? "", written: 0 }; if (!planned.ok) return { ...base, ok: false, error: planned.error }; const { config, fetcher, ref, handle } = planned.plan; const channelRoot = path.join(opts.paths.channelsDir, opts.slug); if ((await readSeenPostIds(channelRoot)).has(ref.id)) { log(`Post ${ref.id} is already in ${opts.slug}'s archive; nothing to read.`); return { ...base, ok: true, already: true }; } // X is asked only by the editor's jobs, on X's queue (lib/xJobRule.ts). if (fetcher.platform === "twitter") { const refusal = xJobContextRefusal(`Importing ${ref.url}`, `pnpm ops import-post --json '{"slug":"${opts.slug}","url":"…"}' --wait`); if (refusal) return { ...base, ok: false, error: refusal }; } const policy = resolveCookiePolicy(opts.settings, config); const xLogin = fetcher.platform === "twitter" ? await resolveXCookieSourceFor(opts.paths, opts.settings, policy.cookies) : undefined; log(`Reading ${ref.url} via ${fetcher.label} for ${opts.slug} (@${handle}).`); const res = await fetcher.fetchOne!({ post: ref, channelSlug: opts.slug, signal: opts.signal ?? new AbortController().signal, onLog: log, ...(alwaysCookies(policy) !== undefined ? { cookies: alwaysCookies(policy) } : {}), ...(xLogin?.source ? { cookieSource: xLogin.source } : {}), ...(xLogin?.browserSpec ? { browserCookies: xLogin.browserSpec } : {}), }); if (res.needsCookies) return { ...base, ok: false, needsCookies: true, error: res.error ?? `${fetcher.label} needs a login to read the post` }; if (!res.post) return { ...base, ok: false, error: res.error ?? `the platform has no post ${ref.id} (deleted, private, or never there)` }; if (!sameAccount(res.post.author, handle)) { return { ...base, ok: false, error: `the post is @${res.post.author}'s; ${opts.slug} archives @${handle}'s posts — nothing written` }; } const w = await writePosts(channelRoot, [res.post]); log(`Wrote ${w.written} post(s) to ${opts.slug}'s archive.`); return { ...base, ok: true, written: w.written, post: { id: res.post.id, url: res.post.url, author: res.post.author, createdAt: res.post.createdAt }, }; }