Extension reads the 'You've hit the daily post limit' banner and fails the job instead of reporting success. Backend then disables x_clips_auto_post, skips remaining scheduled clips, and cancels queued engage.post jobs. Co-authored-by: Cursor <cursoragent@cursor.com>
1898 lines
62 KiB
TypeScript
1898 lines
62 KiB
TypeScript
import type { JobKind, NoticeRow, ProfileData, TweetRow, UserRow } from "@x2/shared";
|
||
|
||
type PageJobKind = JobKind | "cleanup.collect_users";
|
||
type RunResult = { ok: boolean; result?: unknown; error?: string };
|
||
|
||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||
|
||
function reportProgress(
|
||
jobId: string,
|
||
current: number,
|
||
total: number,
|
||
message?: string,
|
||
) {
|
||
chrome.runtime
|
||
.sendMessage({
|
||
type: "content.progress",
|
||
jobId,
|
||
progress: { current, total, message },
|
||
})
|
||
.catch(() => {});
|
||
}
|
||
|
||
function reportResult(jobId: string, result: RunResult) {
|
||
chrome.runtime
|
||
.sendMessage({
|
||
type: "content.jobResult",
|
||
jobId,
|
||
...result,
|
||
})
|
||
.catch(() => {});
|
||
}
|
||
|
||
function textOf(el: Element | null | undefined): string {
|
||
return (el?.textContent || "").trim();
|
||
}
|
||
|
||
function parseCount(raw?: string | null): number | undefined {
|
||
if (!raw) return undefined;
|
||
const s = raw.replace(/,/g, "").trim().toLowerCase();
|
||
const m = s.match(/^([\d.]+)\s*([kmb])?$/i);
|
||
if (!m) {
|
||
const n = Number(s);
|
||
return Number.isFinite(n) ? n : undefined;
|
||
}
|
||
const n = Number(m[1]);
|
||
const u = (m[2] || "").toLowerCase();
|
||
if (u === "k") return Math.round(n * 1e3);
|
||
if (u === "m") return Math.round(n * 1e6);
|
||
if (u === "b") return Math.round(n * 1e9);
|
||
return n;
|
||
}
|
||
|
||
const RESERVED = new Set([
|
||
"home",
|
||
"explore",
|
||
"notifications",
|
||
"messages",
|
||
"i",
|
||
"settings",
|
||
"compose",
|
||
"search",
|
||
"login",
|
||
"signup",
|
||
"tos",
|
||
"privacy",
|
||
"logout",
|
||
"following",
|
||
"followers",
|
||
]);
|
||
|
||
function usernameFromHref(href: string | null | undefined): string | undefined {
|
||
if (!href) return undefined;
|
||
const m = href.match(/^\/([^/?#]+)/);
|
||
const u = m?.[1];
|
||
if (!u || RESERVED.has(u.toLowerCase()) || u.startsWith("i")) return undefined;
|
||
return u;
|
||
}
|
||
|
||
function getLoggedInUsername(): string | undefined {
|
||
// 1) 左侧栏个人主页入口(最稳)
|
||
const profile = document.querySelector(
|
||
'a[data-testid="AppTabBar_Profile_Link"]',
|
||
) as HTMLAnchorElement | null;
|
||
const fromProfile = usernameFromHref(profile?.getAttribute("href"));
|
||
if (fromProfile) return fromProfile;
|
||
|
||
// 2) 账号切换按钮 aria-label 常见含 @handle
|
||
const switcher = document.querySelector(
|
||
'[data-testid="SideNav_AccountSwitcher_Button"]',
|
||
);
|
||
const aria = switcher?.getAttribute("aria-label") || "";
|
||
const ariaMatch = aria.match(/@([A-Za-z0-9_]{1,15})/);
|
||
if (ariaMatch?.[1]) return ariaMatch[1];
|
||
|
||
// 3) 侧栏头像容器 testid: UserAvatar-Container-{username}
|
||
const avatar = document.querySelector(
|
||
'[data-testid^="UserAvatar-Container-"]',
|
||
);
|
||
const testid = avatar?.getAttribute("data-testid") || "";
|
||
const avMatch = testid.match(/^UserAvatar-Container-(.+)$/);
|
||
if (avMatch?.[1] && !RESERVED.has(avMatch[1].toLowerCase())) {
|
||
return avMatch[1];
|
||
}
|
||
|
||
// 4) 任意指向本人的 following 链接(登录后侧栏偶发)
|
||
const following = document.querySelector(
|
||
'a[href$="/following"]',
|
||
) as HTMLAnchorElement | null;
|
||
const fromFollowing = usernameFromHref(
|
||
(following?.getAttribute("href") || "").replace(/\/following$/, ""),
|
||
);
|
||
if (fromFollowing) return fromFollowing;
|
||
|
||
// 5) 页面脚本 / 初始状态里的 screen_name
|
||
try {
|
||
const html = document.documentElement.innerHTML.slice(0, 500_000);
|
||
const m =
|
||
html.match(/"screen_name":"([A-Za-z0-9_]{1,15})"/) ||
|
||
html.match(/"screen_name","([A-Za-z0-9_]{1,15})"/);
|
||
if (m?.[1]) return m[1];
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
|
||
return undefined;
|
||
}
|
||
|
||
function getAccountPayload() {
|
||
const username = getLoggedInUsername();
|
||
if (!username) return undefined;
|
||
|
||
let displayName = username;
|
||
const switcher = document.querySelector(
|
||
'[data-testid="SideNav_AccountSwitcher_Button"]',
|
||
);
|
||
const aria = switcher?.getAttribute("aria-label") || "";
|
||
// e.g. "Account menu. Current account: Name @user."
|
||
const nameFromAria = aria.match(/Current account:\s*(.+?)\s*@/i)?.[1]?.trim();
|
||
if (nameFromAria) displayName = nameFromAria;
|
||
else {
|
||
const nameEl = document.querySelector('[data-testid="UserName"]');
|
||
const raw = textOf(nameEl).split("@")[0]?.trim();
|
||
if (raw) displayName = raw;
|
||
}
|
||
|
||
const avatar = document.querySelector(
|
||
'[data-testid="SideNav_AccountSwitcher_Button"] img',
|
||
) as HTMLImageElement | null;
|
||
|
||
return {
|
||
username,
|
||
displayName,
|
||
avatarUrl: avatar?.src,
|
||
};
|
||
}
|
||
|
||
async function getAccountPayloadReady(timeoutMs = 4000) {
|
||
const start = Date.now();
|
||
while (Date.now() - start < timeoutMs) {
|
||
const account = getAccountPayload();
|
||
if (account?.username) return account;
|
||
// 已登录导航出现但 profile 还没 hydrate
|
||
if (document.querySelector('a[data-testid="AppTabBar_Home_Link"]')) {
|
||
await sleep(250);
|
||
continue;
|
||
}
|
||
await sleep(250);
|
||
}
|
||
return getAccountPayload();
|
||
}
|
||
|
||
async function waitForSelector(sel: string, timeoutMs = 15000): Promise<Element> {
|
||
const start = Date.now();
|
||
while (Date.now() - start < timeoutMs) {
|
||
const el = document.querySelector(sel);
|
||
if (el) return el;
|
||
await sleep(300);
|
||
}
|
||
throw new Error(`等待元素超时: ${sel}`);
|
||
}
|
||
|
||
async function scrollCollectUserCells(
|
||
jobId: string,
|
||
limit: number,
|
||
): Promise<UserRow[]> {
|
||
await waitForSelector('[data-testid="UserCell"], [data-testid="emptyState"]');
|
||
const map = new Map<string, UserRow>();
|
||
let idle = 0;
|
||
let stalledScrolls = 0;
|
||
|
||
while (map.size < limit && idle < 14) {
|
||
const before = map.size;
|
||
const scrollY = window.scrollY;
|
||
document.querySelectorAll('[data-testid="UserCell"]').forEach((cell) => {
|
||
const links = Array.from(
|
||
cell.querySelectorAll('a[href^="/"]'),
|
||
) as HTMLAnchorElement[];
|
||
let username: string | undefined;
|
||
for (const a of links) {
|
||
username = usernameFromHref(a.getAttribute("href"));
|
||
if (username) break;
|
||
}
|
||
if (!username) return;
|
||
const name = textOf(cell.querySelector('[dir="ltr"] span'));
|
||
const bio = textOf(cell.querySelector('[data-testid="UserDescription"]'));
|
||
const followsYou = !!cell.querySelector(
|
||
'[data-testid="userFollowIndicator"]',
|
||
);
|
||
const verified = !!cell.querySelector('svg[data-testid="icon-verified"]');
|
||
map.set(username.toLowerCase(), {
|
||
username,
|
||
name: name || undefined,
|
||
bio: bio || undefined,
|
||
followsYou,
|
||
verified,
|
||
});
|
||
});
|
||
reportProgress(jobId, map.size, limit, `已采集 ${map.size}`);
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1100 + Math.random() * 900);
|
||
if (map.size === before) {
|
||
idle += 1;
|
||
if (Math.abs(window.scrollY - scrollY) < 40) stalledScrolls += 1;
|
||
else stalledScrolls = 0;
|
||
if (stalledScrolls >= 3) break;
|
||
} else {
|
||
idle = 0;
|
||
stalledScrolls = 0;
|
||
}
|
||
}
|
||
|
||
return Array.from(map.values()).slice(0, limit);
|
||
}
|
||
|
||
async function scrapeProfile(): Promise<ProfileData> {
|
||
await waitForSelector('[data-testid="UserName"]');
|
||
const handle =
|
||
location.pathname.split("/").filter(Boolean)[0] || getLoggedInUsername();
|
||
if (!handle) throw new Error("无法确定用户名");
|
||
|
||
const nameBlock = document.querySelector('[data-testid="UserName"]');
|
||
const bio = textOf(document.querySelector('[data-testid="UserDescription"]'));
|
||
const following = textOf(
|
||
document.querySelector('a[href$="/following"] span span'),
|
||
);
|
||
const followers = textOf(
|
||
document.querySelector('a[href$="/followers"] span span'),
|
||
);
|
||
|
||
const locationText =
|
||
textOf(document.querySelector('[data-testid="UserLocation"]')) || undefined;
|
||
const websiteEl = document.querySelector(
|
||
'[data-testid="UserUrl"] a',
|
||
) as HTMLAnchorElement | null;
|
||
const website =
|
||
websiteEl?.getAttribute("href") ||
|
||
textOf(document.querySelector('[data-testid="UserUrl"]')) ||
|
||
undefined;
|
||
const joined =
|
||
textOf(document.querySelector('[data-testid="UserJoinDate"]')) || undefined;
|
||
|
||
let tweetsCount: number | undefined;
|
||
const headerStats = document.querySelectorAll(
|
||
'[data-testid="UserName"] ~ div, [href$="/with_replies"]',
|
||
);
|
||
void headerStats;
|
||
const pageText = document.body.innerText.slice(0, 4000);
|
||
const postsMatch = pageText.match(/([\d,.]+[KMB]?)\s*(Posts|posts|帖子)/);
|
||
if (postsMatch) tweetsCount = parseCount(postsMatch[1]);
|
||
|
||
return {
|
||
username: handle,
|
||
name: textOf(nameBlock).split("@")[0]?.trim(),
|
||
bio: bio || undefined,
|
||
location: locationText,
|
||
website,
|
||
joined,
|
||
followingCount: parseCount(following),
|
||
followersCount: parseCount(followers),
|
||
tweetsCount,
|
||
verified: !!document.querySelector('[data-testid="UserName"] svg'),
|
||
};
|
||
}
|
||
|
||
function extractMediaFromArticle(art: Element): string[] {
|
||
const urls = new Set<string>();
|
||
art.querySelectorAll("video").forEach((v) => {
|
||
const src = v.getAttribute("src") || v.querySelector("source")?.getAttribute("src");
|
||
if (src && /^https?:/i.test(src)) urls.add(src);
|
||
});
|
||
art.querySelectorAll('img[src*="pbs.twimg.com"], img[src*="video.twimg.com"]').forEach((img) => {
|
||
const src = img.getAttribute("src");
|
||
if (!src || /profile_images|emoji/i.test(src)) return;
|
||
urls.add(src.replace(/&name=\w+/, "&name=large").replace(/\?format=\w+/, "?format=jpg"));
|
||
});
|
||
art.querySelectorAll('a[href*="/photo/"], a[href*="/video/"]').forEach((a) => {
|
||
const href = (a as HTMLAnchorElement).href;
|
||
if (href) urls.add(href);
|
||
});
|
||
return Array.from(urls);
|
||
}
|
||
|
||
function parseTweetArticle(art: Element): TweetRow | null {
|
||
const text = textOf(art.querySelector('[data-testid="tweetText"]'));
|
||
const time = art.querySelector("time")?.getAttribute("datetime") || undefined;
|
||
const link = art.querySelector(
|
||
'a[href*="/status/"]',
|
||
) as HTMLAnchorElement | null;
|
||
const url = link?.href;
|
||
if (!text && !url) return null;
|
||
const author = url?.split("/")[3];
|
||
const id = url?.match(/\/status\/(\d+)/)?.[1];
|
||
|
||
const group = art.querySelector('[role="group"]');
|
||
const replyLabel =
|
||
group
|
||
?.querySelector('[data-testid="reply"]')
|
||
?.getAttribute("aria-label") || "";
|
||
const rtLabel =
|
||
group
|
||
?.querySelector('[data-testid="retweet"]')
|
||
?.getAttribute("aria-label") || "";
|
||
const likeLabel =
|
||
group
|
||
?.querySelector('[data-testid="like"], [data-testid="unlike"]')
|
||
?.getAttribute("aria-label") || "";
|
||
const viewsLabel =
|
||
art.querySelector('a[href$="/analytics"]')?.getAttribute("aria-label") ||
|
||
group?.querySelector('[data-testid="app-text-transition-container"]')?.parentElement?.getAttribute("aria-label") ||
|
||
"";
|
||
const parseAriaCount = (label: string) => {
|
||
const m = label.match(/([\d,.]+[KMB]?)/i);
|
||
return m ? parseCount(m[1]) : undefined;
|
||
};
|
||
const hashtags = Array.from(
|
||
(text || "").matchAll(/#([\p{L}\p{N}_]+)/gu),
|
||
).map((m) => m[1]);
|
||
const mediaUrls = extractMediaFromArticle(art);
|
||
|
||
return {
|
||
id,
|
||
text: text || undefined,
|
||
createdAt: time,
|
||
url,
|
||
author,
|
||
replies: parseAriaCount(replyLabel),
|
||
retweets: parseAriaCount(rtLabel),
|
||
likes: parseAriaCount(likeLabel),
|
||
views: parseAriaCount(viewsLabel),
|
||
mediaUrls: mediaUrls.length ? mediaUrls : undefined,
|
||
hashtags: hashtags.length ? hashtags : undefined,
|
||
};
|
||
}
|
||
|
||
async function scrapeTweets(
|
||
jobId: string,
|
||
limit: number,
|
||
opts?: { mediaOnly?: boolean },
|
||
): Promise<TweetRow[]> {
|
||
await waitForSelector('article[data-testid="tweet"], [data-testid="emptyState"]');
|
||
const rows: TweetRow[] = [];
|
||
const seen = new Set<string>();
|
||
let idle = 0;
|
||
|
||
while (rows.length < limit && idle < 14) {
|
||
const before = rows.length;
|
||
document.querySelectorAll('article[data-testid="tweet"]').forEach((art) => {
|
||
const row = parseTweetArticle(art);
|
||
if (!row) return;
|
||
if (opts?.mediaOnly && !(row.mediaUrls && row.mediaUrls.length)) return;
|
||
const key = row.url || `${row.text}:${row.createdAt}`;
|
||
if (seen.has(key)) return;
|
||
seen.add(key);
|
||
rows.push(row);
|
||
});
|
||
reportProgress(
|
||
jobId,
|
||
rows.length,
|
||
limit,
|
||
opts?.mediaOnly ? `已采媒体推文 ${rows.length}` : `已采集推文 ${rows.length}`,
|
||
);
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1100 + Math.random() * 900);
|
||
if (rows.length === before) idle += 1;
|
||
else idle = 0;
|
||
}
|
||
|
||
return rows.slice(0, limit);
|
||
}
|
||
|
||
async function scrapeThread(jobId: string, limit: number): Promise<TweetRow[]> {
|
||
await waitForSelector('article[data-testid="tweet"], [data-testid="emptyState"]');
|
||
// Expand "Show more" / thread continuations a few times
|
||
for (let i = 0; i < 6; i++) {
|
||
const expanders = Array.from(
|
||
document.querySelectorAll('[role="button"], button, [data-testid="tweet-text-show-more-link"]'),
|
||
) as HTMLElement[];
|
||
let clicked = false;
|
||
for (const el of expanders) {
|
||
const t = textOf(el);
|
||
if (/show more|show this thread|显示更多|显示这条串|查看更多/i.test(t)) {
|
||
el.click();
|
||
clicked = true;
|
||
await sleep(700);
|
||
}
|
||
}
|
||
if (!clicked) break;
|
||
}
|
||
return scrapeTweets(jobId, limit);
|
||
}
|
||
|
||
async function scrapeNotifications(
|
||
jobId: string,
|
||
limit: number,
|
||
): Promise<NoticeRow[]> {
|
||
await waitForSelector(
|
||
'[data-testid="primaryColumn"], [data-testid="emptyState"], [data-testid="cellInnerDiv"]',
|
||
);
|
||
const rows: NoticeRow[] = [];
|
||
const seen = new Set<string>();
|
||
let idle = 0;
|
||
|
||
while (rows.length < limit && idle < 12) {
|
||
const before = rows.length;
|
||
const cells = Array.from(
|
||
document.querySelectorAll(
|
||
'[data-testid="notification"], [data-testid="cellInnerDiv"]',
|
||
),
|
||
);
|
||
for (const cell of cells) {
|
||
const text = textOf(cell).slice(0, 400);
|
||
if (!text || text.length < 8) continue;
|
||
const actors = Array.from(
|
||
cell.querySelectorAll('a[href^="/"]'),
|
||
)
|
||
.map((a) => usernameFromHref((a as HTMLAnchorElement).getAttribute("href")))
|
||
.filter((u): u is string => !!u);
|
||
const uniqueActors = Array.from(new Set(actors)).slice(0, 5);
|
||
const link = cell.querySelector(
|
||
'a[href*="/status/"]',
|
||
) as HTMLAnchorElement | null;
|
||
const url = link?.href;
|
||
const lower = text.toLowerCase();
|
||
const type = /liked|赞了|喜欢了/i.test(text)
|
||
? "like"
|
||
: /followed|关注了|started following/i.test(text)
|
||
? "follow"
|
||
: /replied|回复了|mention|提到/i.test(text)
|
||
? "reply"
|
||
: /retweet|repost|转推|转发/i.test(text)
|
||
? "retweet"
|
||
: /quoted|引用/i.test(text)
|
||
? "quote"
|
||
: "other";
|
||
const key = `${type}:${url || ""}:${text.slice(0, 80)}`;
|
||
if (seen.has(key)) continue;
|
||
// skip pure timeline tweet cells without notification flavor when possible
|
||
if (
|
||
cell.getAttribute("data-testid") !== "notification" &&
|
||
!/liked|followed|replied|retweet|repost|mentioned|赞了|关注了|回复|转推|提到/i.test(
|
||
lower,
|
||
)
|
||
) {
|
||
continue;
|
||
}
|
||
seen.add(key);
|
||
rows.push({
|
||
text,
|
||
actors: uniqueActors.length ? uniqueActors : undefined,
|
||
type,
|
||
url,
|
||
});
|
||
if (rows.length >= limit) break;
|
||
}
|
||
reportProgress(jobId, rows.length, limit, `已采通知 ${rows.length}`);
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1100 + Math.random() * 800);
|
||
if (rows.length === before) idle += 1;
|
||
else idle = 0;
|
||
}
|
||
|
||
return rows.slice(0, limit);
|
||
}
|
||
|
||
async function unfollowUsers(
|
||
jobId: string,
|
||
usernames: string[],
|
||
delayMs: { min: number; max: number },
|
||
): Promise<{ unfollowed: string[]; skipped: string[] }> {
|
||
await waitForSelector('[data-testid="UserCell"], [data-testid="emptyState"]');
|
||
const targets = new Set(usernames.map((u) => u.toLowerCase()));
|
||
const unfollowed: string[] = [];
|
||
const skipped: string[] = [];
|
||
let rounds = 0;
|
||
|
||
while (unfollowed.length + skipped.length < targets.size && rounds < 40) {
|
||
rounds += 1;
|
||
const cells = Array.from(
|
||
document.querySelectorAll('[data-testid="UserCell"]'),
|
||
);
|
||
|
||
for (const cell of cells) {
|
||
const a = cell.querySelector('a[href^="/"]') as HTMLAnchorElement | null;
|
||
const username = (a?.getAttribute("href") || "")
|
||
.split("/")
|
||
.filter(Boolean)[0];
|
||
if (!username) continue;
|
||
const key = username.toLowerCase();
|
||
if (!targets.has(key)) continue;
|
||
if (unfollowed.includes(username) || skipped.includes(username)) continue;
|
||
|
||
const btn = cell.querySelector(
|
||
'[data-testid$="-unfollow"]',
|
||
) as HTMLElement | null;
|
||
if (!btn) {
|
||
skipped.push(username);
|
||
continue;
|
||
}
|
||
|
||
btn.click();
|
||
await sleep(600);
|
||
const confirm = document.querySelector(
|
||
'[data-testid="confirmationSheetConfirm"]',
|
||
) as HTMLElement | null;
|
||
confirm?.click();
|
||
unfollowed.push(username);
|
||
reportProgress(
|
||
jobId,
|
||
unfollowed.length,
|
||
targets.size,
|
||
`已取关 @${username}`,
|
||
);
|
||
const wait =
|
||
delayMs.min + Math.random() * Math.max(0, delayMs.max - delayMs.min);
|
||
await sleep(wait);
|
||
}
|
||
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1500);
|
||
}
|
||
|
||
return { unfollowed, skipped };
|
||
}
|
||
|
||
async function unfollowVisible(
|
||
jobId: string,
|
||
limit: number,
|
||
delayMs: { min: number; max: number },
|
||
onlyNonFollowers: boolean,
|
||
): Promise<{ unfollowed: string[]; skipped: string[]; mode: string }> {
|
||
await waitForSelector(
|
||
'[data-testid="UserCell"], [data-testid$="-unfollow"], [data-testid="emptyState"]',
|
||
);
|
||
const unfollowed: string[] = [];
|
||
const skipped: string[] = [];
|
||
const seen = new Set<string>();
|
||
let idle = 0;
|
||
|
||
while (unfollowed.length < limit && idle < 14) {
|
||
let acted = false;
|
||
const cells = Array.from(
|
||
document.querySelectorAll('[data-testid="UserCell"]'),
|
||
);
|
||
for (const cell of cells) {
|
||
if (unfollowed.length >= limit) break;
|
||
const links = Array.from(
|
||
cell.querySelectorAll('a[href^="/"]'),
|
||
) as HTMLAnchorElement[];
|
||
let username: string | undefined;
|
||
for (const a of links) {
|
||
username = usernameFromHref(a.getAttribute("href"));
|
||
if (username) break;
|
||
}
|
||
if (!username || seen.has(username.toLowerCase())) continue;
|
||
seen.add(username.toLowerCase());
|
||
|
||
const followsYou = !!cell.querySelector(
|
||
'[data-testid="userFollowIndicator"]',
|
||
);
|
||
if (onlyNonFollowers && followsYou) {
|
||
skipped.push(username);
|
||
continue;
|
||
}
|
||
|
||
const btn = cell.querySelector(
|
||
'[data-testid$="-unfollow"]',
|
||
) as HTMLElement | null;
|
||
if (!btn) {
|
||
skipped.push(username);
|
||
continue;
|
||
}
|
||
|
||
btn.click();
|
||
await sleep(600);
|
||
const confirm = document.querySelector(
|
||
'[data-testid="confirmationSheetConfirm"]',
|
||
) as HTMLElement | null;
|
||
confirm?.click();
|
||
unfollowed.push(username);
|
||
acted = true;
|
||
reportProgress(
|
||
jobId,
|
||
unfollowed.length,
|
||
limit,
|
||
`已取关 @${username}`,
|
||
);
|
||
await sleep(delayBetween(delayMs));
|
||
}
|
||
|
||
if (!acted) {
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1400);
|
||
idle += 1;
|
||
} else {
|
||
idle = 0;
|
||
}
|
||
}
|
||
|
||
return {
|
||
unfollowed,
|
||
skipped,
|
||
mode: onlyNonFollowers ? "non_followers_visible" : "all_visible",
|
||
};
|
||
}
|
||
|
||
function delayBetween(delayMs: { min: number; max: number }) {
|
||
return delayMs.min + Math.random() * Math.max(0, delayMs.max - delayMs.min);
|
||
}
|
||
|
||
async function clickUserAction(
|
||
action: "mute" | "unmute" | "block" | "unblock",
|
||
): Promise<boolean> {
|
||
const more =
|
||
(document.querySelector('[data-testid="userActions"]') as HTMLElement | null) ||
|
||
(document.querySelector('[aria-label*="More"]') as HTMLElement | null);
|
||
if (!more) return false;
|
||
more.click();
|
||
await sleep(700);
|
||
|
||
const items = Array.from(
|
||
document.querySelectorAll('[role="menuitem"], [data-testid="Dropdown"] div[role="button"]'),
|
||
) as HTMLElement[];
|
||
const needle =
|
||
action === "mute"
|
||
? /^(?!.*un).*mute|(?:^|[^取消])静音/i
|
||
: action === "unmute"
|
||
? /unmute|取消静音|解除静音/i
|
||
: action === "block"
|
||
? /^(?!.*un).*block|(?:^|[^取消解除])屏蔽|拉黑/i
|
||
: /unblock|取消屏蔽|解除屏蔽|取消拉黑/i;
|
||
// Prefer exact-ish Chinese/English labels; fall back to simple includes
|
||
const simple =
|
||
action === "mute"
|
||
? /mute|静音/i
|
||
: action === "unmute"
|
||
? /unmute|取消静音|解除静音/i
|
||
: action === "block"
|
||
? /block|屏蔽|拉黑/i
|
||
: /unblock|取消屏蔽|解除屏蔽|取消拉黑/i;
|
||
let item = items.find((el) => {
|
||
const t = textOf(el);
|
||
if (action === "mute" && /unmute|取消静音|解除静音/i.test(t)) return false;
|
||
if (action === "block" && /unblock|取消屏蔽|解除屏蔽/i.test(t)) return false;
|
||
if (action === "unmute" || action === "unblock") return simple.test(t);
|
||
return simple.test(t) && !/unmute|unblock|取消|解除/i.test(t);
|
||
});
|
||
void needle;
|
||
if (!item) {
|
||
document.body.click();
|
||
return false;
|
||
}
|
||
item.click();
|
||
await sleep(500);
|
||
const confirm = document.querySelector(
|
||
'[data-testid="confirmationSheetConfirm"]',
|
||
) as HTMLElement | null;
|
||
confirm?.click();
|
||
await sleep(400);
|
||
return true;
|
||
}
|
||
|
||
/** Called after background navigated to each profile */
|
||
async function muteOrBlockCurrent(
|
||
action: "mute" | "unmute" | "block" | "unblock",
|
||
): Promise<{ ok: boolean }> {
|
||
await waitForSelector('[data-testid="UserName"], [data-testid="userActions"]');
|
||
const ok = await clickUserAction(action);
|
||
if (!ok) {
|
||
const tip =
|
||
action === "mute"
|
||
? "找不到静音入口"
|
||
: action === "unmute"
|
||
? "找不到取消静音入口"
|
||
: action === "block"
|
||
? "找不到屏蔽入口"
|
||
: "找不到取消屏蔽入口";
|
||
throw new Error(tip);
|
||
}
|
||
return { ok: true };
|
||
}
|
||
|
||
async function likeVisible(
|
||
jobId: string,
|
||
limit: number,
|
||
delayMs?: { min: number; max: number },
|
||
): Promise<number> {
|
||
let liked = 0;
|
||
const seen = new Set<Element>();
|
||
let idle = 0;
|
||
const d = delayMs || { min: 2500, max: 5000 };
|
||
while (liked < limit && idle < 10) {
|
||
const buttons = Array.from(
|
||
document.querySelectorAll('[data-testid="like"]'),
|
||
).filter((b) => !seen.has(b));
|
||
if (!buttons.length) {
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1500);
|
||
idle += 1;
|
||
continue;
|
||
}
|
||
idle = 0;
|
||
for (const btn of buttons) {
|
||
if (liked >= limit) break;
|
||
seen.add(btn);
|
||
(btn as HTMLElement).click();
|
||
liked += 1;
|
||
reportProgress(jobId, liked, limit, `已点赞 ${liked}`);
|
||
await sleep(delayBetween(d));
|
||
}
|
||
}
|
||
return liked;
|
||
}
|
||
|
||
async function unlikeVisible(
|
||
jobId: string,
|
||
limit: number,
|
||
delayMs?: { min: number; max: number },
|
||
): Promise<number> {
|
||
let unliked = 0;
|
||
const seen = new Set<Element>();
|
||
let idle = 0;
|
||
const d = delayMs || { min: 2000, max: 4500 };
|
||
while (unliked < limit && idle < 12) {
|
||
const buttons = Array.from(
|
||
document.querySelectorAll('[data-testid="unlike"]'),
|
||
).filter((b) => !seen.has(b));
|
||
if (!buttons.length) {
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1400);
|
||
idle += 1;
|
||
continue;
|
||
}
|
||
idle = 0;
|
||
for (const btn of buttons) {
|
||
if (unliked >= limit) break;
|
||
seen.add(btn);
|
||
(btn as HTMLElement).click();
|
||
unliked += 1;
|
||
reportProgress(jobId, unliked, limit, `已取消点赞 ${unliked}`);
|
||
await sleep(delayBetween(d));
|
||
}
|
||
}
|
||
return unliked;
|
||
}
|
||
|
||
async function followVisible(
|
||
jobId: string,
|
||
limit: number,
|
||
delayMs?: { min: number; max: number },
|
||
): Promise<number> {
|
||
let followed = 0;
|
||
const seen = new Set<string>();
|
||
let idle = 0;
|
||
const d = delayMs || { min: 2500, max: 5000 };
|
||
while (followed < limit && idle < 10) {
|
||
const buttons = Array.from(
|
||
document.querySelectorAll('[data-testid$="-follow"]'),
|
||
) as HTMLElement[];
|
||
let acted = false;
|
||
for (const btn of buttons) {
|
||
const testid = btn.getAttribute("data-testid") || "";
|
||
if (testid.endsWith("-unfollow")) continue;
|
||
const cell = btn.closest('[data-testid="UserCell"]');
|
||
const art = btn.closest('article[data-testid="tweet"]');
|
||
let username = "";
|
||
if (cell) {
|
||
const a = cell.querySelector('a[href^="/"]') as HTMLAnchorElement | null;
|
||
username = (a?.getAttribute("href") || "").split("/").filter(Boolean)[0] || "";
|
||
} else if (art) {
|
||
const link = art.querySelector(
|
||
'a[href*="/status/"]',
|
||
) as HTMLAnchorElement | null;
|
||
username = link?.href?.split("/")[3] || "";
|
||
}
|
||
if (!username || seen.has(username)) continue;
|
||
seen.add(username);
|
||
btn.click();
|
||
followed += 1;
|
||
acted = true;
|
||
reportProgress(jobId, followed, limit, `已关注 @${username}`);
|
||
await sleep(delayBetween(d));
|
||
if (followed >= limit) break;
|
||
}
|
||
if (!acted) {
|
||
window.scrollTo(0, document.body.scrollHeight);
|
||
await sleep(1500);
|
||
idle += 1;
|
||
} else {
|
||
idle = 0;
|
||
}
|
||
}
|
||
return followed;
|
||
}
|
||
|
||
async function likeCurrentTweet(): Promise<boolean> {
|
||
await waitForSelector('article[data-testid="tweet"], [data-testid="like"], [data-testid="unlike"]');
|
||
if (document.querySelector('[data-testid="unlike"]')) return true;
|
||
const btn = document.querySelector('[data-testid="like"]') as HTMLElement | null;
|
||
if (!btn) return false;
|
||
btn.click();
|
||
await sleep(800);
|
||
return true;
|
||
}
|
||
|
||
async function unlikeCurrentTweet(): Promise<boolean> {
|
||
await waitForSelector('article[data-testid="tweet"], [data-testid="like"], [data-testid="unlike"]');
|
||
if (document.querySelector('[data-testid="like"]') && !document.querySelector('[data-testid="unlike"]')) {
|
||
return true;
|
||
}
|
||
const btn = document.querySelector('[data-testid="unlike"]') as HTMLElement | null;
|
||
if (!btn) return false;
|
||
btn.click();
|
||
await sleep(800);
|
||
return true;
|
||
}
|
||
|
||
async function bookmarkCurrent(): Promise<{ ok: boolean; already?: boolean }> {
|
||
await waitForSelector(
|
||
'article[data-testid="tweet"], [data-testid="bookmark"], [data-testid="removeBookmark"]',
|
||
);
|
||
if (document.querySelector('[data-testid="removeBookmark"]')) {
|
||
return { ok: true, already: true };
|
||
}
|
||
const btn = document.querySelector('[data-testid="bookmark"]') as HTMLElement | null;
|
||
if (!btn) throw new Error("找不到收藏按钮");
|
||
btn.click();
|
||
await sleep(800);
|
||
return { ok: true };
|
||
}
|
||
|
||
async function unbookmarkCurrent(): Promise<{ ok: boolean; already?: boolean }> {
|
||
await waitForSelector(
|
||
'article[data-testid="tweet"], [data-testid="bookmark"], [data-testid="removeBookmark"]',
|
||
);
|
||
if (document.querySelector('[data-testid="bookmark"]') && !document.querySelector('[data-testid="removeBookmark"]')) {
|
||
return { ok: true, already: true };
|
||
}
|
||
const btn = document.querySelector('[data-testid="removeBookmark"]') as HTMLElement | null;
|
||
if (!btn) throw new Error("找不到取消收藏按钮");
|
||
btn.click();
|
||
await sleep(800);
|
||
return { ok: true };
|
||
}
|
||
|
||
async function followCurrentProfile(): Promise<{
|
||
ok: boolean;
|
||
username?: string;
|
||
already?: boolean;
|
||
}> {
|
||
await waitForSelector('[data-testid="UserName"], [data-testid$="-follow"], [data-testid$="-unfollow"]');
|
||
const handle =
|
||
location.pathname.split("/").filter(Boolean)[0] || getLoggedInUsername();
|
||
if (document.querySelector('[data-testid$="-unfollow"]')) {
|
||
return { ok: true, username: handle, already: true };
|
||
}
|
||
const buttons = Array.from(
|
||
document.querySelectorAll('[data-testid$="-follow"]'),
|
||
) as HTMLElement[];
|
||
const btn = buttons.find((b) => {
|
||
const id = b.getAttribute("data-testid") || "";
|
||
return id.endsWith("-follow") && !id.endsWith("-unfollow");
|
||
});
|
||
if (!btn) throw new Error("找不到关注按钮");
|
||
btn.click();
|
||
await sleep(900);
|
||
return { ok: true, username: handle };
|
||
}
|
||
|
||
async function unretweetCurrent(): Promise<{ ok: boolean }> {
|
||
await waitForSelector(
|
||
'article[data-testid="tweet"], [data-testid="unretweet"], [data-testid="retweet"]',
|
||
);
|
||
const undo =
|
||
(document.querySelector('[data-testid="unretweet"]') as HTMLElement | null) ||
|
||
null;
|
||
if (!undo) {
|
||
// already not retweeted
|
||
if (document.querySelector('[data-testid="retweet"]')) {
|
||
return { ok: true };
|
||
}
|
||
throw new Error("找不到取消转推按钮");
|
||
}
|
||
undo.click();
|
||
await sleep(600);
|
||
const confirm =
|
||
(document.querySelector('[data-testid="unretweetConfirm"]') as HTMLElement | null) ||
|
||
(Array.from(document.querySelectorAll('[role="menuitem"]')).find((el) =>
|
||
/undo|取消转推|undo repost|remove/i.test(textOf(el)),
|
||
) as HTMLElement | undefined);
|
||
confirm?.click();
|
||
await sleep(900);
|
||
return { ok: true };
|
||
}
|
||
|
||
async function deleteCurrentTweet(): Promise<{ ok: boolean }> {
|
||
await waitForSelector('article[data-testid="tweet"]');
|
||
const art = document.querySelector('article[data-testid="tweet"]');
|
||
if (!art) throw new Error("找不到推文");
|
||
const caret =
|
||
(art.querySelector('[data-testid="caret"]') as HTMLElement | null) ||
|
||
(art.querySelector('[aria-label*="More"]') as HTMLElement | null);
|
||
if (!caret) throw new Error("找不到更多菜单");
|
||
caret.click();
|
||
await sleep(700);
|
||
const items = Array.from(
|
||
document.querySelectorAll('[role="menuitem"]'),
|
||
) as HTMLElement[];
|
||
const del = items.find((el) => /delete|删除/i.test(textOf(el)));
|
||
if (!del) {
|
||
document.body.click();
|
||
throw new Error("找不到删除入口(可能不是自己的帖)");
|
||
}
|
||
del.click();
|
||
await sleep(500);
|
||
const confirm = document.querySelector(
|
||
'[data-testid="confirmationSheetConfirm"]',
|
||
) as HTMLElement | null;
|
||
if (!confirm) throw new Error("找不到删除确认");
|
||
confirm.click();
|
||
await sleep(1000);
|
||
return { ok: true };
|
||
}
|
||
|
||
async function pinOrUnpinCurrent(action: "pin" | "unpin"): Promise<{ ok: boolean }> {
|
||
await waitForSelector('article[data-testid="tweet"]');
|
||
const art = document.querySelector('article[data-testid="tweet"]');
|
||
if (!art) throw new Error("找不到推文");
|
||
const caret =
|
||
(art.querySelector('[data-testid="caret"]') as HTMLElement | null) ||
|
||
(art.querySelector('[aria-label*="More"]') as HTMLElement | null);
|
||
if (!caret) throw new Error("找不到更多菜单");
|
||
caret.click();
|
||
await sleep(700);
|
||
const items = Array.from(
|
||
document.querySelectorAll('[role="menuitem"]'),
|
||
) as HTMLElement[];
|
||
const needle =
|
||
action === "pin"
|
||
? /pin to your profile|置顶到主页|固定到个人资料|pin this/i
|
||
: /unpin from profile|取消置顶|取消固定|unpin/i;
|
||
const anti =
|
||
action === "pin"
|
||
? /unpin|取消置顶|取消固定/i
|
||
: /pin to your profile|置顶到主页|固定到个人资料/i;
|
||
const item = items.find((el) => {
|
||
const t = textOf(el);
|
||
if (anti.test(t) && action === "pin") return false;
|
||
return needle.test(t);
|
||
});
|
||
if (!item) {
|
||
document.body.click();
|
||
throw new Error(
|
||
action === "pin" ? "找不到置顶入口(需是自己的帖)" : "找不到取消置顶入口",
|
||
);
|
||
}
|
||
item.click();
|
||
await sleep(500);
|
||
const confirm = document.querySelector(
|
||
'[data-testid="confirmationSheetConfirm"]',
|
||
) as HTMLElement | null;
|
||
confirm?.click();
|
||
await sleep(900);
|
||
return { ok: true };
|
||
}
|
||
|
||
async function copyTweetLink(): Promise<{ ok: boolean; url?: string }> {
|
||
await waitForSelector('article[data-testid="tweet"]');
|
||
const art = document.querySelector('article[data-testid="tweet"]');
|
||
if (!art) throw new Error("找不到推文");
|
||
const statusLink = art.querySelector(
|
||
'a[href*="/status/"]',
|
||
) as HTMLAnchorElement | null;
|
||
const direct = statusLink?.href;
|
||
const share =
|
||
(art.querySelector('[data-testid="share"]') as HTMLElement | null) ||
|
||
(art.querySelector('[aria-label*="Share"]') as HTMLElement | null);
|
||
if (share) {
|
||
share.click();
|
||
await sleep(700);
|
||
const items = Array.from(
|
||
document.querySelectorAll('[role="menuitem"]'),
|
||
) as HTMLElement[];
|
||
const copyItem = items.find((el) =>
|
||
/copy link|复制链接|copy post/i.test(textOf(el)),
|
||
);
|
||
if (copyItem) {
|
||
copyItem.click();
|
||
await sleep(500);
|
||
return { ok: true, url: direct };
|
||
}
|
||
document.body.click();
|
||
}
|
||
if (direct) {
|
||
try {
|
||
await navigator.clipboard.writeText(direct);
|
||
return { ok: true, url: direct };
|
||
} catch {
|
||
return { ok: true, url: direct };
|
||
}
|
||
}
|
||
throw new Error("无法复制链接");
|
||
}
|
||
|
||
async function retweetCurrent(quoteText?: string): Promise<{ ok: boolean; mode: string }> {
|
||
await waitForSelector('article[data-testid="tweet"], [data-testid="retweet"]');
|
||
const btn = document.querySelector('[data-testid="retweet"]') as HTMLElement | null;
|
||
if (!btn) throw new Error("找不到转推按钮");
|
||
btn.click();
|
||
await sleep(700);
|
||
|
||
if (quoteText && quoteText.trim()) {
|
||
const quoteItem = Array.from(
|
||
document.querySelectorAll('[role="menuitem"]'),
|
||
).find((el) => /quote|引用/i.test(textOf(el))) as HTMLElement | undefined;
|
||
if (!quoteItem) throw new Error("找不到引用入口");
|
||
quoteItem.click();
|
||
await sleep(900);
|
||
const box =
|
||
(document.querySelector('[data-testid="tweetTextarea_0"]') as HTMLElement | null) ||
|
||
(document.querySelector('div[role="textbox"][contenteditable="true"]') as HTMLElement | null);
|
||
if (!box) throw new Error("找不到引用输入框");
|
||
box.focus();
|
||
document.execCommand("insertText", false, quoteText);
|
||
await sleep(500);
|
||
const send = (document.querySelector('[data-testid="tweetButton"]') ||
|
||
document.querySelector('[data-testid="tweetButtonInline"]')) as HTMLButtonElement | null;
|
||
if (!send || send.disabled) throw new Error("引用发送按钮不可用");
|
||
send.click();
|
||
await sleep(1200);
|
||
return { ok: true, mode: "quote" };
|
||
}
|
||
|
||
const confirm =
|
||
(document.querySelector('[data-testid="retweetConfirm"]') as HTMLElement | null) ||
|
||
(Array.from(document.querySelectorAll('[role="menuitem"]')).find((el) =>
|
||
/repost|转推|retweet/i.test(textOf(el)),
|
||
) as HTMLElement | undefined);
|
||
if (!confirm) throw new Error("找不到确认转推");
|
||
confirm.click();
|
||
await sleep(900);
|
||
return { ok: true, mode: "retweet" };
|
||
}
|
||
|
||
async function replyCurrent(text: string): Promise<{ ok: boolean; text: string }> {
|
||
await waitForSelector('article[data-testid="tweet"], [data-testid="reply"]');
|
||
const replyBtn = document.querySelector('[data-testid="reply"]') as HTMLElement | null;
|
||
replyBtn?.click();
|
||
await sleep(1000);
|
||
const box =
|
||
(document.querySelector('[data-testid="tweetTextarea_0"]') as HTMLElement | null) ||
|
||
(document.querySelector('div[role="textbox"][contenteditable="true"]') as HTMLElement | null);
|
||
if (!box) throw new Error("找不到回复输入框");
|
||
box.focus();
|
||
const okInsert = document.execCommand("insertText", false, text);
|
||
if (!okInsert) {
|
||
box.textContent = text;
|
||
box.dispatchEvent(new InputEvent("input", { bubbles: true, data: text }));
|
||
}
|
||
await sleep(500);
|
||
const send = (document.querySelector('[data-testid="tweetButton"]') ||
|
||
document.querySelector('[data-testid="tweetButtonInline"]')) as HTMLButtonElement | null;
|
||
if (!send || send.getAttribute("aria-disabled") === "true" || send.disabled) {
|
||
throw new Error("回复发送按钮不可用");
|
||
}
|
||
send.click();
|
||
await sleep(1200);
|
||
return { ok: true, text };
|
||
}
|
||
|
||
function findTweetComposeBox(): HTMLElement | null {
|
||
const dialog =
|
||
(document.querySelector('[role="dialog"]') as HTMLElement | null) ||
|
||
(document.querySelector('[data-testid="mask"]')?.parentElement as HTMLElement | null);
|
||
const roots: Array<ParentNode> = [];
|
||
if (dialog) roots.push(dialog);
|
||
roots.push(document);
|
||
|
||
for (const root of roots) {
|
||
const box =
|
||
(root.querySelector('[data-testid="tweetTextarea_0"]') as HTMLElement | null) ||
|
||
(root.querySelector('[data-testid="tweetTextarea_1"]') as HTMLElement | null);
|
||
if (box) return box;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function composerPlain(box: HTMLElement): string {
|
||
return (box.innerText || box.textContent || "").replace(/\u200b/g, "").trim();
|
||
}
|
||
|
||
function captionOnly(s: string): string {
|
||
return s
|
||
.replace(/https?:\/\/\S+/gi, "")
|
||
.replace(/#\w+/g, "")
|
||
.replace(/\s+/g, " ")
|
||
.trim();
|
||
}
|
||
|
||
/** Reject empty / URL-only; allow short CJK names (旧规则 length>=12 会误杀「小夏妹妹」). */
|
||
function isCaptionAcceptable(body: string): boolean {
|
||
const raw = String(body || "").trim();
|
||
if (!raw) return false;
|
||
if (/^https?:\/\/\S+$/i.test(raw)) return false;
|
||
const token = captionOnly(raw);
|
||
if (!token) return false;
|
||
const cjk = (token.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g) || []).join("").length;
|
||
if (cjk >= 2) return true;
|
||
return token.replace(/\s+/g, "").length >= 6;
|
||
}
|
||
|
||
function captionMatchToken(got: string, token: string): boolean {
|
||
const t = captionOnly(token);
|
||
const g = captionOnly(got);
|
||
if (!t || !g) return false;
|
||
const needle = t.slice(0, Math.min(10, t.length));
|
||
return g.includes(needle);
|
||
}
|
||
|
||
function looksLikePlaceholder(s: string): boolean {
|
||
return /^(what('|’)s happening|what is happening|有什么新鲜事|发生什么了|有什麼新鮮事)/i.test(
|
||
s.trim(),
|
||
);
|
||
}
|
||
|
||
/** Draft.js / X composer prefers paste events over execCommand. */
|
||
function dispatchPaste(box: HTMLElement, text: string): boolean {
|
||
const dt = new DataTransfer();
|
||
dt.setData("text/plain", text);
|
||
try {
|
||
const ev = new ClipboardEvent("paste", {
|
||
bubbles: true,
|
||
cancelable: true,
|
||
clipboardData: dt,
|
||
});
|
||
return box.dispatchEvent(ev);
|
||
} catch {
|
||
const ev = new Event("paste", { bubbles: true, cancelable: true });
|
||
Object.defineProperty(ev, "clipboardData", { value: dt });
|
||
return box.dispatchEvent(ev);
|
||
}
|
||
}
|
||
|
||
async function clearComposer(box: HTMLElement): Promise<void> {
|
||
box.focus();
|
||
await sleep(120);
|
||
const sel = window.getSelection();
|
||
try {
|
||
const range = document.createRange();
|
||
range.selectNodeContents(box);
|
||
sel?.removeAllRanges();
|
||
sel?.addRange(range);
|
||
} catch {
|
||
document.execCommand("selectAll", false);
|
||
}
|
||
await sleep(40);
|
||
document.execCommand("delete", false);
|
||
// Also try backspace select-all via keyboard for Draft
|
||
document.execCommand("selectAll", false);
|
||
document.execCommand("delete", false);
|
||
await sleep(80);
|
||
}
|
||
|
||
/** X free-tier daily post cap banner inside composer / toast. */
|
||
function readXDailyPostLimitError(): string | null {
|
||
const needles = [
|
||
/you've hit the daily post limit/i,
|
||
/hit the daily post limit/i,
|
||
/daily post limit/i,
|
||
/subscribe to premium for higher limits/i,
|
||
/upgrade to unlock/i,
|
||
/达到.?每日.?发帖.?上限/,
|
||
/今日发帖.?上限/,
|
||
/发帖次数已达上限/,
|
||
/发帖已达上限/,
|
||
];
|
||
const roots: HTMLElement[] = [];
|
||
const dialog = document.querySelector('[role="dialog"]') as HTMLElement | null;
|
||
if (dialog) roots.push(dialog);
|
||
roots.push(document.body);
|
||
for (const root of roots) {
|
||
const text = String(root.innerText || root.textContent || "");
|
||
for (const re of needles) {
|
||
if (re.test(text)) {
|
||
return "X_DAILY_POST_LIMIT: You've hit the daily post limit";
|
||
}
|
||
}
|
||
}
|
||
for (const el of document.querySelectorAll(
|
||
'[role="alert"], [data-testid="toast"], [data-testid="error"]',
|
||
)) {
|
||
const text = String((el as HTMLElement).innerText || el.textContent || "");
|
||
for (const re of needles) {
|
||
if (re.test(text)) {
|
||
return "X_DAILY_POST_LIMIT: You've hit the daily post limit";
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function readComposerOverBy(): number | null {
|
||
// X shows remaining (or negative overage) near the toolbar when close to / over limit
|
||
const root =
|
||
(document.querySelector('[role="dialog"]') as HTMLElement | null) ||
|
||
document.body;
|
||
const nodes = Array.from(
|
||
root.querySelectorAll('[role="progressbar"], span, div'),
|
||
) as HTMLElement[];
|
||
for (const el of nodes) {
|
||
const label = `${el.getAttribute("aria-valuetext") || ""} ${el.getAttribute("aria-label") || ""}`;
|
||
const mLabel = label.match(/(-?\d+)\s*(character|字符|字)/i);
|
||
if (mLabel) {
|
||
const n = Number(mLabel[1]);
|
||
// If it's "remaining", negative means over; if absolute overage in Chinese UI "超出N"
|
||
if (n < 0) return Math.abs(n);
|
||
}
|
||
const t = (el.textContent || "").trim();
|
||
if (/^-\d{1,3}$/.test(t)) return Math.abs(Number(t));
|
||
}
|
||
// Chinese toast / helper text
|
||
const all = root.innerText || "";
|
||
const m = all.match(/超出\s*(\d+)\s*个?字符/);
|
||
if (m) return Number(m[1]);
|
||
return null;
|
||
}
|
||
|
||
async function setComposerText(box: HTMLElement, text: string): Promise<boolean> {
|
||
// Refuse to type raw URL-only payloads
|
||
if (/^https?:\/\/\S+$/i.test(text.trim())) return false;
|
||
// Single-line only — newlines create Draft blocks and inflate X's counter
|
||
const flat = text.replace(/\s+/g, " ").trim();
|
||
|
||
await clearComposer(box);
|
||
box.focus();
|
||
// One paste — avoid chunked insertText (known Draft.js phantom count bug)
|
||
dispatchPaste(box, flat);
|
||
await sleep(400);
|
||
|
||
let got = composerPlain(box);
|
||
if (looksLikePlaceholder(got)) got = "";
|
||
let cap = captionOnly(got);
|
||
const expect = captionOnly(flat).slice(0, 16);
|
||
if (expect.length >= 2 && cap.includes(expect.slice(0, Math.min(10, expect.length)))) return true;
|
||
|
||
// Fallback once: insertText whole string (still no chunking)
|
||
await clearComposer(box);
|
||
box.focus();
|
||
if (!document.execCommand("insertText", false, flat)) {
|
||
box.dispatchEvent(
|
||
new InputEvent("beforeinput", {
|
||
bubbles: true,
|
||
cancelable: true,
|
||
inputType: "insertText",
|
||
data: flat,
|
||
}),
|
||
);
|
||
}
|
||
await sleep(350);
|
||
got = composerPlain(box);
|
||
if (looksLikePlaceholder(got)) got = "";
|
||
cap = captionOnly(got);
|
||
if (expect.length >= 2 && cap.includes(expect.slice(0, Math.min(10, expect.length)))) return true;
|
||
return isCaptionAcceptable(cap);
|
||
}
|
||
|
||
async function ensureComposerCaption(text: string, token: string): Promise<HTMLElement> {
|
||
if (/https?:\/\//i.test(text)) {
|
||
// Soft warn path: still try, but token check uses captionOnly
|
||
}
|
||
for (let attempt = 0; attempt < 4; attempt++) {
|
||
const box = findTweetComposeBox();
|
||
if (!box) throw new Error("找不到发帖输入框,请手动打开发帖框后重试");
|
||
const ok = await setComposerText(box, text);
|
||
await sleep(200);
|
||
const live = findTweetComposeBox() || box;
|
||
let raw = composerPlain(live);
|
||
if (looksLikePlaceholder(raw)) raw = "";
|
||
const got = captionOnly(raw);
|
||
// Must not be URL-only in the box
|
||
if (/^https?:\/\/\S+$/i.test(raw.trim())) {
|
||
await sleep(250);
|
||
continue;
|
||
}
|
||
if (ok && captionMatchToken(got, token) && isCaptionAcceptable(got)) {
|
||
return live;
|
||
}
|
||
await sleep(300);
|
||
}
|
||
const box = findTweetComposeBox();
|
||
const now = box ? captionOnly(composerPlain(box)) : "";
|
||
throw new Error(
|
||
`无法写入正文(当前「${now.slice(0, 48) || "空"}」)。已中止,避免发出纯链接帖`,
|
||
);
|
||
}
|
||
|
||
async function postTweet(
|
||
text: string,
|
||
media?: Array<{ base64?: string; mime: string; name: string; file?: File }>,
|
||
): Promise<{
|
||
ok: boolean;
|
||
text: string;
|
||
postedAt: string;
|
||
mediaCount: number;
|
||
composerSnapshot: string;
|
||
}> {
|
||
const body = String(text || "").trim();
|
||
if (!body) throw new Error("发帖内容为空");
|
||
if (/^https?:\/\/\S+$/i.test(body)) {
|
||
throw new Error("拒绝发送纯链接(违反 X 可读帖规范)");
|
||
}
|
||
|
||
const token = captionOnly(body);
|
||
if (!isCaptionAcceptable(body)) {
|
||
throw new Error("正文过短或仅含链接/话题(需可读正文)。已中止");
|
||
}
|
||
|
||
let box = findTweetComposeBox();
|
||
if (!box) {
|
||
const sidePost = document.querySelector(
|
||
'[data-testid="SideNav_NewTweet_Button"]',
|
||
) as HTMLElement | null;
|
||
sidePost?.click();
|
||
await sleep(1200);
|
||
box = findTweetComposeBox();
|
||
}
|
||
if (!box) throw new Error("找不到发帖输入框,请手动打开发帖框后重试");
|
||
|
||
const mediaList = (media || []).filter((m) => m && (m.base64 || (m as { file?: File }).file) && m.mime);
|
||
|
||
// Media FIRST, caption ONCE after — re-pasting after media doubles Draft.js count (shows -46)
|
||
if (mediaList.length) {
|
||
await attachComposerMedia(mediaList as Array<{ base64?: string; mime: string; name: string; file?: File }>);
|
||
await sleep(800);
|
||
}
|
||
await ensureComposerCaption(body, token);
|
||
|
||
box = findTweetComposeBox();
|
||
if (!box) throw new Error("发帖框消失,已中止");
|
||
let finalRaw = composerPlain(box);
|
||
if (looksLikePlaceholder(finalRaw)) finalRaw = "";
|
||
let finalCaption = captionOnly(finalRaw);
|
||
if (
|
||
/^https?:\/\/\S+$/i.test(finalRaw.trim()) ||
|
||
!isCaptionAcceptable(finalRaw) ||
|
||
!captionMatchToken(finalCaption, token)
|
||
) {
|
||
throw new Error(
|
||
`发送前校验失败:正文丢失(「${finalRaw.slice(0, 40)}」)。不会发出纯链接`,
|
||
);
|
||
}
|
||
|
||
// If X counter is red, wipe and use short title-only (never paste twice on top)
|
||
let over = readComposerOverBy();
|
||
if (over && over > 0) {
|
||
const short =
|
||
body.split(/\s+[·—|]\s+/)[0]?.trim().slice(0, 100) || body.slice(0, 100);
|
||
await ensureComposerCaption(short, captionOnly(short));
|
||
await sleep(300);
|
||
over = readComposerOverBy();
|
||
if (over && over > 0) {
|
||
throw new Error(`X 显示超出 ${over} 个字符,已中止(免费上限 280)`);
|
||
}
|
||
box = findTweetComposeBox() || box;
|
||
finalRaw = composerPlain(box);
|
||
finalCaption = captionOnly(finalRaw);
|
||
}
|
||
|
||
const limitBefore = readXDailyPostLimitError();
|
||
if (limitBefore) throw new Error(limitBefore);
|
||
|
||
const btn = (document.querySelector('[data-testid="tweetButton"]') ||
|
||
document.querySelector('[data-testid="tweetButtonInline"]')) as
|
||
| HTMLButtonElement
|
||
| null;
|
||
if (!btn || btn.getAttribute("aria-disabled") === "true" || btn.disabled) {
|
||
const limBtn = readXDailyPostLimitError();
|
||
if (limBtn) throw new Error(limBtn);
|
||
const over2 = readComposerOverBy();
|
||
throw new Error(
|
||
over2
|
||
? `发帖按钮不可用:超出 ${over2} 个字符(X 免费上限 280)`
|
||
: "发帖按钮不可用(可能未登录、超字数、媒体还在上传)",
|
||
);
|
||
}
|
||
btn.click();
|
||
const waitMs = mediaList.some((m) => m.mime.startsWith("video/")) ? 5500 : 2800;
|
||
const deadline = Date.now() + waitMs;
|
||
while (Date.now() < deadline) {
|
||
const lim = readXDailyPostLimitError();
|
||
if (lim) throw new Error(lim);
|
||
await sleep(350);
|
||
}
|
||
const limAfter = readXDailyPostLimitError();
|
||
if (limAfter) throw new Error(limAfter);
|
||
|
||
// Composer still open with Post button + our caption → post likely rejected
|
||
const stillBox = findTweetComposeBox();
|
||
const stillBtn = (document.querySelector('[data-testid="tweetButton"]') ||
|
||
document.querySelector('[data-testid="tweetButtonInline"]')) as
|
||
| HTMLButtonElement
|
||
| null;
|
||
if (stillBox && stillBtn && !stillBtn.disabled) {
|
||
const still = captionOnly(composerPlain(stillBox));
|
||
if (still && captionMatchToken(still, token)) {
|
||
const limStill = readXDailyPostLimitError();
|
||
if (limStill) throw new Error(limStill);
|
||
throw new Error("发帖未确认成功(编辑框仍在,可能被 X 拦截)");
|
||
}
|
||
}
|
||
|
||
return {
|
||
ok: true,
|
||
text: body,
|
||
postedAt: new Date().toISOString(),
|
||
mediaCount: mediaList.length,
|
||
composerSnapshot: finalRaw.slice(0, 200),
|
||
};
|
||
}
|
||
|
||
function base64ToFile(base64: string, mime: string, name: string): File {
|
||
const bin = atob(base64);
|
||
const bytes = new Uint8Array(bin.length);
|
||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||
return new File([bytes], name, { type: mime });
|
||
}
|
||
|
||
async function urlToFile(url: string, mime: string, name: string): Promise<File> {
|
||
// Must go through background SW: content scripts on x.com are CORS-bound.
|
||
const resp = await new Promise<{
|
||
ok?: boolean;
|
||
base64?: string;
|
||
mime?: string;
|
||
name?: string;
|
||
error?: string;
|
||
}>((resolve, reject) => {
|
||
try {
|
||
chrome.runtime.sendMessage(
|
||
{ type: "media.fetch", url, mime, name },
|
||
(r) => {
|
||
if (chrome.runtime.lastError) {
|
||
reject(new Error(chrome.runtime.lastError.message || "扩展通信失败"));
|
||
return;
|
||
}
|
||
resolve(r || { ok: false, error: "无响应" });
|
||
},
|
||
);
|
||
} catch (e) {
|
||
reject(e instanceof Error ? e : new Error(String(e)));
|
||
}
|
||
});
|
||
if (!resp?.ok || !resp.base64) {
|
||
throw new Error(resp?.error || "下载媒体失败(Failed to fetch)");
|
||
}
|
||
const type = resp.mime || mime || "application/octet-stream";
|
||
const fname = resp.name || name || "media.bin";
|
||
return base64ToFile(resp.base64, type, fname);
|
||
}
|
||
|
||
async function resolveMediaFiles(
|
||
media?: Array<{ base64?: string; mime?: string; name?: string; url?: string }>,
|
||
mediaUrls?: Array<{ url?: string; mime?: string; name?: string; key?: string }>,
|
||
): Promise<Array<{ base64?: string; mime: string; name: string; file?: File }>> {
|
||
const out: Array<{ base64?: string; mime: string; name: string; file?: File }> = [];
|
||
for (const m of media || []) {
|
||
if (m?.base64 && m?.mime) {
|
||
out.push({ base64: m.base64, mime: m.mime, name: m.name || "media.bin" });
|
||
}
|
||
}
|
||
for (const m of mediaUrls || []) {
|
||
const url = String(m?.url || "").trim();
|
||
if (!url) continue;
|
||
const mime = String(m.mime || "application/octet-stream");
|
||
const name = String(m.name || "media.bin");
|
||
const file = await urlToFile(url, mime, name);
|
||
out.push({ mime: file.type || mime, name: file.name || name, file });
|
||
}
|
||
return out.slice(0, 4);
|
||
}
|
||
|
||
async function findComposerFileInput(): Promise<HTMLInputElement | null> {
|
||
const pick = () =>
|
||
document.querySelector(
|
||
'input[data-testid="fileInput"], input[type="file"][accept*="image"], input[type="file"][multiple], input[type="file"]',
|
||
) as HTMLInputElement | null;
|
||
|
||
let input = pick();
|
||
if (input) return input;
|
||
|
||
const candidates = Array.from(
|
||
document.querySelectorAll('[role="button"], button, div[aria-label]'),
|
||
) as HTMLElement[];
|
||
for (const el of candidates) {
|
||
const label = `${el.getAttribute("aria-label") || ""} ${textOf(el)}`.toLowerCase();
|
||
if (
|
||
/media|photo|video|图片|视频|媒體|照片|gif|image/.test(label) &&
|
||
!/gif search|emoji/.test(label)
|
||
) {
|
||
el.click();
|
||
await sleep(500);
|
||
input = pick();
|
||
if (input) return input;
|
||
}
|
||
}
|
||
// toolbars often have a hidden file input already
|
||
return pick();
|
||
}
|
||
|
||
async function attachComposerMedia(
|
||
media: Array<{ base64?: string; mime: string; name: string; file?: File }>,
|
||
): Promise<void> {
|
||
const input = await findComposerFileInput();
|
||
if (!input) throw new Error("找不到媒体上传控件(请先打开发帖框)");
|
||
|
||
const files = media.slice(0, 4).map((m) => {
|
||
if (m.file instanceof File) return m.file;
|
||
if (m.base64) return base64ToFile(m.base64, m.mime, m.name);
|
||
throw new Error("媒体缺少数据");
|
||
});
|
||
const dt = new DataTransfer();
|
||
for (const f of files) dt.items.add(f);
|
||
input.files = dt.files;
|
||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||
|
||
// wait for preview / upload
|
||
const hasVideo = files.some((f) => f.type.startsWith("video/"));
|
||
const deadline = Date.now() + (hasVideo ? 45000 : 12000);
|
||
while (Date.now() < deadline) {
|
||
const preview =
|
||
document.querySelector('[data-testid="attachments"]') ||
|
||
document.querySelector('[data-testid="toolBar"]')?.parentElement?.querySelector("img, video") ||
|
||
document.querySelector('[aria-label*="Remove"]') ||
|
||
document.querySelector('[aria-label*="移除"]');
|
||
const btn = (document.querySelector('[data-testid="tweetButton"]') ||
|
||
document.querySelector('[data-testid="tweetButtonInline"]')) as HTMLButtonElement | null;
|
||
if (preview && btn && btn.getAttribute("aria-disabled") !== "true" && !btn.disabled) {
|
||
return;
|
||
}
|
||
await sleep(500);
|
||
}
|
||
}
|
||
|
||
async function growthOnSearchPage(
|
||
jobId: string,
|
||
params: Record<string, unknown>,
|
||
): Promise<Record<string, unknown>> {
|
||
const likeLimit = Number(params.likeLimit ?? 0);
|
||
const followLimit = Number(params.followLimit ?? 0);
|
||
const replyLimit = Number(params.replyLimit ?? 0);
|
||
const replyText = String(params.replyText || "").trim();
|
||
const delay = {
|
||
min: Number(params.minDelayMs ?? 2500),
|
||
max: Number(params.maxDelayMs ?? 5000),
|
||
};
|
||
let liked = 0;
|
||
let followed = 0;
|
||
let replied = 0;
|
||
|
||
if (likeLimit > 0) {
|
||
liked = await likeVisible(jobId, likeLimit, delay);
|
||
}
|
||
if (followLimit > 0) {
|
||
followed = await followVisible(jobId, followLimit, delay);
|
||
}
|
||
if (replyLimit > 0 && replyText) {
|
||
const arts = Array.from(
|
||
document.querySelectorAll('article[data-testid="tweet"]'),
|
||
).slice(0, replyLimit);
|
||
for (let i = 0; i < arts.length; i++) {
|
||
const replyBtn = arts[i].querySelector(
|
||
'[data-testid="reply"]',
|
||
) as HTMLElement | null;
|
||
if (!replyBtn) continue;
|
||
replyBtn.click();
|
||
await sleep(900);
|
||
const box =
|
||
(document.querySelector('[data-testid="tweetTextarea_0"]') as HTMLElement | null) ||
|
||
(document.querySelector('div[role="textbox"][contenteditable="true"]') as HTMLElement | null);
|
||
if (!box) continue;
|
||
box.focus();
|
||
document.execCommand("insertText", false, replyText);
|
||
await sleep(400);
|
||
const send = (document.querySelector('[data-testid="tweetButton"]') ||
|
||
document.querySelector('[data-testid="tweetButtonInline"]')) as
|
||
| HTMLButtonElement
|
||
| null;
|
||
if (send && !send.disabled) {
|
||
send.click();
|
||
replied += 1;
|
||
reportProgress(jobId, replied, replyLimit, `已回复 ${replied}`);
|
||
}
|
||
await sleep(delayBetween(delay));
|
||
// close compose if still open
|
||
const close = document.querySelector(
|
||
'[data-testid="app-bar-close"]',
|
||
) as HTMLElement | null;
|
||
close?.click();
|
||
await sleep(400);
|
||
}
|
||
}
|
||
|
||
return { liked, followed, replied, query: params.query };
|
||
}
|
||
|
||
/** Page-local actions only — navigation is done by background */
|
||
async function runJob(
|
||
jobId: string,
|
||
kind: PageJobKind,
|
||
params: Record<string, unknown>,
|
||
): Promise<RunResult> {
|
||
try {
|
||
const limit = Number(params.limit ?? 50);
|
||
const delay = {
|
||
min: Number(params.minDelayMs ?? 2000),
|
||
max: Number(params.maxDelayMs ?? 5000),
|
||
};
|
||
|
||
switch (kind) {
|
||
case "scrape.profile": {
|
||
const profile = await scrapeProfile();
|
||
return { ok: true, result: profile };
|
||
}
|
||
case "scrape.following":
|
||
case "scrape.followers": {
|
||
const users = await scrollCollectUserCells(jobId, limit);
|
||
return { ok: true, result: { users } };
|
||
}
|
||
case "scrape.tweets":
|
||
case "scrape.search":
|
||
case "scrape.bookmarks":
|
||
case "scrape.likes":
|
||
case "scrape.hashtag":
|
||
case "scrape.home":
|
||
case "scrape.mentions":
|
||
case "scrape.with_replies": {
|
||
const tweets = await scrapeTweets(jobId, limit);
|
||
return {
|
||
ok: true,
|
||
result: { tweets, query: params.query, hashtag: params.hashtag },
|
||
};
|
||
}
|
||
case "scrape.people": {
|
||
const users = await scrollCollectUserCells(jobId, limit);
|
||
return { ok: true, result: { users, query: params.query } };
|
||
}
|
||
case "scrape.notifications": {
|
||
const notices = await scrapeNotifications(jobId, limit);
|
||
return { ok: true, result: { notices } };
|
||
}
|
||
case "scrape.thread": {
|
||
const tweets = await scrapeThread(jobId, limit);
|
||
return {
|
||
ok: true,
|
||
result: { tweets, statusUrl: params.statusUrl || params.url },
|
||
};
|
||
}
|
||
case "scrape.media": {
|
||
const tweets = await scrapeTweets(jobId, limit, { mediaOnly: true });
|
||
const items = tweets.map((t) => ({
|
||
url: t.url,
|
||
author: t.author,
|
||
text: t.text,
|
||
mediaUrls: t.mediaUrls || [],
|
||
createdAt: t.createdAt,
|
||
}));
|
||
return {
|
||
ok: true,
|
||
result: {
|
||
tweets,
|
||
items,
|
||
mediaCount: items.reduce((n, i) => n + i.mediaUrls.length, 0),
|
||
query: params.query,
|
||
},
|
||
};
|
||
}
|
||
case "scrape.likers":
|
||
case "scrape.list":
|
||
case "scrape.retweeters":
|
||
case "scrape.quotes": {
|
||
const users = await scrollCollectUserCells(jobId, limit);
|
||
return {
|
||
ok: true,
|
||
result: {
|
||
users,
|
||
statusUrl: params.statusUrl || params.url,
|
||
listUrl: params.listUrl,
|
||
},
|
||
};
|
||
}
|
||
case "cleanup.collect_users": {
|
||
const users = await scrollCollectUserCells(jobId, limit);
|
||
return { ok: true, result: { users } };
|
||
}
|
||
case "cleanup.unfollow": {
|
||
const list = (params.usernames as string[]) || [];
|
||
if (!list.length) throw new Error("缺少 usernames");
|
||
const result = await unfollowUsers(jobId, list, delay);
|
||
return { ok: true, result };
|
||
}
|
||
case "cleanup.unfollow_visible": {
|
||
const onlyNonFollowers = params.onlyNonFollowers !== false;
|
||
const result = await unfollowVisible(
|
||
jobId,
|
||
limit,
|
||
delay,
|
||
onlyNonFollowers,
|
||
);
|
||
return { ok: true, result };
|
||
}
|
||
case "cleanup.mute":
|
||
case "cleanup.unmute":
|
||
case "cleanup.block":
|
||
case "cleanup.unblock": {
|
||
const action =
|
||
kind === "cleanup.mute"
|
||
? "mute"
|
||
: kind === "cleanup.unmute"
|
||
? "unmute"
|
||
: kind === "cleanup.block"
|
||
? "block"
|
||
: "unblock";
|
||
const result = await muteOrBlockCurrent(action);
|
||
return { ok: true, result: { ...result, action, username: params.username } };
|
||
}
|
||
case "engage.like": {
|
||
if (params.statusUrl || params.url) {
|
||
const ok = await likeCurrentTweet();
|
||
return { ok: true, result: { liked: ok ? 1 : 0, url: params.statusUrl || params.url } };
|
||
}
|
||
const n = await likeVisible(jobId, limit, delay);
|
||
return { ok: true, result: { liked: n } };
|
||
}
|
||
case "engage.unlike": {
|
||
if (params.statusUrl || params.url) {
|
||
const ok = await unlikeCurrentTweet();
|
||
return { ok: true, result: { unliked: ok ? 1 : 0, url: params.statusUrl || params.url } };
|
||
}
|
||
const n = await unlikeVisible(jobId, limit, delay);
|
||
return { ok: true, result: { unliked: n } };
|
||
}
|
||
case "engage.follow": {
|
||
if (params.singleProfile) {
|
||
const result = await followCurrentProfile();
|
||
return { ok: true, result: { followed: result.already ? 0 : 1, ...result } };
|
||
}
|
||
const n = await followVisible(jobId, limit, delay);
|
||
return { ok: true, result: { followed: n } };
|
||
}
|
||
case "engage.post": {
|
||
const text = String(params.text || "");
|
||
if (!text.trim()) throw new Error("缺少 text");
|
||
const mediaRaw = Array.isArray(params.media)
|
||
? (params.media as Array<{ base64?: string; mime?: string; name?: string; url?: string }>)
|
||
: [];
|
||
const mediaUrls = Array.isArray(params.mediaUrls)
|
||
? (params.mediaUrls as Array<{ url?: string; mime?: string; name?: string; key?: string }>)
|
||
: [];
|
||
const resolved = await resolveMediaFiles(mediaRaw, mediaUrls);
|
||
const result = await postTweet(text, resolved as Array<{ base64: string; mime: string; name: string }>);
|
||
return { ok: true, result: { ...result, mediaKeys: mediaUrls.map((m) => m.key).filter(Boolean) } };
|
||
}
|
||
case "engage.reply": {
|
||
const text = String(params.text || "");
|
||
if (!text.trim()) throw new Error("缺少回复内容");
|
||
const result = await replyCurrent(text);
|
||
return { ok: true, result: { ...result, url: params.statusUrl || params.url } };
|
||
}
|
||
case "engage.retweet": {
|
||
const result = await retweetCurrent();
|
||
return { ok: true, result: { ...result, url: params.statusUrl || params.url } };
|
||
}
|
||
case "engage.unretweet": {
|
||
const result = await unretweetCurrent();
|
||
return { ok: true, result: { ...result, url: params.statusUrl || params.url } };
|
||
}
|
||
case "engage.quote": {
|
||
const text = String(params.text || "");
|
||
if (!text.trim()) throw new Error("缺少引用文案");
|
||
const result = await retweetCurrent(text);
|
||
return { ok: true, result: { ...result, text, url: params.statusUrl || params.url } };
|
||
}
|
||
case "engage.bookmark": {
|
||
const result = await bookmarkCurrent();
|
||
return {
|
||
ok: true,
|
||
result: { ...result, url: params.statusUrl || params.url },
|
||
};
|
||
}
|
||
case "engage.unbookmark": {
|
||
const result = await unbookmarkCurrent();
|
||
return {
|
||
ok: true,
|
||
result: { ...result, url: params.statusUrl || params.url },
|
||
};
|
||
}
|
||
case "engage.delete": {
|
||
const result = await deleteCurrentTweet();
|
||
return {
|
||
ok: true,
|
||
result: { ...result, url: params.statusUrl || params.url },
|
||
};
|
||
}
|
||
case "engage.pin": {
|
||
const result = await pinOrUnpinCurrent("pin");
|
||
return {
|
||
ok: true,
|
||
result: { ...result, url: params.statusUrl || params.url },
|
||
};
|
||
}
|
||
case "engage.unpin": {
|
||
const result = await pinOrUnpinCurrent("unpin");
|
||
return {
|
||
ok: true,
|
||
result: { ...result, url: params.statusUrl || params.url },
|
||
};
|
||
}
|
||
case "engage.copy_link": {
|
||
const result = await copyTweetLink();
|
||
return {
|
||
ok: true,
|
||
result: { ...result, url: result.url || params.statusUrl || params.url },
|
||
};
|
||
}
|
||
case "growth.engage":
|
||
case "growth.home": {
|
||
const result = await growthOnSearchPage(jobId, params);
|
||
return { ok: true, result };
|
||
}
|
||
case "monitor.snapshot_followers":
|
||
case "monitor.snapshot_following": {
|
||
const users = await scrollCollectUserCells(jobId, limit);
|
||
return {
|
||
ok: true,
|
||
result: {
|
||
usernames: users.map((u) => u.username),
|
||
users,
|
||
capturedAt: new Date().toISOString(),
|
||
},
|
||
};
|
||
}
|
||
default:
|
||
return { ok: false, error: `这一步还不支持(请更新扩展)` };
|
||
}
|
||
} catch (err) {
|
||
return {
|
||
ok: false,
|
||
error: err instanceof Error ? err.message : String(err),
|
||
};
|
||
}
|
||
}
|
||
|
||
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
|
||
if (message?.type === "x2.getAccount") {
|
||
void getAccountPayloadReady().then((account) => {
|
||
sendResponse({ account, loggedIn: !!document.querySelector('a[data-testid="AppTabBar_Home_Link"]') });
|
||
});
|
||
return true;
|
||
}
|
||
|
||
if (message?.type === "x2.ping") {
|
||
sendResponse({ ok: true });
|
||
return false;
|
||
}
|
||
|
||
if (message?.type === "x2.runJob") {
|
||
// Do NOT use async sendResponse / return true — result goes via content.jobResult
|
||
const jobId = message.jobId as string;
|
||
void runJob(
|
||
jobId,
|
||
message.kind as PageJobKind,
|
||
(message.params || {}) as Record<string, unknown>,
|
||
).then((result) => reportResult(jobId, result));
|
||
return false;
|
||
}
|
||
|
||
return false;
|
||
});
|