douyinWEB/extensions/dylive-helper/src/background.ts
eric ba2ab0400a fix(test1): X发帖媒体改为后台下载,失败不再删S3
content script 在 x.com 上 fetch S3 会 Failed to fetch;改走 background host_permissions,且 failed 任务保留媒体以便重试。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 08:07:27 -05:00

1616 lines
47 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
AGENT_HTTP,
AGENT_WS,
envelope,
type AccountInfo,
type AgentEvent,
type ExtensionJobExecPayload,
type JobKind,
type JobProgress,
type JobRecord,
type JobStatus,
type UserRow,
} from "@x2/shared";
type ConnState = "disconnected" | "connecting" | "connected";
type LocalJob = JobRecord & { source: "local" | "agent" };
let ws: WebSocket | null = null;
let token = "";
let state: ConnState = "disconnected";
let cachedAccount: Partial<AccountInfo> | undefined;
const pendingJobs = new Map<
string,
{
resolve: (v: { ok: boolean; result?: unknown; error?: string }) => void;
reject: (e: Error) => void;
timer: ReturnType<typeof setTimeout>;
}
>();
const localJobs: LocalJob[] = [];
const cancelledLocal = new Set<string>();
const MAX_LOCAL_JOBS = 80;
async function loadToken(): Promise<string> {
const stored = await chrome.storage.local.get(["token"]);
if (stored.token) return String(stored.token);
return "";
}
async function saveToken(t: string) {
token = t;
await chrome.storage.local.set({ token: t });
}
async function pair(): Promise<string> {
const res = await fetch(`${AGENT_HTTP}/pair`);
if (!res.ok) throw new Error(`配对失败 HTTP ${res.status}`);
const data = (await res.json()) as { token: string };
await saveToken(data.token);
return data.token;
}
function setState(s: ConnState) {
state = s;
broadcastUi({ type: "conn.state", state, account: cachedAccount });
chrome.action.setBadgeText({ text: s === "connected" ? "ON" : "SOLO" });
chrome.action.setBadgeBackgroundColor({
color: s === "connected" ? "#1a7f37" : "#c47a1a",
});
}
function broadcastUi(msg: Record<string, unknown>) {
chrome.runtime.sendMessage(msg).catch(() => {});
}
function sleep(ms: number) {
return new Promise((r) => setTimeout(r, ms));
}
function nowIso() {
return new Date().toISOString();
}
function newLocalId() {
return `local_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
}
function upsertLocalJob(job: LocalJob) {
const idx = localJobs.findIndex((j) => j.id === job.id);
if (idx >= 0) localJobs[idx] = job;
else localJobs.unshift(job);
if (localJobs.length > MAX_LOCAL_JOBS) localJobs.length = MAX_LOCAL_JOBS;
broadcastUi({ type: "job.updated", job });
void chrome.storage.local.set({
localJobs: localJobs.slice(0, 40),
});
}
async function pushLocalJobToDouyin(job: LocalJob) {
// When Agent is connected, Agent may also push — still OK for extension solo display
try {
const cfg = await chrome.storage.local.get([
"douyinWebhookEnabled",
"douyinWebhookUrl",
"douyinWebhookToken",
"douyinAgentId",
"douyinAgentLabel",
]);
const token = String(cfg.douyinWebhookToken || "").trim();
if (!token) return;
if (cfg.douyinWebhookEnabled === false) return;
const url = String(
cfg.douyinWebhookUrl || "https://dylive.nomadro.com/api/x2/ingest",
).trim();
if (!url) return;
const accounts = [];
if (cachedAccount?.username) {
accounts.push({
id: `x:${cachedAccount.username}`,
username: cachedAccount.username,
displayName: cachedAccount.displayName || "",
avatarUrl: cachedAccount.avatarUrl || "",
lastSeenAt: nowIso(),
});
}
await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-X2-Token": token,
},
body: JSON.stringify({
source: "dylive-helper",
event: "job.updated",
agent_id: String(cfg.douyinAgentId || "dylive-helper"),
label: String(cfg.douyinAgentLabel || "dylive Helper"),
extension_connected: true,
job,
accounts: accounts.length ? accounts : undefined,
ts: nowIso(),
}),
});
} catch {
/* ignore */
}
}
async function pushHeartbeatToDouyin() {
try {
const cfg = await chrome.storage.local.get([
"douyinWebhookEnabled",
"douyinWebhookUrl",
"douyinWebhookToken",
"douyinAgentId",
"douyinAgentLabel",
]);
const token = String(cfg.douyinWebhookToken || "").trim();
if (!token) return;
if (cfg.douyinWebhookEnabled === false) return;
const url = String(
cfg.douyinWebhookUrl || "https://dylive.nomadro.com/api/x2/ingest",
).trim();
if (!url) return;
await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-X2-Token": token,
},
body: JSON.stringify({
source: "dylive-helper",
event: "heartbeat",
agent_id: String(cfg.douyinAgentId || "dylive-helper"),
label: String(cfg.douyinAgentLabel || "dylive Helper"),
extension_connected: true,
message: "dylive-helper alive",
ts: nowIso(),
}),
});
} catch {
/* ignore */
}
}
/** Web /x → extension via WSS (poll kept only as rare fallback). */
let webJobBusy = false;
let dyliveWs: WebSocket | null = null;
let dyliveWsOpening = false;
let dyliveWsBackoffMs = 1500;
let dyliveWsTimer: ReturnType<typeof setTimeout> | null = null;
function accountsPayload() {
if (!cachedAccount?.username) return undefined;
return [
{
id: `x:${cachedAccount.username}`,
username: cachedAccount.username,
displayName: cachedAccount.displayName || "",
avatarUrl: cachedAccount.avatarUrl || "",
lastSeenAt: nowIso(),
},
];
}
async function applyDyliveAutoPair(msg: {
origin?: string;
token?: string;
ingestUrl?: string;
pollUrl?: string;
wsUrl?: string;
}) {
const origin = String(msg.origin || "https://dylive.nomadro.com").replace(/\/$/, "");
const token = String(msg.token || "").trim();
if (!token) return;
const wsBase = origin.replace(/^http/i, "ws");
await chrome.storage.local.set({
douyinWebhookEnabled: true,
douyinWebhookUrl: String(msg.ingestUrl || `${origin}/api/x2/ingest`),
douyinWebhookToken: token,
douyinPollUrl: String(msg.pollUrl || `${origin}/api/x2/extension/poll`),
douyinWsUrl: String(msg.wsUrl || `${wsBase}/api/x2/extension/ws`),
douyinOrigin: origin,
douyinAgentId: "dylive-helper",
douyinAgentLabel: "dylive Helper",
douyinAutoPaired: true,
douyinAutoPairedAt: nowIso(),
});
dyliveWsBackoffMs = 1500;
void ensureDyliveWs(true);
}
async function runWebJob(job: {
id: string;
kind: JobKind;
params?: Record<string, unknown>;
}) {
if (!job?.id || !job.kind) return;
webJobBusy = true;
wsSend({ type: "busy", busy: true });
const local: LocalJob = {
id: String(job.id),
kind: job.kind,
status: "queued",
params: (job.params || {}) as Record<string, unknown>,
progress: { current: 0, total: 1, message: "Web 任务领取" },
createdAt: nowIso(),
updatedAt: nowIso(),
source: "local",
};
upsertLocalJob(local);
try {
await runLocalJob(local);
} finally {
webJobBusy = false;
wsSend({ type: "ready" });
}
}
function wsSend(payload: Record<string, unknown>) {
if (dyliveWs && dyliveWs.readyState === WebSocket.OPEN) {
try {
dyliveWs.send(JSON.stringify(payload));
} catch {
/* ignore */
}
}
}
function scheduleDyliveWsReconnect() {
if (dyliveWsTimer) return;
const wait = dyliveWsBackoffMs;
dyliveWsBackoffMs = Math.min(30000, Math.floor(dyliveWsBackoffMs * 1.6));
dyliveWsTimer = setTimeout(() => {
dyliveWsTimer = null;
void ensureDyliveWs(false);
}, wait);
}
async function ensureDyliveWs(force = false) {
if (dyliveWsOpening) return;
if (!force && dyliveWs && (dyliveWs.readyState === WebSocket.OPEN || dyliveWs.readyState === WebSocket.CONNECTING)) {
return;
}
const cfg = await chrome.storage.local.get([
"douyinWebhookEnabled",
"douyinWebhookToken",
"douyinWsUrl",
"douyinOrigin",
"douyinAgentId",
"douyinAgentLabel",
]);
if (cfg.douyinWebhookEnabled === false) return;
const token = String(cfg.douyinWebhookToken || "").trim();
if (!token) return;
const origin = String(cfg.douyinOrigin || "https://dylive.nomadro.com").replace(/\/$/, "");
const wsBase = String(cfg.douyinWsUrl || `${origin.replace(/^http/i, "ws")}/api/x2/extension/ws`).trim();
const agentId = encodeURIComponent(String(cfg.douyinAgentId || "dylive-helper"));
const label = encodeURIComponent(String(cfg.douyinAgentLabel || "dylive Helper"));
const url = `${wsBase}${wsBase.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}&agent_id=${agentId}&label=${label}`;
try {
if (dyliveWs) {
try {
dyliveWs.close();
} catch {
/* ignore */
}
dyliveWs = null;
}
dyliveWsOpening = true;
const ws = new WebSocket(url);
dyliveWs = ws;
ws.onopen = () => {
dyliveWsOpening = false;
dyliveWsBackoffMs = 1500;
wsSend({
type: "hello",
busy: webJobBusy,
accounts: accountsPayload(),
});
};
ws.onmessage = (ev) => {
void (async () => {
let msg: {
type?: string;
job?: { id: string; kind: JobKind; params?: Record<string, unknown> };
ids?: string[];
};
try {
msg = JSON.parse(String(ev.data));
} catch {
return;
}
const t = String(msg?.type || "");
if (t === "job.cancel" && Array.isArray(msg.ids)) {
for (const cid of msg.ids) {
cancelledLocal.add(String(cid));
patchLocalJob(String(cid), { status: "cancelled", error: "用户取消" });
}
return;
}
if (t === "job.exec" && msg.job?.id && msg.job.kind) {
if (webJobBusy) {
wsSend({ type: "busy", busy: true });
return;
}
wsSend({ type: "job.ack", jobId: msg.job.id });
await runWebJob(msg.job);
}
})();
};
ws.onclose = () => {
dyliveWsOpening = false;
if (dyliveWs === ws) dyliveWs = null;
scheduleDyliveWsReconnect();
};
ws.onerror = () => {
try {
ws.close();
} catch {
/* ignore */
}
};
} catch {
dyliveWsOpening = false;
scheduleDyliveWsReconnect();
}
}
function wsHeartbeatTick() {
void ensureDyliveWs(false);
if (dyliveWs && dyliveWs.readyState === WebSocket.OPEN) {
wsSend({
type: "heartbeat",
busy: webJobBusy,
accounts: accountsPayload(),
});
}
}
/** Rare HTTP fallback if WS down for a while (should almost never run jobs this way). */
async function pollWebQueueFallback() {
if (webJobBusy) return;
if (dyliveWs && dyliveWs.readyState === WebSocket.OPEN) return;
try {
const cfg = await chrome.storage.local.get([
"douyinWebhookEnabled",
"douyinWebhookToken",
"douyinPollUrl",
"douyinOrigin",
"douyinAgentId",
"douyinAgentLabel",
]);
if (cfg.douyinWebhookEnabled === false) return;
const token = String(cfg.douyinWebhookToken || "").trim();
if (!token) return;
const pollUrl = String(
cfg.douyinPollUrl ||
`${cfg.douyinOrigin || "https://dylive.nomadro.com"}/api/x2/extension/poll`,
);
const res = await fetch(pollUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-X2-Token": token,
},
body: JSON.stringify({
agent_id: String(cfg.douyinAgentId || "dylive-helper"),
label: String(cfg.douyinAgentLabel || "dylive Helper"),
busy: false,
accounts: accountsPayload(),
}),
});
if (!res.ok) return;
const data = (await res.json()) as {
job?: { id: string; kind: JobKind; params?: Record<string, unknown> };
cancel_ids?: string[];
};
for (const cid of data.cancel_ids || []) {
cancelledLocal.add(String(cid));
patchLocalJob(String(cid), { status: "cancelled", error: "用户取消" });
}
if (data.job?.id && data.job.kind) await runWebJob(data.job);
} catch {
/* ignore */
}
}
function patchLocalJob(
id: string,
patch: Partial<LocalJob> & { progress?: JobProgress },
) {
const cur = localJobs.find((j) => j.id === id);
if (!cur) return;
const next: LocalJob = {
...cur,
...patch,
progress: patch.progress || cur.progress,
updatedAt: nowIso(),
};
upsertLocalJob(next);
void pushLocalJobToDouyin(next);
return next;
}
async function ensureXTab(): Promise<number> {
// 优先当前窗口活动的 x.com 标签
const [active] = await chrome.tabs.query({ active: true, currentWindow: true });
if (active?.id && /https:\/\/(x|twitter)\.com\//i.test(active.url || "")) {
return active.id;
}
const tabs = await chrome.tabs.query({
url: ["https://x.com/*", "https://twitter.com/*"],
});
const preferred =
tabs.find((t) => t.active && t.id) ||
tabs.find((t) => t.id && /\/(home|notifications)/.test(t.url || "")) ||
tabs.find((t) => t.id);
if (preferred?.id) return preferred.id;
const created = await chrome.tabs.create({ url: "https://x.com/home" });
if (!created.id) throw new Error("无法打开 x.com");
await waitTabComplete(created.id);
return created.id;
}
async function injectContent(tabId: number): Promise<boolean> {
try {
await chrome.scripting.executeScript({
target: { tabId },
files: ["content.js"],
});
return true;
} catch {
return false;
}
}
async function ensureContentReady(tabId: number): Promise<boolean> {
if (await pingContent(tabId, 4)) return true;
await injectContent(tabId);
return pingContent(tabId, 10);
}
async function readPageAccount(): Promise<Partial<AccountInfo> | undefined> {
try {
const tabId = await ensureXTab();
const ready = await ensureContentReady(tabId);
if (!ready) return undefined;
const res = await sendTabMessage<{
account?: Partial<AccountInfo>;
loggedIn?: boolean;
}>(tabId, {
type: "x2.getAccount",
});
if (res?.account?.username) {
cachedAccount = res.account;
broadcastUi({ type: "account.updated", account: cachedAccount });
}
return res?.account;
} catch {
return undefined;
}
}
function waitTabComplete(tabId: number, timeoutMs = 30000): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
chrome.tabs.onUpdated.removeListener(listener);
reject(new Error("页面加载超时"));
}, timeoutMs);
const listener = (id: number, info: chrome.tabs.TabChangeInfo) => {
if (id === tabId && info.status === "complete") {
clearTimeout(timer);
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
};
chrome.tabs.get(tabId, (tab) => {
if (chrome.runtime.lastError) {
clearTimeout(timer);
chrome.tabs.onUpdated.removeListener(listener);
reject(new Error(chrome.runtime.lastError.message));
return;
}
if (tab.status === "complete") {
clearTimeout(timer);
chrome.tabs.onUpdated.removeListener(listener);
resolve();
return;
}
chrome.tabs.onUpdated.addListener(listener);
});
});
}
async function navigateTab(tabId: number, url: string) {
const tab = await chrome.tabs.get(tabId);
if (tab.url === url) {
await sleep(500);
return;
}
await chrome.tabs.update(tabId, { url, active: true });
await waitTabComplete(tabId);
await sleep(1800);
}
async function pingContent(tabId: number, tries = 12): Promise<boolean> {
for (let i = 0; i < tries; i++) {
try {
const res = await sendTabMessage<{ ok?: boolean }>(tabId, { type: "x2.ping" });
if (res?.ok) return true;
} catch {
/* content not ready */
}
await sleep(400);
}
return false;
}
function sendTabMessage<T = unknown>(
tabId: number,
message: unknown,
): Promise<T> {
return new Promise((resolve, reject) => {
chrome.tabs.sendMessage(tabId, message, (response) => {
const err = chrome.runtime.lastError;
if (err) {
reject(new Error(err.message));
return;
}
resolve(response as T);
});
});
}
function dispatchJob(tabId: number, message: Record<string, unknown>): void {
chrome.tabs.sendMessage(tabId, message, () => {
void chrome.runtime.lastError;
});
}
function awaitJobResult(
jobId: string,
timeoutMs = 10 * 60 * 1000,
): Promise<{ ok: boolean; result?: unknown; error?: string }> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingJobs.delete(jobId);
reject(new Error("任务超时"));
}, timeoutMs);
pendingJobs.set(jobId, { resolve, reject, timer });
});
}
async function runOnPage(
tabId: number,
jobId: string,
kind: JobKind | "cleanup.collect_users",
params: Record<string, unknown>,
) {
if (cancelledLocal.has(jobId)) {
return { ok: false, error: "用户取消" };
}
const ready = await ensureContentReady(tabId);
if (!ready) throw new Error("内容脚本未就绪,请刷新 x.com 后重试");
const phaseId = `${jobId}:${kind}:${Date.now()}`;
const resultPromise = awaitJobResult(phaseId);
dispatchJob(tabId, {
type: "x2.runJob",
jobId: phaseId,
kind,
params,
});
return resultPromise;
}
/** Shared executor used by Agent job.exec and standalone local jobs */
async function executeJobPayload(
payload: ExtensionJobExecPayload,
): Promise<{ ok: boolean; result?: unknown; error?: string }> {
const { jobId, kind, params } = payload;
const tabId = await ensureXTab();
const username = String(params.username || "").replace(/^@/, "");
const limit = Number(params.limit ?? 50);
const statusUrl = String(params.statusUrl || params.url || "").trim();
const query = String(params.query || "").trim();
switch (kind) {
case "scrape.profile": {
if (username) await navigateTab(tabId, `https://x.com/${username}`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.following": {
if (!username) throw new Error("缺少 username");
await navigateTab(tabId, `https://x.com/${username}/following`);
return runOnPage(tabId, jobId, kind, params);
}
case "monitor.snapshot_following": {
if (!username) throw new Error("缺少 username");
await navigateTab(tabId, `https://x.com/${username}/following`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.followers":
case "monitor.snapshot_followers": {
if (!username) throw new Error("缺少 username");
await navigateTab(tabId, `https://x.com/${username}/followers`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.tweets": {
if (username) await navigateTab(tabId, `https://x.com/${username}`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.search": {
if (!query) throw new Error("缺少搜索关键词");
const q = encodeURIComponent(query);
const filter = String(params.filter || "live");
const f =
filter === "user" || filter === "people"
? "user"
: filter === "media"
? "media"
: "live";
await navigateTab(
tabId,
`https://x.com/search?q=${q}&src=typed_query&f=${f}`,
);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.hashtag": {
const tag = String(params.hashtag || query || "")
.replace(/^#/, "")
.trim();
if (!tag) throw new Error("缺少话题标签 hashtag");
await navigateTab(
tabId,
`https://x.com/hashtag/${encodeURIComponent(tag)}?f=live`,
);
return runOnPage(tabId, jobId, kind, { ...params, hashtag: tag });
}
case "scrape.people": {
if (!query) throw new Error("缺少搜索关键词");
const q = encodeURIComponent(query);
await navigateTab(
tabId,
`https://x.com/search?q=${q}&src=typed_query&f=user`,
);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.notifications": {
await navigateTab(tabId, "https://x.com/notifications");
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.home": {
await navigateTab(tabId, "https://x.com/home");
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.mentions": {
await navigateTab(tabId, "https://x.com/notifications/mentions");
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.retweeters": {
if (!statusUrl) throw new Error("缺少推文链接 statusUrl");
const base = statusUrl.replace(/\/?(?:\?.*)?$/, "");
await navigateTab(tabId, `${base}/retweets`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.quotes": {
if (!statusUrl) throw new Error("缺少推文链接 statusUrl");
const base = statusUrl.replace(/\/?(?:\?.*)?$/, "");
await navigateTab(tabId, `${base}/quotes`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.with_replies": {
if (!username) throw new Error("缺少 username");
await navigateTab(tabId, `https://x.com/${username}/with_replies`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.bookmarks": {
await navigateTab(tabId, "https://x.com/i/bookmarks");
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.media": {
if (query) {
const q = encodeURIComponent(query);
await navigateTab(
tabId,
`https://x.com/search?q=${q}&src=typed_query&f=live`,
);
} else if (username) {
await navigateTab(tabId, `https://x.com/${username}/media`);
}
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.likers": {
if (!statusUrl) throw new Error("缺少推文链接 statusUrl");
const likesUrl = statusUrl.replace(/\/?(?:\?.*)?$/, "") + "/likes";
await navigateTab(tabId, likesUrl);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.thread": {
if (!statusUrl) throw new Error("缺少推文链接 statusUrl");
await navigateTab(tabId, statusUrl);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.likes": {
if (!username) throw new Error("缺少 username");
await navigateTab(tabId, `https://x.com/${username}/likes`);
return runOnPage(tabId, jobId, kind, params);
}
case "scrape.list": {
const listUrl = String(params.listUrl || statusUrl || "").trim();
if (!listUrl) throw new Error("缺少列表链接 listUrl");
await navigateTab(tabId, listUrl.includes("/members") ? listUrl : listUrl.replace(/\/?$/, "/members"));
return runOnPage(tabId, jobId, kind, params);
}
case "cleanup.non_followers": {
if (!username) throw new Error("缺少 username");
const followingLimit = Number(params.followingLimit ?? limit);
const followersLimit = Number(params.followersLimit ?? limit);
await navigateTab(tabId, `https://x.com/${username}/following`);
const followingRes = await runOnPage(tabId, jobId, "cleanup.collect_users", {
limit: followingLimit,
});
if (!followingRes.ok) throw new Error(followingRes.error || "采集 following 失败");
await navigateTab(tabId, `https://x.com/${username}/followers`);
const followersRes = await runOnPage(tabId, jobId, "cleanup.collect_users", {
limit: followersLimit,
});
if (!followersRes.ok) throw new Error(followersRes.error || "采集 followers 失败");
const following =
((followingRes.result as { users?: UserRow[] })?.users || []);
const followers =
((followersRes.result as { users?: UserRow[] })?.users || []);
const followerSet = new Set(followers.map((u) => u.username.toLowerCase()));
const nonFollowers = following.filter((u) => {
if (typeof u.followsYou === "boolean") return !u.followsYou;
return !followerSet.has(u.username.toLowerCase());
});
return {
ok: true,
result: {
nonFollowers,
followingCount: following.length,
followersCount: followers.length,
},
};
}
case "cleanup.unfollow": {
const me = username || (await readPageAccount())?.username || "";
if (!me) throw new Error("缺少 username");
await navigateTab(tabId, `https://x.com/${me}/following`);
return runOnPage(tabId, jobId, kind, params);
}
case "cleanup.unfollow_visible": {
const me = username || (await readPageAccount())?.username || "";
if (!me) throw new Error("缺少 username");
await navigateTab(tabId, `https://x.com/${me}/following`);
return runOnPage(tabId, jobId, kind, params);
}
case "cleanup.mute":
case "cleanup.unmute":
case "cleanup.block":
case "cleanup.unblock": {
const list = ((params.usernames as string[]) || [])
.map((u) => String(u).replace(/^@/, "").trim())
.filter(Boolean);
if (!list.length) throw new Error("缺少 usernames");
const done: string[] = [];
const skipped: string[] = [];
const action =
kind === "cleanup.mute"
? "mute"
: kind === "cleanup.unmute"
? "unmute"
: kind === "cleanup.block"
? "block"
: "unblock";
for (let i = 0; i < list.length; i++) {
if (cancelledLocal.has(jobId)) {
return { ok: false, error: "用户取消" };
}
const u = list[i];
await navigateTab(tabId, `https://x.com/${u}`);
const res = await runOnPage(tabId, jobId, kind, { ...params, username: u });
if (res.ok) done.push(u);
else skipped.push(u);
await new Promise((r) =>
setTimeout(
r,
Number(params.minDelayMs ?? 2000) +
Math.random() *
Math.max(
0,
Number(params.maxDelayMs ?? 5000) - Number(params.minDelayMs ?? 2000),
),
),
);
}
return {
ok: true,
result: {
action,
done,
skipped,
requested: list.length,
},
};
}
case "engage.post": {
// Fresh compose page — avoids Draft.js phantom char count from leftover drafts
await navigateTab(tabId, "https://x.com/compose/post");
return runOnPage(tabId, jobId, kind, params);
}
case "engage.reply":
case "engage.retweet":
case "engage.unretweet":
case "engage.quote":
case "engage.bookmark":
case "engage.unbookmark":
case "engage.delete":
case "engage.pin":
case "engage.unpin":
case "engage.copy_link": {
if (!statusUrl) throw new Error("缺少推文链接 statusUrl");
await navigateTab(tabId, statusUrl);
return runOnPage(tabId, jobId, kind, params);
}
case "engage.like":
case "engage.unlike": {
if (statusUrl) {
await navigateTab(tabId, statusUrl);
return runOnPage(tabId, jobId, kind, params);
}
if (query) {
const q = encodeURIComponent(query);
await navigateTab(
tabId,
`https://x.com/search?q=${q}&src=typed_query&f=live`,
);
}
return runOnPage(tabId, jobId, kind, params);
}
case "engage.follow": {
const list = ((params.usernames as string[]) || [])
.map((u) => String(u).replace(/^@/, "").trim())
.filter(Boolean);
if (list.length) {
const followed: string[] = [];
const skipped: string[] = [];
for (const u of list) {
if (cancelledLocal.has(jobId)) {
return { ok: false, error: "用户取消" };
}
await navigateTab(tabId, `https://x.com/${u}`);
const res = await runOnPage(tabId, jobId, kind, {
...params,
username: u,
singleProfile: true,
});
const r = (res.result || {}) as { followed?: number; already?: boolean };
if (res.ok && Number(r.followed || 0) > 0) followed.push(u);
else if (res.ok && r.already) followed.push(u);
else skipped.push(u);
await new Promise((r) =>
setTimeout(
r,
Number(params.minDelayMs ?? 2500) +
Math.random() *
Math.max(
0,
Number(params.maxDelayMs ?? 5000) - Number(params.minDelayMs ?? 2500),
),
),
);
}
return {
ok: true,
result: {
followed: followed.length,
users: followed,
skipped,
requested: list.length,
},
};
}
if (query) {
const q = encodeURIComponent(query);
await navigateTab(
tabId,
`https://x.com/search?q=${q}&src=typed_query&f=user`,
);
}
return runOnPage(tabId, jobId, kind, params);
}
case "growth.engage": {
if (!query) throw new Error("缺少关键词 query");
const q = encodeURIComponent(query);
await navigateTab(
tabId,
`https://x.com/search?q=${q}&src=typed_query&f=live`,
);
return runOnPage(tabId, jobId, kind, params);
}
case "growth.home": {
await navigateTab(tabId, "https://x.com/home");
return runOnPage(tabId, jobId, kind, params);
}
default: {
return runOnPage(tabId, jobId, kind, params);
}
}
}
async function handleAgentJobExec(payload: ExtensionJobExecPayload) {
try {
const result = await executeJobPayload(payload);
ws?.send(
JSON.stringify(
envelope("job.result", {
jobId: payload.jobId,
ok: !!result.ok,
result: result.result,
error: result.error,
}),
),
);
} catch (err) {
ws?.send(
JSON.stringify(
envelope("job.result", {
jobId: payload.jobId,
ok: false,
error: err instanceof Error ? err.message : String(err),
}),
),
);
}
}
async function runLocalJob(job: LocalJob) {
if (cancelledLocal.has(job.id)) {
patchLocalJob(job.id, { status: "cancelled", error: "用户取消" });
return;
}
patchLocalJob(job.id, {
status: "running",
progress: { current: 0, total: 1, message: "启动中…" },
});
try {
const result = await executeJobPayload({
jobId: job.id,
kind: job.kind,
params: job.params,
});
if (cancelledLocal.has(job.id)) {
patchLocalJob(job.id, { status: "cancelled", error: "用户取消" });
return;
}
if (result.ok) {
const base: Record<string, unknown> =
typeof result.result === "object" && result.result
? { ...(result.result as Record<string, unknown>) }
: { value: result.result };
base.finishedAt = nowIso();
if (job.params.username) base.account = String(job.params.username).replace(/^@/, "");
if (job.kind === "engage.post" || job.kind === "engage.reply" || job.kind === "engage.quote") {
base.text = base.text || job.params.text || "";
base.postedAt = base.postedAt || base.finishedAt;
}
if (
(job.kind === "engage.like" ||
job.kind === "engage.unlike" ||
job.kind === "engage.follow" ||
job.kind === "growth.engage" ||
job.kind === "cleanup.unfollow_visible") &&
job.params.limit != null
) {
base.requested = Number(job.params.limit);
}
patchLocalJob(job.id, {
status: "completed",
result: base,
progress: { current: 1, total: 1, message: "做完了" },
});
} else {
patchLocalJob(job.id, {
status: "failed",
error: result.error || "失败",
progress: { current: 0, total: 1, message: "失败" },
});
}
} catch (err) {
patchLocalJob(job.id, {
status: cancelledLocal.has(job.id) ? "cancelled" : "failed",
error: err instanceof Error ? err.message : String(err),
});
} finally {
cancelledLocal.delete(job.id);
}
}
async function createViaAgent(
kind: JobKind,
params: Record<string, unknown>,
): Promise<JobRecord | null> {
const res = await fetch(`${AGENT_HTTP}/api/jobs`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ kind, params }),
});
const data = await res.json();
return (data.job as JobRecord) || null;
}
async function createJobFromUi(
kind: JobKind,
params: Record<string, unknown>,
preferAgent: boolean,
) {
const account = cachedAccount || (await readPageAccount());
const username =
String(params.username || account?.username || "").replace(/^@/, "") ||
undefined;
const merged = { ...params, ...(username ? { username } : {}) };
if (preferAgent && state === "connected") {
try {
const job = await createViaAgent(kind, merged);
if (job) {
broadcastUi({ type: "job.updated", job: { ...job, source: "agent" } });
return { ok: true, mode: "agent" as const, job };
}
} catch {
/* fall through to local */
}
}
const job: LocalJob = {
id: newLocalId(),
kind,
status: "queued",
params: merged,
progress: { current: 0, total: 1, message: "排队中" },
createdAt: nowIso(),
updatedAt: nowIso(),
source: "local",
};
upsertLocalJob(job);
void runLocalJob(job);
return { ok: true, mode: "local" as const, job };
}
async function cancelJob(jobId: string) {
if (jobId.startsWith("local_")) {
cancelledLocal.add(jobId);
const job = localJobs.find((j) => j.id === jobId);
if (job && (job.status === "running" || job.status === "queued")) {
patchLocalJob(jobId, {
status: "cancelled",
error: "用户取消",
});
}
return { ok: true };
}
if (state === "connected") {
try {
const res = await fetch(`${AGENT_HTTP}/api/jobs/${jobId}/cancel`, {
method: "POST",
});
const data = await res.json();
return { ok: !!data.job, job: data.job };
} catch {
return { ok: false };
}
}
return { ok: false };
}
async function agentAlive(): Promise<boolean> {
try {
const res = await fetch(`${AGENT_HTTP}/health`, {
signal: AbortSignal.timeout(1200),
});
return res.ok;
} catch {
return false;
}
}
async function autoBindAccount(force = false) {
if (state !== "connected" || !ws || ws.readyState !== WebSocket.OPEN) return;
const account = await readPageAccount();
if (!account?.username) return;
const key = account.username.toLowerCase();
const store = chrome.storage.session ?? chrome.storage.local;
const last = await store.get(["lastBound"]);
if (!force && last.lastBound === key) return;
ws.send(
JSON.stringify(
envelope("account.bind", {
username: account.username,
displayName: account.displayName,
avatarUrl: account.avatarUrl,
}),
),
);
await store.set({ lastBound: key });
}
async function connect(force = false) {
if (!force && (state === "connecting" || state === "connected")) return;
if (force && ws) {
try {
ws.onclose = null;
ws.close();
} catch {
/* ignore */
}
ws = null;
}
setState("connecting");
if (!(await agentAlive())) {
setState("disconnected");
return;
}
try {
token = await pair();
} catch {
setState("disconnected");
return;
}
try {
ws = new WebSocket(AGENT_WS);
} catch {
setState("disconnected");
return;
}
const socket = ws;
const openTimer = setTimeout(() => {
if (state === "connecting") {
try {
socket.close();
} catch {
/* ignore */
}
setState("disconnected");
}
}, 4000);
socket.addEventListener("open", async () => {
clearTimeout(openTimer);
const account = await readPageAccount();
socket.send(
JSON.stringify(
envelope("hello", {
role: "extension" as const,
token,
account,
}),
),
);
});
socket.addEventListener("message", async (ev) => {
let msg: AgentEvent;
try {
msg = JSON.parse(String(ev.data)) as AgentEvent;
} catch {
return;
}
if (msg.type === "hello.ok") {
setState("connected");
await autoBindAccount(true);
return;
}
if (msg.type === "hello.err") {
token = "";
await chrome.storage.local.remove("token");
socket.close();
setState("disconnected");
return;
}
if (msg.type === "ping") {
socket.send(JSON.stringify(envelope("pong", { t: Date.now() })));
return;
}
if (msg.type === "job.exec") {
await handleAgentJobExec(msg.payload);
}
});
socket.addEventListener("close", () => {
clearTimeout(openTimer);
if (ws === socket) ws = null;
setState("disconnected");
});
socket.addEventListener("error", () => {
clearTimeout(openTimer);
try {
socket.close();
} catch {
/* ignore */
}
});
}
async function watchdogTick() {
if (state === "connected") {
if (!ws || ws.readyState !== WebSocket.OPEN) {
setState("disconnected");
} else {
try {
ws.send(JSON.stringify(envelope("ping", {})));
} catch {
setState("disconnected");
}
await autoBindAccount(false);
return;
}
}
if (state === "connecting") return;
await connect(false);
}
function armWatchdog() {
chrome.alarms.create("x2.watchdog", { when: Date.now() + 2000 });
}
function rootJobId(phaseOrId: string) {
return String(phaseOrId).split(":")[0];
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === "popup.getState") {
void (async () => {
let agentJobs: JobRecord[] = [];
if (state === "connected") {
try {
const res = await fetch(`${AGENT_HTTP}/api/jobs`);
const data = await res.json();
agentJobs = (data.jobs || []) as JobRecord[];
} catch {
/* ignore */
}
}
const merged = [
...localJobs,
...agentJobs.filter((aj) => !localJobs.some((lj) => lj.id === aj.id)),
].sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
sendResponse({
state,
auto: true,
account: cachedAccount,
jobs: merged.slice(0, 40),
mode: state === "connected" ? "paired" : "standalone",
});
})();
return true;
}
if (message?.type === "popup.reconnect") {
void connect(true);
sendResponse({ ok: true, state: "connecting" });
return false;
}
if (message?.type === "popup.refreshAccount") {
void readPageAccount().then((account) => {
sendResponse({ ok: true, account });
});
return true;
}
if (message?.type === "popup.createJob") {
const kind = message.kind as JobKind;
const params = (message.params || {}) as Record<string, unknown>;
const preferAgent = message.preferAgent !== false;
void createJobFromUi(kind, params, preferAgent).then((res) => {
sendResponse(res);
});
return true;
}
if (message?.type === "popup.cancelJob") {
void cancelJob(String(message.jobId)).then((res) => sendResponse(res));
return true;
}
if (message?.type === "popup.clearJobs") {
for (let i = localJobs.length - 1; i >= 0; i--) {
const s = localJobs[i].status;
if (s === "completed" || s === "failed" || s === "cancelled") {
localJobs.splice(i, 1);
}
}
broadcastUi({ type: "jobs.cleared", jobs: localJobs.slice(0, 30) });
void chrome.storage.local.set({ localJobs: localJobs.slice(0, 40) });
sendResponse({ ok: true, jobs: localJobs.slice(0, 30) });
return false;
}
if (message?.type === "popup.openX") {
void ensureXTab().then(() => sendResponse({ ok: true }));
return true;
}
if (message?.type === "content.progress") {
const rootId = rootJobId(String(message.jobId));
const progress = message.progress as JobProgress;
if (rootId.startsWith("local_") || rootId.startsWith("web_")) {
patchLocalJob(rootId, {
status: "running" as JobStatus,
progress,
});
}
ws?.send(
JSON.stringify(
envelope("job.progress", {
jobId: rootId,
progress,
}),
),
);
return false;
}
// Content scripts cannot CORS-fetch S3 from x.com — download here with host_permissions.
if (message?.type === "media.fetch") {
void (async () => {
try {
const url = String(message.url || "").trim();
if (!url) throw new Error("缺少媒体 URL");
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new Error("媒体 URL 无效");
}
const host = parsed.hostname.toLowerCase();
const allowed =
host === "s3.nomadro.com" ||
host === "feiniu.nomadro.com" ||
host.endsWith(".nomadro.com") ||
host === "127.0.0.1" ||
host === "localhost";
if (!allowed) throw new Error(`不允许的媒体域名: ${host}`);
if (parsed.protocol !== "https:" && host !== "127.0.0.1" && host !== "localhost") {
throw new Error("仅支持 https 媒体地址");
}
const res = await fetch(url, { method: "GET", credentials: "omit", cache: "no-store" });
if (!res.ok) throw new Error(`下载媒体失败 HTTP ${res.status}`);
const mimeHint = String(message.mime || "").trim();
const nameHint = String(message.name || "").trim() || "media.bin";
const buf = new Uint8Array(await res.arrayBuffer());
if (!buf.byteLength) throw new Error("媒体文件为空");
// ~48MB raw → base64 ~64MB; keep headroom for chrome.runtime messaging
if (buf.byteLength > 48 * 1024 * 1024) {
throw new Error(`媒体过大(${Math.round(buf.byteLength / 1024 / 1024)}MB),请缩短切片`);
}
let binary = "";
const chunk = 0x8000;
for (let i = 0; i < buf.length; i += chunk) {
const slice = buf.subarray(i, i + chunk);
binary += String.fromCharCode.apply(null, Array.from(slice) as unknown as number[]);
}
const base64 = btoa(binary);
const ctype =
mimeHint ||
res.headers.get("content-type")?.split(";")[0]?.trim() ||
"application/octet-stream";
sendResponse({
ok: true,
base64,
mime: ctype,
name: nameHint,
size: buf.byteLength,
});
} catch (exc) {
const msg = exc instanceof Error ? exc.message : String(exc);
sendResponse({ ok: false, error: msg || "Failed to fetch" });
}
})();
return true;
}
if (message?.type === "content.jobResult") {
const jobId = String(message.jobId);
const pending = pendingJobs.get(jobId);
if (pending) {
clearTimeout(pending.timer);
pendingJobs.delete(jobId);
pending.resolve({
ok: !!message.ok,
result: message.result,
error: message.error,
});
}
return false;
}
// Auto-pair from dylive web (visit /x while logged in) — does not change X popup UX
if (message?.type === "DYLIVE_X_AUTO_PAIR") {
void applyDyliveAutoPair(message).then(() => sendResponse({ ok: true }));
return true;
}
// ---------- TikTok Cookie module ----------
if (message?.type === "GET_TIKTOK_COOKIES") {
void (async () => {
try {
const byName: Record<string, string> = {};
const absorb = (list: chrome.cookies.Cookie[] | null | undefined) => {
for (const c of list || []) {
if (c?.name && c.value) byName[c.name] = String(c.value);
}
};
const urls = [
"https://www.tiktok.com/",
"https://www.tiktok.com",
"https://tiktok.com/",
"https://www.tiktok.com/foryou",
"https://www.tiktok.com/login",
];
const domains = [".tiktok.com", "tiktok.com", ".www.tiktok.com", "www.tiktok.com"];
await Promise.all([
...urls.map((url) => chrome.cookies.getAll({ url }).then(absorb).catch(() => undefined)),
...domains.map((domain) =>
chrome.cookies.getAll({ domain }).then(absorb).catch(() => undefined),
),
]);
// Partitioned cookies (CHIPS) are omitted from default getAll in modern Chrome.
for (const topLevelSite of ["https://www.tiktok.com", "https://tiktok.com"]) {
try {
absorb(
await chrome.cookies.getAll({
domain: ".tiktok.com",
partitionKey: { topLevelSite },
} as chrome.cookies.GetAllDetails),
);
} catch {
/* older Chrome without partitionKey */
}
try {
absorb(
await chrome.cookies.getAll({
url: `${topLevelSite}/`,
partitionKey: { topLevelSite },
} as chrome.cookies.GetAllDetails),
);
} catch {
/* ignore */
}
}
// Explicit name lookups — tt-target-idc is easy to miss via domain-only scans.
for (const name of ["sessionid", "sessionid_ss", "tt-target-idc", "uniqueid"]) {
for (const url of urls) {
try {
const c = await chrome.cookies.get({ url, name });
if (c?.value) byName[c.name] = String(c.value);
} catch {
/* ignore */
}
}
}
const sessionid = String(byName.sessionid || byName.sessionid_ss || "").trim();
const dc = String(byName["tt-target-idc"] || byName.tt_target_idc || "").trim();
const handle = String(byName.uniqueid || byName.uniqueId || "").trim();
const payload = {
sessionid,
dc_id: dc,
"tt-target-idc": dc,
tiktok_username: handle,
};
sendResponse({
ok: Boolean(sessionid),
sessionid,
dc_id: dc,
tiktok_username: handle,
payload,
error: sessionid
? ""
: "未找到 sessionid。请用同一 Chrome 打开并登录 https://www.tiktok.com",
});
} catch (err) {
sendResponse({ ok: false, error: String(err) });
}
})();
return true;
}
return false;
});
chrome.alarms.onAlarm.addListener((a) => {
if (a.name === "x2.watchdog") {
void watchdogTick().finally(() => armWatchdog());
}
if (a.name === "dylive.heartbeat") {
void pushHeartbeatToDouyin();
wsHeartbeatTick();
}
if (a.name === "dylive.ws") {
wsHeartbeatTick();
void pollWebQueueFallback();
}
});
chrome.alarms.create("dylive.heartbeat", { periodInMinutes: 2 });
chrome.alarms.create("dylive.ws", { periodInMinutes: 1 });
// Keep WS alive while SW is awake
setInterval(() => {
wsHeartbeatTick();
}, 12000);
void ensureDyliveWs(false);
chrome.tabs.onUpdated.addListener((_tabId, info, tab) => {
if (info.status !== "complete") return;
const url = tab.url || "";
if (!/https:\/\/(x|twitter)\.com\//.test(url)) return;
void autoBindAccount(true);
void readPageAccount();
});
chrome.tabs.onActivated.addListener(() => {
void autoBindAccount(true);
});
chrome.runtime.onStartup.addListener(() => {
void connect(true);
armWatchdog();
void pushHeartbeatToDouyin();
});
chrome.runtime.onInstalled.addListener(() => {
void connect(true);
armWatchdog();
void pushHeartbeatToDouyin();
});
void (async () => {
const stored = await chrome.storage.local.get(["localJobs"]);
if (Array.isArray(stored.localJobs)) {
for (const j of stored.localJobs as LocalJob[]) {
if (j?.id) {
if (j.status === "running" || j.status === "queued") {
j.status = "failed";
j.error = "扩展重启,任务中断";
}
localJobs.push(j);
}
}
}
token = await loadToken();
void connect(true);
armWatchdog();
void readPageAccount();
void pushHeartbeatToDouyin();
})();