Something went wrong. Try again.
Mirror of https://github.com/kualta/site — web infrastructure
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331import { join } from "node:path";import { recordKey } from "../lib/atproto-content.mjs";import { openProfile } from "./browser.mjs";import { deleteCast } from "./farcaster.mjs";import { deleteLensPost } from "./lens.mjs";import { creatorOrigin, findNote } from "./rednote.mjs";const owner = "did:plc:jhvnnnd3adml7t6anu3ay7ip";
export function deletionDestination(platform, value, post) { const url = new URL(value); if (url.protocol !== "https:" || url.username || url.password || url.port) throw new Error("Invalid publication URL"); if (["grain", "bluesky"].includes(platform)) { const key = recordKey(`publisher:${platform}:${post.id}`); const expected = platform === "grain" ? `https://grain.social/profile/${owner}/gallery/${key}` : `https://bsky.app/profile/${owner}/post/${key}`; if (url.href !== expected) throw new Error("Publication URL does not match this post"); return { id: key, url: expected }; } const hosts = { twitter: ["x.com", "www.x.com", "twitter.com", "www.twitter.com"], instagram: ["www.instagram.com", "instagram.com"], youtube: ["youtu.be", "www.youtube.com", "youtube.com"], tiktok: ["www.tiktok.com", "tiktok.com"], xiaohongshu: ["www.xiaohongshu.com", "xiaohongshu.com", "www.rednote.com", "rednote.com"], farcaster: ["farcaster.xyz", "www.farcaster.xyz", "warpcast.com", "www.warpcast.com"], lens: ["hey.xyz", "www.hey.xyz"], }; if (!hosts[platform]?.includes(url.hostname)) throw new Error("Unexpected publication host"); let id; if (platform === "twitter") id = url.pathname.match(/^\/[\w]+\/status\/(\d+)\/?$/)?.[1]; if (platform === "instagram") id = url.pathname.match(/^\/(?:p|reel)\/([\w-]+)\/?$/)?.[1]; if (platform === "tiktok") id = url.pathname.match(/^\/@[\w.-]+\/(?:video|photo)\/(\d+)\/?$/)?.[1]; if (platform === "xiaohongshu") id = url.pathname.match(/^\/explore\/([a-f\d]+)\/?$/)?.[1]; // Publishing links with the full hash; one pasted from the app may have the short one. if (platform === "farcaster") id = url.pathname.match(/^\/[~\w.-]+(?:\/conversations)?\/(0x[a-f\d]{8,40})\/?$/)?.[1]; if (platform === "lens") id = url.pathname.match(/^\/posts\/(\w+)\/?$/)?.[1]; // A post on the channel's Posts tab, rather than a video. const youtubePost = platform === "youtube" && url.hostname !== "youtu.be" && url.pathname.startsWith("/post/"); if (youtubePost) id = url.pathname.match(/^\/post\/([\w-]+)\/?$/)?.[1]; else if (platform === "youtube") id = url.hostname === "youtu.be" ? url.pathname.slice(1) : url.pathname === "/watch" ? url.searchParams.get("v") : url.pathname.match(/^\/shorts\/([\w-]+)\/?$/)?.[1]; if (!id || !/^[\w-]{5,80}$/.test(id)) throw new Error("Cannot identify the published post"); if (youtubePost) return { id, url: `https://www.youtube.com/post/${id}`, post: true }; return { id, url: platform === "youtube" ? `https://studio.youtube.com/video/${id}/edit` : url.origin + url.pathname, };}
export function deletionResponse(platform, responseUrl, method, body, requestBody, id) { if (method !== "POST" && method !== "DELETE") return false; const url = new URL(responseUrl); const host = url.hostname; const path = url.pathname; const hasId = `${url.search} ${requestBody || ""}`.includes(id); if (platform === "twitter") return ( ["x.com", "twitter.com"].includes(host) && /\/DeleteTweet$/.test(path) && hasId && !!body?.data?.delete_tweet && !body.errors?.length ); if (platform === "instagram") return ( ["www.instagram.com", "instagram.com"].includes(host) && /\/(?:web\/create|media)\/\d+\/delete\/$/.test(path) && body?.status === "ok" ); if (platform === "youtube") return ( host === "studio.youtube.com" && /\/delete_video$/.test(path) && hasId && body?.status === "STATUS_SUCCEEDED" ); if (platform === "tiktok") return ( // Studio's request is named its own way; it carries the post's id and TikTok's success code. /(^|\.)tiktok\.com$/.test(host) && /delete/i.test(path) && hasId && body?.status_code === 0 ); if (platform === "xiaohongshu") return ( /(^|\.)(?:xiaohongshu|rednote)\.com$/.test(host) && /\/note\/delete\/?$/.test(path) && hasId && body?.code === 0 && body?.success !== false ); return false;}
// What a post's own page says once it no longer exists: the receipt when a reply isn't recognised.const goneText = { twitter: /this page doesn.t exist|this post was deleted|this post is unavailable/i, instagram: /this page isn.t available/i, tiktok: /(?:video|post) currently unavailable|couldn.t find this (?:video|post)/i, youtube: /this post (?:isn.t|is not|is no longer) available|this post (?:was|has been) (?:deleted|removed)/i,};async function gone(page, platform, destination) { // A video's Studio page never says a post is gone. if (!goneText[platform] || (platform === "youtube" && !destination.post)) return false; try { await page.getByText(goneText[platform]).first().waitFor({ timeout: 8_000 }); return true; } catch { return false; }}export async function deletePublication( deletion, { oauth, stateDir, open = openProfile, farcaster = deleteCast, lens = deleteLensPost },) { const { target, post } = deletion; let submitted = false; let context; let confirmed = false; const responses = new Set(); try { if (target.state !== "succeeded") throw new Error("Only confirmed publications can be deleted"); const destination = deletionDestination(target.platform, target.url, post); if (["grain", "bluesky"].includes(target.platform)) { const { agent } = await oauth.agent(); if (agent.did !== owner) throw new Error("Use kualta’s AT Protocol account"); if (target.platform === "bluesky") { submitted = true; await agent.com.atproto.repo.deleteRecord({ repo: owner, collection: "app.bsky.feed.post", rkey: destination.id, }); } else { const writes = [ { $type: "com.atproto.repo.applyWrites#delete", collection: "social.grain.gallery", rkey: destination.id, }, ]; for (let index = 0; index < post.media.length; index++) { const rkey = recordKey(`publisher:grain:${post.id}:${index}`); for (const collection of [ "social.grain.gallery.item", "social.grain.photo", ...(post.datesTaken?.[index] ? ["social.grain.photo.exif"] : []), ]) writes.push({ $type: "com.atproto.repo.applyWrites#delete", collection, rkey }); } submitted = true; await agent.com.atproto.repo.applyWrites({ repo: owner, writes }); } return { state: "deleted", message: "Deleted from the platform" }; } if (target.platform === "farcaster" || target.platform === "lens") { submitted = true; const remove = target.platform === "farcaster" ? farcaster : lens; return await remove(destination.id, { stateDir, publication: post.id }); } if (target.platform === "xiaohongshu") { context = await open(join(stateDir, target.platform)); const page = context.pages()[0] || (await context.newPage()); page.setDefaultTimeout(15_000); const origin = creatorOrigin(destination.url); const { card } = await findNote(page, origin, destination.id); if (!card) return { state: "deleted", message: "Already removed from the platform" }; const receipt = page.waitForResponse( async (response) => { if (!response.ok()) return false; try { return deletionResponse( target.platform, response.url(), response.request().method(), await response.json(), response.request().postData(), destination.id, ); } catch { return false; } }, { timeout: 30_000 }, ); receipt.catch(() => {}); await card.hover(); await card.locator(".note-card__action-btn--del").click(); submitted = true; await page .locator('[role="dialog"] button, .d-modal button') .filter({ hasText: /^(确定|删除|确认删除|确认)$/ }) .last() .click(); try { await receipt; } catch { if (!(await findNote(page, origin, destination.id)).card) return { state: "deleted", message: "Removed: the note is gone from the creator center" }; throw new Error("Deletion was not confirmed"); } return { state: "deleted", message: "Platform confirmed deletion" }; } context = await open(join(stateDir, target.platform)); const page = context.pages()[0] || (await context.newPage()); page.setDefaultTimeout(15_000); await page.goto(destination.url); if (await gone(page, target.platform, destination)) return { state: "deleted", message: "Already removed from the platform" }; page.on("response", (response) => { if (!submitted || !response.ok()) return; const task = response .json() .then((body) => { if ( deletionResponse( target.platform, response.url(), response.request().method(), body, response.request().postData(), destination.id, ) ) confirmed = true; }) .catch(() => {}) .finally(() => responses.delete(task)); responses.add(task); }); // Use only the menu on the exact publication, never a feed-wide menu. if (target.platform === "twitter") { const article = page .locator('article[data-testid="tweet"]') .filter({ has: page.locator(`a[href$="/status/${destination.id}"]`) }); await article.getByTestId("caret").click(); submitted = true; await page.getByRole("menuitem", { name: /^Delete$/ }).click(); } else if (target.platform === "instagram") { await page.getByRole("button", { name: /^More options$/ }).click(); submitted = true; await page .getByRole("dialog") .getByRole("button", { name: /^Delete$/ }) .click(); } else if (target.platform === "youtube" && destination.post) { await page .locator("ytd-backstage-post-renderer") .first() .getByRole("button", { name: /^Action menu$/ }) .click(); submitted = true; await page.getByRole("menuitem", { name: /^Delete$/ }).or(page.getByText("Delete", { exact: true })).first().click(); } else if (target.platform === "youtube") { await page.getByRole("button", { name: /^Options$/ }).click(); submitted = true; await page.getByText("Delete forever", { exact: true }).click(); await page.getByRole("checkbox").check(); } else if (target.platform === "tiktok") { // A video's own page has no owner menu: TikTok Studio's post list has one on each post's row. await page.goto("https://www.tiktok.com/tiktokstudio/content"); await page .locator(`a[href$="/${destination.id}"]`) .first() .locator('xpath=ancestor::*[.//*[@data-tt="components_ActionCell_Clickable"]][1]') .locator('[data-tt="components_ActionCell_Clickable"]') .click(); submitted = true; await page.getByRole("dialog").getByText("Delete", { exact: true }).click(); } else { await page.getByRole("button", { name: /^(更多|More)$/ }).click(); submitted = true; await page.getByText("删除", { exact: true }).click(); } // X asks in an alert dialog; the others use a plain dialog. const dialog = page.getByRole(target.platform === "twitter" ? "alertdialog" : "dialog"); const confirmation = dialog.getByRole("button", { name: target.platform === "youtube" && !destination.post ? /^Delete forever$/ : target.platform === "xiaohongshu" ? /^(删除|确认删除)$/ : /^Delete$/, }); await confirmation.waitFor({ state: "visible" }); const receipt = page.waitForResponse( async (response) => { if (!submitted || !response.ok()) return false; try { return deletionResponse( target.platform, response.url(), response.request().method(), await response.json(), response.request().postData(), destination.id, ); } catch { return false; } }, { timeout: 30_000 }, ); receipt.catch(() => {}); submitted = true; await confirmation.click(); try { await receipt; } catch { await page.goto(destination.url); if (await gone(page, target.platform, destination)) return { state: "deleted", message: "Removed: the post's page no longer exists" }; throw new Error("Deletion was not confirmed"); } return { state: "deleted", message: "Platform confirmed deletion" }; } catch (error) { await Promise.allSettled([...responses]); if (confirmed) return { state: "deleted", message: "Platform confirmed deletion" }; if (error.rejected) return { state: "failed", message: error.message }; return { state: submitted ? "uncertain" : "failed", message: submitted ? "Deletion was not confirmed. Check the post on the platform before retrying." : "Could not open the post’s delete controls. Check your account and post URL, then retry.", }; } finally { await context?.close().catch(() => {}); }}