feat: Web /x 控制台下发任务,插件自动配对领取执行
插件 X popup 保持可独立运行;打开本站即可自动配对,无需手填 Token。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
9806ed3a0a
commit
57690bd286
@ -15,6 +15,7 @@ _PUBLIC_PATHS = {
|
||||
"/api/tiktok/oauth/callback",
|
||||
"/api/events/stream",
|
||||
"/api/x2/ingest",
|
||||
"/api/x2/extension/poll",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -878,6 +878,66 @@ async def x2_accounts_list(limit: int = Query(50, ge=1, le=200)) -> dict[str, An
|
||||
return {"accounts": rows}
|
||||
|
||||
|
||||
@app.post("/api/x2/jobs")
|
||||
async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Web console creates a job; Chrome extension claims & executes it."""
|
||||
from . import x2_db
|
||||
|
||||
kind = str(body.get("kind") or "").strip()
|
||||
params = body.get("params") if isinstance(body.get("params"), dict) else {}
|
||||
try:
|
||||
job = await _db(x2_db.create_web_job, kind, params)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
return {"ok": True, "job": job}
|
||||
|
||||
|
||||
@app.post("/api/x2/jobs/{job_id}/cancel")
|
||||
async def x2_jobs_cancel(job_id: str) -> dict[str, Any]:
|
||||
from . import x2_db
|
||||
|
||||
job = await _db(x2_db.cancel_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
return {"ok": True, "job": job}
|
||||
|
||||
|
||||
@app.post("/api/x2/extension/poll")
|
||||
async def x2_extension_poll(request: Request, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""Extension heartbeat + claim next queued job. Auth: X-X2-Token (auto-synced from /x)."""
|
||||
from . import x2_db
|
||||
|
||||
token = (
|
||||
(request.headers.get("X-X2-Token") or "")
|
||||
or (request.headers.get("x-x2-token") or "")
|
||||
or (request.query_params.get("token") or "")
|
||||
).strip()
|
||||
if not x2_db.verify_ingest_token(token):
|
||||
raise HTTPException(401, "无效 Token")
|
||||
payload = body if isinstance(body, dict) else {}
|
||||
agent_id = str(payload.get("agent_id") or "dylive-helper").strip() or "dylive-helper"
|
||||
label = str(payload.get("label") or "dylive Helper").strip() or "dylive Helper"
|
||||
accounts = payload.get("accounts") if isinstance(payload.get("accounts"), list) else None
|
||||
await _db(
|
||||
x2_db.ingest_payload,
|
||||
{
|
||||
"agent_id": agent_id,
|
||||
"label": label,
|
||||
"event": "heartbeat",
|
||||
"extension_connected": True,
|
||||
"source": "dylive-helper",
|
||||
"accounts": accounts,
|
||||
"message": "poll",
|
||||
},
|
||||
)
|
||||
cancel_ids = await _db(x2_db.list_cancel_requested, agent_id)
|
||||
busy = bool(payload.get("busy"))
|
||||
job = None
|
||||
if not busy:
|
||||
job = await _db(x2_db.claim_next_job, agent_id)
|
||||
return {"ok": True, "job": job, "cancel_ids": cancel_ids}
|
||||
|
||||
|
||||
# ---------- TikTok (fully isolated from Shorts) ----------
|
||||
|
||||
def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
|
||||
@ -32,6 +32,7 @@ _PUBLIC_API_EXACT = {
|
||||
"/api/tiktok/oauth/callback",
|
||||
"/api/events/stream",
|
||||
"/api/x2/ingest",
|
||||
"/api/x2/extension/poll",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -441,11 +441,16 @@ def status_snapshot() -> dict[str, Any]:
|
||||
running = sum(1 for j in jobs if str(j.get("status") or "") == "running")
|
||||
failed = sum(1 for j in jobs if str(j.get("status") or "") == "failed")
|
||||
completed = sum(1 for j in jobs if str(j.get("status") or "") == "completed")
|
||||
queued = sum(1 for j in jobs if str(j.get("status") or "") == "queued")
|
||||
token = ensure_ingest_token()
|
||||
hint = (token[:4] + "…" + token[-4:]) if len(token) > 8 else ("***" if token else "")
|
||||
ext_online = any(
|
||||
a.get("online") and a.get("extension_connected") for a in agents
|
||||
)
|
||||
return {
|
||||
"agents": agents,
|
||||
"online_count": len(online),
|
||||
"extension_online": ext_online,
|
||||
"accounts": accounts,
|
||||
"jobs": jobs,
|
||||
"events": events,
|
||||
@ -454,8 +459,180 @@ def status_snapshot() -> dict[str, Any]:
|
||||
"accounts": len(accounts),
|
||||
"jobs_shown": len(jobs),
|
||||
"running": running,
|
||||
"queued": queued,
|
||||
"failed": failed,
|
||||
"completed": completed,
|
||||
},
|
||||
"ingest_token_hint": hint,
|
||||
}
|
||||
|
||||
|
||||
def _job_to_client(d: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize DB row to extension/web job shape."""
|
||||
params = d.get("params") if isinstance(d.get("params"), dict) else {}
|
||||
if not params:
|
||||
try:
|
||||
params = json.loads(str(d.get("params_json") or "{}"))
|
||||
except Exception:
|
||||
params = {}
|
||||
result = d.get("result") if isinstance(d.get("result"), dict) else {}
|
||||
if not result:
|
||||
try:
|
||||
result = json.loads(str(d.get("result_json") or "{}"))
|
||||
except Exception:
|
||||
result = {}
|
||||
return {
|
||||
"id": str(d.get("id") or ""),
|
||||
"kind": str(d.get("kind") or ""),
|
||||
"status": str(d.get("status") or ""),
|
||||
"params": params,
|
||||
"result": result,
|
||||
"error": str(d.get("error") or ""),
|
||||
"progress": {
|
||||
"current": int(d.get("progress_current") or 0),
|
||||
"total": int(d.get("progress_total") or 0),
|
||||
"message": str(d.get("progress_message") or ""),
|
||||
},
|
||||
"accountId": str(d.get("account_id") or ""),
|
||||
"account_username": str(d.get("account_username") or ""),
|
||||
"agent_id": str(d.get("agent_id") or ""),
|
||||
"createdAt": str(d.get("job_created_at") or ""),
|
||||
"updatedAt": str(d.get("job_updated_at") or ""),
|
||||
"received_at": d.get("received_at"),
|
||||
}
|
||||
|
||||
|
||||
def create_web_job(
|
||||
kind: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
*,
|
||||
agent_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
k = str(kind or "").strip()
|
||||
if not k:
|
||||
raise ValueError("缺少 kind")
|
||||
jid = f"web_{uuid.uuid4().hex[:16]}"
|
||||
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
job = {
|
||||
"id": jid,
|
||||
"kind": k,
|
||||
"status": "queued",
|
||||
"params": params or {},
|
||||
"progress": {"current": 0, "total": 1, "message": "排队等待插件领取"},
|
||||
"createdAt": now_iso,
|
||||
"updatedAt": now_iso,
|
||||
}
|
||||
row = upsert_job(str(agent_id or "").strip() or "web", job)
|
||||
add_event(str(agent_id or "web"), "job.queued", f"{k} 已入队", {"job_id": jid})
|
||||
return _job_to_client(row or job)
|
||||
|
||||
|
||||
def claim_next_job(agent_id: str) -> dict[str, Any] | None:
|
||||
aid = str(agent_id or "").strip() or "dylive-helper"
|
||||
now = time.time()
|
||||
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_x2_tables(conn)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT * FROM x2_jobs
|
||||
WHERE status = 'queued'
|
||||
ORDER BY received_at ASC
|
||||
LIMIT 1
|
||||
"""
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
d = _row_to_dict(row) or {}
|
||||
jid = str(d.get("id") or "")
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE x2_jobs
|
||||
SET status = 'running',
|
||||
agent_id = ?,
|
||||
progress_message = ?,
|
||||
job_updated_at = ?,
|
||||
received_at = ?
|
||||
WHERE id = ? AND status = 'queued'
|
||||
""",
|
||||
(aid, "插件执行中", now_iso, now, jid),
|
||||
)
|
||||
if conn.total_changes == 0:
|
||||
conn.commit()
|
||||
return None
|
||||
conn.commit()
|
||||
refreshed = _row_to_dict(
|
||||
conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
|
||||
)
|
||||
return _job_to_client(refreshed or d)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def cancel_job(job_id: str) -> dict[str, Any] | None:
|
||||
jid = str(job_id or "").strip()
|
||||
if not jid:
|
||||
return None
|
||||
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_x2_tables(conn)
|
||||
row = conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
d = _row_to_dict(row) or {}
|
||||
st = str(d.get("status") or "")
|
||||
if st in {"completed", "failed", "cancelled"}:
|
||||
return _job_to_client(d)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE x2_jobs
|
||||
SET status = 'cancelled',
|
||||
error = ?,
|
||||
progress_message = ?,
|
||||
job_updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
("用户取消", "已取消", now_iso, jid),
|
||||
)
|
||||
conn.commit()
|
||||
refreshed = _row_to_dict(
|
||||
conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
|
||||
)
|
||||
return _job_to_client(refreshed or d)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_cancel_requested(agent_id: str = "") -> list[str]:
|
||||
"""Jobs cancelled while possibly still running on extension."""
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_x2_tables(conn)
|
||||
# recent cancelled in last 10 min
|
||||
cutoff = time.time() - 600
|
||||
if agent_id:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id FROM x2_jobs
|
||||
WHERE status = 'cancelled' AND agent_id = ? AND received_at >= ?
|
||||
ORDER BY received_at DESC LIMIT 20
|
||||
""",
|
||||
(agent_id, cutoff),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id FROM x2_jobs
|
||||
WHERE status = 'cancelled' AND received_at >= ?
|
||||
ORDER BY received_at DESC LIMIT 20
|
||||
""",
|
||||
(cutoff,),
|
||||
).fetchall()
|
||||
return [str(r[0]) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
3
extensions/dylive-helper/.gitignore
vendored
Normal file
3
extensions/dylive-helper/.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.log
|
||||
26
extensions/dylive-helper/README.md
Normal file
26
extensions/dylive-helper/README.md
Normal file
@ -0,0 +1,26 @@
|
||||
# dylive Helper
|
||||
|
||||
TikTok Cookie + X2 Ops(popup **可独立运行**)。
|
||||
|
||||
与本站 Web `/x` 的对接(自动配对 / 任务队列)在后台完成,**不改变** X 页签原有操作方式。
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
cd extensions/dylive-helper
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
Chrome 加载:`extensions/dylive-helper/dist`
|
||||
|
||||
## 与 Web /x
|
||||
|
||||
1. 登录 https://dylive.nomadro.com 并打开 `/x`(或任意本站页)→ 插件自动配对,无需手填 Token
|
||||
2. Web `/x` 下发任务 → 插件领取并在 x.com 执行 → 结果回写本站
|
||||
3. 插件 **X** 页签仍可像原来一样本地点按钮跑任务(独立模式)
|
||||
|
||||
## 顶栏
|
||||
|
||||
- **TikTok**:Cookie 导出
|
||||
- **X**:原 X2 Ops popup
|
||||
34
extensions/dylive-helper/content-dylive.js
Normal file
34
extensions/dylive-helper/content-dylive.js
Normal file
@ -0,0 +1,34 @@
|
||||
function fillCookieForm(payload) {
|
||||
const sid = document.getElementById("tiktok-sessionid");
|
||||
const dc = document.getElementById("tiktok-dc-id");
|
||||
const user = document.getElementById("tiktok-username");
|
||||
if (!sid || !dc) {
|
||||
window.dispatchEvent(new CustomEvent("dylive-tiktok-cookie", { detail: payload }));
|
||||
return { ok: false, reason: "form-hidden" };
|
||||
}
|
||||
const setNative = (el, value) => {
|
||||
const proto = Object.getPrototypeOf(el);
|
||||
const desc = Object.getOwnPropertyDescriptor(proto, "value");
|
||||
desc?.set?.call(el, value);
|
||||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
el.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
};
|
||||
setNative(sid, payload.sessionid || "");
|
||||
setNative(dc, payload.dc_id || "useast2a");
|
||||
if (user && payload.tiktok_username) setNative(user, payload.tiktok_username);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
|
||||
if (msg?.type !== "DYLIVE_FILL_TIKTOK_COOKIE") return;
|
||||
sendResponse(fillCookieForm(msg.payload || {}));
|
||||
});
|
||||
|
||||
window.addEventListener("dylive-tiktok-cookie-request", async () => {
|
||||
try {
|
||||
const data = await chrome.runtime.sendMessage({ type: "GET_TIKTOK_COOKIES" });
|
||||
if (data?.ok) window.dispatchEvent(new CustomEvent("dylive-tiktok-cookie", { detail: data.payload }));
|
||||
} catch {
|
||||
/* popup / page 未授权时忽略 */
|
||||
}
|
||||
});
|
||||
BIN
extensions/dylive-helper/icon.png
Normal file
BIN
extensions/dylive-helper/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 805 KiB |
60
extensions/dylive-helper/manifest.json
Normal file
60
extensions/dylive-helper/manifest.json
Normal file
@ -0,0 +1,60 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "dylive Helper",
|
||||
"version": "2.1.0",
|
||||
"description": "TikTok Cookie + X2 Ops(推送到 dylive /x)",
|
||||
"permissions": ["cookies", "storage", "tabs", "alarms", "scripting", "clipboardWrite"],
|
||||
"host_permissions": [
|
||||
"https://www.tiktok.com/*",
|
||||
"https://*.tiktok.com/*",
|
||||
"https://x.com/*",
|
||||
"https://twitter.com/*",
|
||||
"https://dylive.nomadro.com/*",
|
||||
"http://127.0.0.1/*",
|
||||
"http://localhost/*",
|
||||
"http://127.0.0.1:17888/*"
|
||||
],
|
||||
"icons": {
|
||||
"16": "icons/icon-16.png",
|
||||
"48": "icons/icon-48.png",
|
||||
"128": "icons/icon-128.png"
|
||||
},
|
||||
"background": {
|
||||
"service_worker": "background.js",
|
||||
"type": "module"
|
||||
},
|
||||
"action": {
|
||||
"default_popup": "popup.html",
|
||||
"default_title": "dylive Helper",
|
||||
"default_icon": {
|
||||
"16": "icons/icon-16.png",
|
||||
"48": "icons/icon-48.png",
|
||||
"128": "icons/icon-128.png"
|
||||
}
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": [
|
||||
"https://dylive.nomadro.com/tiktok*",
|
||||
"http://127.0.0.1:*/tiktok*",
|
||||
"http://localhost:*/tiktok*"
|
||||
],
|
||||
"js": ["content-dylive.js"],
|
||||
"run_at": "document_idle"
|
||||
},
|
||||
{
|
||||
"matches": [
|
||||
"https://dylive.nomadro.com/*",
|
||||
"http://127.0.0.1:*/*",
|
||||
"http://localhost:*/*"
|
||||
],
|
||||
"js": ["content-dylive-bridge.js"],
|
||||
"run_at": "document_idle"
|
||||
},
|
||||
{
|
||||
"matches": ["https://x.com/*", "https://twitter.com/*"],
|
||||
"js": ["content.js"],
|
||||
"run_at": "document_idle"
|
||||
}
|
||||
]
|
||||
}
|
||||
2365
extensions/dylive-helper/package-lock.json
generated
Normal file
2365
extensions/dylive-helper/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
25
extensions/dylive-helper/package.json
Normal file
25
extensions/dylive-helper/package.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "dylive-helper",
|
||||
"version": "2.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build:shared": "tsc -p vendor/shared/tsconfig.json",
|
||||
"build": "vite build",
|
||||
"dev": "vite build --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-react": "^1.28.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/chrome": "^0.0.313",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.8.2",
|
||||
"vite": "^6.2.2",
|
||||
"vite-plugin-static-copy": "^2.3.0"
|
||||
}
|
||||
}
|
||||
BIN
extensions/dylive-helper/public/icons/icon-128.png
Normal file
BIN
extensions/dylive-helper/public/icons/icon-128.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 908 KiB |
BIN
extensions/dylive-helper/public/icons/icon-16.png
Normal file
BIN
extensions/dylive-helper/public/icons/icon-16.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 908 KiB |
BIN
extensions/dylive-helper/public/icons/icon-48.png
Normal file
BIN
extensions/dylive-helper/public/icons/icon-48.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 908 KiB |
BIN
extensions/dylive-helper/public/icons/tiktok-icon.png
Normal file
BIN
extensions/dylive-helper/public/icons/tiktok-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 805 KiB |
1052
extensions/dylive-helper/src/PopupApp.tsx
Normal file
1052
extensions/dylive-helper/src/PopupApp.tsx
Normal file
File diff suppressed because it is too large
Load Diff
126
extensions/dylive-helper/src/TikTokPanel.tsx
Normal file
126
extensions/dylive-helper/src/TikTokPanel.tsx
Normal file
@ -0,0 +1,126 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
const CONSOLE_URL = "https://dylive.nomadro.com/tiktok";
|
||||
|
||||
function mask(v: string) {
|
||||
const s = String(v || "");
|
||||
if (s.length <= 8) return s ? "***" : "—";
|
||||
return `${s.slice(0, 4)}…${s.slice(-4)}`;
|
||||
}
|
||||
|
||||
type CookieRes = {
|
||||
ok?: boolean;
|
||||
sessionid?: string;
|
||||
dc_id?: string;
|
||||
payload?: { sessionid: string; dc_id: string; tiktok_username?: string };
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export function TikTokPanel() {
|
||||
const [status, setStatus] = useState<{ kind: string; text: string }>({
|
||||
kind: "idle",
|
||||
text: "正在读取…",
|
||||
});
|
||||
const [sid, setSid] = useState("—");
|
||||
const [dc, setDc] = useState("—");
|
||||
const [payload, setPayload] = useState<CookieRes["payload"] | null>(null);
|
||||
|
||||
const load = async () => {
|
||||
const data = (await chrome.runtime.sendMessage({
|
||||
type: "GET_TIKTOK_COOKIES",
|
||||
})) as CookieRes;
|
||||
setPayload(data?.ok ? data.payload || null : null);
|
||||
setSid(data?.ok ? mask(String(data.sessionid || "")) : "未登录 / 未找到");
|
||||
setDc(data?.dc_id || "useast2a");
|
||||
if (data?.ok) setStatus({ kind: "ok", text: "已读到 Cookie,可复制或填入控制台" });
|
||||
else
|
||||
setStatus({
|
||||
kind: "err",
|
||||
text: data?.error || "请先在本浏览器登录 tiktok.com,再点插件",
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
const copy = async () => {
|
||||
if (!payload) return;
|
||||
await navigator.clipboard.writeText(JSON.stringify(payload));
|
||||
setStatus({ kind: "ok", text: "已复制 JSON,到控制台点「从剪贴板导入」" });
|
||||
};
|
||||
|
||||
const fill = async () => {
|
||||
if (!payload) return;
|
||||
const tabs = await chrome.tabs.query({});
|
||||
const target = tabs.find(
|
||||
(t) =>
|
||||
/\/tiktok(\?|$)/.test(t.url || "") &&
|
||||
/dylive\.nomadro\.com|127\.0\.0\.1|localhost/.test(t.url || ""),
|
||||
);
|
||||
if (!target?.id) {
|
||||
await chrome.tabs.create({ url: CONSOLE_URL });
|
||||
setStatus({
|
||||
kind: "idle",
|
||||
text: "已打开控制台。打开「粘贴 Cookie」后再点一次「填入控制台」",
|
||||
});
|
||||
return;
|
||||
}
|
||||
await chrome.tabs.update(target.id, { active: true });
|
||||
try {
|
||||
await chrome.tabs.sendMessage(target.id, {
|
||||
type: "DYLIVE_FILL_TIKTOK_COOKIE",
|
||||
payload,
|
||||
});
|
||||
} catch {
|
||||
await chrome.scripting.executeScript({
|
||||
target: { tabId: target.id },
|
||||
files: ["content-dylive.js"],
|
||||
});
|
||||
await chrome.tabs.sendMessage(target.id, {
|
||||
type: "DYLIVE_FILL_TIKTOK_COOKIE",
|
||||
payload,
|
||||
});
|
||||
}
|
||||
setStatus({ kind: "ok", text: "已填入控制台表单,确认后点保存" });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="tt-panel">
|
||||
<header className="tt-head">
|
||||
<h1>TikTok Cookie</h1>
|
||||
<p>登录 tiktok.com 后点导出,无需 F12</p>
|
||||
</header>
|
||||
<div className={`status ${status.kind}`}>{status.text}</div>
|
||||
<dl>
|
||||
<dt>sessionid</dt>
|
||||
<dd>{sid}</dd>
|
||||
<dt>tt-target-idc</dt>
|
||||
<dd>{dc}</dd>
|
||||
</dl>
|
||||
<div className="tt-actions">
|
||||
<button type="button" className="tt-primary" disabled={!payload} onClick={() => void copy()}>
|
||||
复制 JSON
|
||||
</button>
|
||||
<button type="button" className="tt-secondary" disabled={!payload} onClick={() => void fill()}>
|
||||
填入控制台
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="tt-muted"
|
||||
onClick={() => chrome.tabs.create({ url: "https://www.tiktok.com/login" })}
|
||||
>
|
||||
打开 TikTok 登录
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="tt-secondary"
|
||||
onClick={() => chrome.tabs.create({ url: CONSOLE_URL })}
|
||||
>
|
||||
打开 dylive /tiktok
|
||||
</button>
|
||||
</div>
|
||||
<p className="tt-hint">sessionid 等同密码,只粘贴到自己的 dylive 控制台。</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
1411
extensions/dylive-helper/src/background.ts
Normal file
1411
extensions/dylive-helper/src/background.ts
Normal file
File diff suppressed because it is too large
Load Diff
26
extensions/dylive-helper/src/content-dylive-bridge.js
Normal file
26
extensions/dylive-helper/src/content-dylive-bridge.js
Normal file
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Auto-pair with dylive web: when user is logged into /x (or any dylive page),
|
||||
* pull ingest token + origin and hand to the service worker. No manual paste.
|
||||
*/
|
||||
(async () => {
|
||||
try {
|
||||
const origin = location.origin;
|
||||
const res = await fetch(`${origin}/api/x2/status`, {
|
||||
credentials: "include",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const token = String(data?.ingest_token || "").trim();
|
||||
if (!token) return;
|
||||
chrome.runtime.sendMessage({
|
||||
type: "DYLIVE_X_AUTO_PAIR",
|
||||
origin,
|
||||
token,
|
||||
ingestUrl: `${origin}/api/x2/ingest`,
|
||||
pollUrl: `${origin}/api/x2/extension/poll`,
|
||||
});
|
||||
} catch {
|
||||
/* not logged in / offline */
|
||||
}
|
||||
})();
|
||||
34
extensions/dylive-helper/src/content-dylive.js
Normal file
34
extensions/dylive-helper/src/content-dylive.js
Normal file
@ -0,0 +1,34 @@
|
||||
function fillCookieForm(payload) {
|
||||
const sid = document.getElementById("tiktok-sessionid");
|
||||
const dc = document.getElementById("tiktok-dc-id");
|
||||
const user = document.getElementById("tiktok-username");
|
||||
if (!sid || !dc) {
|
||||
window.dispatchEvent(new CustomEvent("dylive-tiktok-cookie", { detail: payload }));
|
||||
return { ok: false, reason: "form-hidden" };
|
||||
}
|
||||
const setNative = (el, value) => {
|
||||
const proto = Object.getPrototypeOf(el);
|
||||
const desc = Object.getOwnPropertyDescriptor(proto, "value");
|
||||
desc?.set?.call(el, value);
|
||||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
el.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
};
|
||||
setNative(sid, payload.sessionid || "");
|
||||
setNative(dc, payload.dc_id || "useast2a");
|
||||
if (user && payload.tiktok_username) setNative(user, payload.tiktok_username);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
|
||||
if (msg?.type !== "DYLIVE_FILL_TIKTOK_COOKIE") return;
|
||||
sendResponse(fillCookieForm(msg.payload || {}));
|
||||
});
|
||||
|
||||
window.addEventListener("dylive-tiktok-cookie-request", async () => {
|
||||
try {
|
||||
const data = await chrome.runtime.sendMessage({ type: "GET_TIKTOK_COOKIES" });
|
||||
if (data?.ok) window.dispatchEvent(new CustomEvent("dylive-tiktok-cookie", { detail: data.payload }));
|
||||
} catch {
|
||||
/* popup / page 未授权时忽略 */
|
||||
}
|
||||
});
|
||||
1749
extensions/dylive-helper/src/content.ts
Normal file
1749
extensions/dylive-helper/src/content.ts
Normal file
File diff suppressed because it is too large
Load Diff
399
extensions/dylive-helper/src/hooks/usePopup.ts
Normal file
399
extensions/dylive-helper/src/hooks/usePopup.ts
Normal file
@ -0,0 +1,399 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { JobKind, JobRecord } from "@x2/shared";
|
||||
import { jobKindLabel } from "@x2/shared";
|
||||
|
||||
export type TabId = "cleanup" | "scrape" | "engage" | "monitor" | "jobs";
|
||||
|
||||
export const STATUS_ZH: Record<string, string> = {
|
||||
queued: "排队中",
|
||||
running: "进行中",
|
||||
completed: "已完成",
|
||||
failed: "出错了",
|
||||
cancelled: "已取消",
|
||||
paused: "已暂停",
|
||||
};
|
||||
|
||||
type Account = { username?: string; displayName?: string };
|
||||
|
||||
function send<T = unknown>(msg: Record<string, unknown>): Promise<T> {
|
||||
return new Promise((resolve) => {
|
||||
chrome.runtime.sendMessage(msg, (res) => {
|
||||
void chrome.runtime.lastError;
|
||||
resolve(res as T);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function summarizeResult(job: JobRecord): string {
|
||||
const name = jobKindLabel(job.kind);
|
||||
if (job.status === "failed") {
|
||||
return `${name}没做成\n原因:${job.error || "未知错误"}`;
|
||||
}
|
||||
if (job.status === "cancelled") return `${name}已取消`;
|
||||
if (job.status !== "completed") {
|
||||
const p = job.progress;
|
||||
const msg = p?.message || STATUS_ZH[job.status] || "进行中";
|
||||
if (p && p.total > 1) return `${msg}(${p.current}/${p.total})`;
|
||||
return msg;
|
||||
}
|
||||
const r = (job.result || {}) as Record<string, unknown>;
|
||||
if (job.kind === "cleanup.non_followers") {
|
||||
const non = (r.nonFollowers as Array<{ username: string }>) || [];
|
||||
return (
|
||||
`扫描完成:有 ${non.length} 人没回关你\n(看了关注 ${r.followingCount},粉丝 ${r.followersCount})\n` +
|
||||
non
|
||||
.slice(0, 40)
|
||||
.map((u) => `@${u.username}`)
|
||||
.join("\n") +
|
||||
(non.length > 40 ? `\n…还有 ${non.length - 40} 人` : "")
|
||||
);
|
||||
}
|
||||
if (job.kind === "scrape.profile") {
|
||||
return `${r.name || r.username}(@${r.username})\n粉丝 ${r.followersCount} · 关注 ${r.followingCount}\n${r.bio || "暂无简介"}`;
|
||||
}
|
||||
if (job.kind === "scrape.following" || job.kind === "scrape.followers") {
|
||||
const users = (r.users as Array<{ username: string }>) || [];
|
||||
const tip = job.kind === "scrape.following" ? "关注" : "粉丝";
|
||||
return (
|
||||
`抓到 ${users.length} 个${tip}\n` +
|
||||
users
|
||||
.slice(0, 50)
|
||||
.map((u) => `@${u.username}`)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "scrape.tweets") {
|
||||
const tweets = (r.tweets as Array<{ text?: string }>) || [];
|
||||
return (
|
||||
`抓到 ${tweets.length} 条推文\n` +
|
||||
tweets
|
||||
.slice(0, 20)
|
||||
.map((t) => t.text || "")
|
||||
.join("\n——\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "cleanup.unfollow" || job.kind === "cleanup.unfollow_visible") {
|
||||
const u = (r.unfollowed as string[]) || [];
|
||||
const s = (r.skipped as string[]) || [];
|
||||
const tip = job.kind === "cleanup.unfollow_visible" ? "可见页取关" : "取关";
|
||||
return (
|
||||
`${tip}完成:成功 ${u.length},跳过 ${s.length}\n` + u.map((x) => `@${x}`).join("\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "cleanup.mute" || job.kind === "cleanup.unmute" || job.kind === "cleanup.block" || job.kind === "cleanup.unblock") {
|
||||
const done = (r.done as string[]) || [];
|
||||
const tip =
|
||||
job.kind === "cleanup.mute"
|
||||
? "静音"
|
||||
: job.kind === "cleanup.unmute"
|
||||
? "取消静音"
|
||||
: job.kind === "cleanup.block"
|
||||
? "屏蔽"
|
||||
: "取消屏蔽";
|
||||
return `${tip}完成:${done.length} 人\n` + done.map((x) => `@${x}`).join("\n");
|
||||
}
|
||||
if (
|
||||
job.kind === "scrape.search" ||
|
||||
job.kind === "scrape.bookmarks" ||
|
||||
job.kind === "scrape.media" ||
|
||||
job.kind === "scrape.likes" ||
|
||||
job.kind === "scrape.thread" ||
|
||||
job.kind === "scrape.hashtag" ||
|
||||
job.kind === "scrape.home" ||
|
||||
job.kind === "scrape.mentions" ||
|
||||
job.kind === "scrape.with_replies"
|
||||
) {
|
||||
const tweets = (r.tweets as Array<{ text?: string }>) || [];
|
||||
const tip =
|
||||
job.kind === "scrape.search"
|
||||
? `搜索「${r.query || ""}」`
|
||||
: job.kind === "scrape.bookmarks"
|
||||
? "书签"
|
||||
: job.kind === "scrape.media"
|
||||
? `媒体(${r.mediaCount ?? tweets.length})`
|
||||
: job.kind === "scrape.likes"
|
||||
? "点赞时间线"
|
||||
: job.kind === "scrape.hashtag"
|
||||
? `话题 #${r.hashtag || ""}`
|
||||
: job.kind === "scrape.home"
|
||||
? "首页"
|
||||
: job.kind === "scrape.mentions"
|
||||
? "提及"
|
||||
: job.kind === "scrape.with_replies"
|
||||
? "含回复"
|
||||
: "推文串";
|
||||
return (
|
||||
`${tip}:${tweets.length} 条\n` +
|
||||
tweets
|
||||
.slice(0, 20)
|
||||
.map((t) => t.text || "")
|
||||
.join("\n——\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "scrape.people") {
|
||||
const users = (r.users as Array<{ username: string }>) || [];
|
||||
return (
|
||||
`搜人 ${users.length} 人\n` +
|
||||
users
|
||||
.slice(0, 50)
|
||||
.map((u) => `@${u.username}`)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "scrape.notifications") {
|
||||
const notices = (r.notices as Array<{ text?: string; type?: string }>) || [];
|
||||
return (
|
||||
`通知 ${notices.length} 条\n` +
|
||||
notices
|
||||
.slice(0, 30)
|
||||
.map((n) => `[${n.type || "?"}] ${n.text || ""}`)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "scrape.likers" || job.kind === "scrape.list" || job.kind === "scrape.retweeters" || job.kind === "scrape.quotes") {
|
||||
const users = (r.users as Array<{ username: string }>) || [];
|
||||
const tip =
|
||||
job.kind === "scrape.list"
|
||||
? "列表成员"
|
||||
: job.kind === "scrape.retweeters"
|
||||
? "转推用户"
|
||||
: job.kind === "scrape.quotes"
|
||||
? "引用用户"
|
||||
: "点赞用户";
|
||||
return (
|
||||
`${tip} ${users.length} 人\n` +
|
||||
users
|
||||
.slice(0, 50)
|
||||
.map((u) => `@${u.username}`)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "monitor.snapshot_followers") {
|
||||
const n = ((r.usernames as string[]) || []).length;
|
||||
const diff = r.diff as { gained?: string[]; lost?: string[] } | undefined;
|
||||
if (!diff) return `已记下当前 ${n} 个粉丝,下次再拍就能看出变化`;
|
||||
return `新粉 ${diff.gained?.length || 0} 人 · 掉粉 ${diff.lost?.length || 0} 人`;
|
||||
}
|
||||
if (job.kind === "engage.like") {
|
||||
return `点赞完成:一共点了 ${r.liked ?? 0} 个${r.requested ? `(目标 ${r.requested})` : ""}`;
|
||||
}
|
||||
if (job.kind === "engage.unlike") {
|
||||
return `取消点赞:一共取消了 ${r.unliked ?? 0} 个${r.requested ? `(目标 ${r.requested})` : ""}`;
|
||||
}
|
||||
if (job.kind === "engage.follow") {
|
||||
return `关注完成:一共关了 ${r.followed ?? 0} 个${r.requested ? `(目标 ${r.requested})` : ""}`;
|
||||
}
|
||||
if (job.kind === "engage.post" || job.kind === "engage.reply" || job.kind === "engage.quote") {
|
||||
const text = String(r.text || job.params?.text || "");
|
||||
const tip =
|
||||
job.kind === "engage.post" ? "发帖成功" : job.kind === "engage.reply" ? "回复成功" : "引用成功";
|
||||
return `${tip}\n\n${text || "(没有正文记录)"}`;
|
||||
}
|
||||
if (job.kind === "engage.retweet") return "转推成功";
|
||||
if (job.kind === "engage.unretweet") return "已取消转推";
|
||||
if (job.kind === "engage.delete") return "已删除推文";
|
||||
if (job.kind === "engage.pin") return "已置顶";
|
||||
if (job.kind === "engage.unpin") return "已取消置顶";
|
||||
if (job.kind === "engage.bookmark") {
|
||||
return `收藏成功${r.already ? "(本来就收藏过)" : ""}`;
|
||||
}
|
||||
if (job.kind === "engage.unbookmark") {
|
||||
return `已取消收藏${r.already ? "(本来就没收藏)" : ""}`;
|
||||
}
|
||||
if (job.kind === "monitor.snapshot_following") {
|
||||
const n = ((r.usernames as string[]) || []).length;
|
||||
const diff = r.diff as { newlyFollowed?: string[]; unfollowed?: string[] } | undefined;
|
||||
if (!diff) return `已记下 ${n} 个关注`;
|
||||
return `新关注 ${diff.newlyFollowed?.length || 0} · 取关了 ${diff.unfollowed?.length || 0}`;
|
||||
}
|
||||
if (job.kind === "analyze.profiles") {
|
||||
const ranking = (r.ranking as Array<{ username: string; followersCount?: number }>) || [];
|
||||
return (
|
||||
`对比 ${r.count || ranking.length} 个账号\n` +
|
||||
ranking
|
||||
.slice(0, 20)
|
||||
.map((p, i) => `${i + 1}. @${p.username} · ${p.followersCount ?? "—"}`)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
if (job.kind === "analyze.tweets") {
|
||||
return `推文表现:样本 ${r.count ?? 0} · 均赞 ${r.avgLikes ?? 0} · 均转 ${r.avgRetweets ?? 0}`;
|
||||
}
|
||||
if (job.kind === "growth.engage") {
|
||||
return `增长完成「${r.query || ""}」:赞 ${r.liked ?? 0} · 关 ${r.followed ?? 0} · 回 ${r.replied ?? 0}`;
|
||||
}
|
||||
if (job.kind === "growth.home") {
|
||||
return `首页互动:赞 ${r.liked ?? 0} · 关 ${r.followed ?? 0} · 回 ${r.replied ?? 0}`;
|
||||
}
|
||||
if (job.kind === "engage.copy_link") {
|
||||
return `链接已复制:${r.url || job.params?.statusUrl || ""}`;
|
||||
}
|
||||
return `${name}已完成`;
|
||||
}
|
||||
|
||||
export function nonFollowersFromJob(job: JobRecord | null): string[] {
|
||||
if (!job || job.kind !== "cleanup.non_followers" || job.status !== "completed") return [];
|
||||
const r = (job.result || {}) as { nonFollowers?: Array<{ username: string }> };
|
||||
return (r.nonFollowers || []).map((u) => u.username);
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const [toast, setToast] = useState<string | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const show = useCallback((msg: string) => {
|
||||
setToast(msg);
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => setToast(null), 1800);
|
||||
}, []);
|
||||
return { toast, show };
|
||||
}
|
||||
|
||||
export function usePopup(showToast: (msg: string) => void) {
|
||||
const [connState, setConnState] = useState("disconnected");
|
||||
const [account, setAccount] = useState<Account | undefined>();
|
||||
const [jobs, setJobs] = useState<JobRecord[]>([]);
|
||||
const [selectedJobId, setSelectedJobId] = useState<string | null>(null);
|
||||
const [tab, setTab] = useState<TabId>("cleanup");
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
const state = await send<{
|
||||
state?: string;
|
||||
account?: Account;
|
||||
jobs?: JobRecord[];
|
||||
}>({ type: "popup.getState" });
|
||||
if (!state) return;
|
||||
setConnState(state.state || "disconnected");
|
||||
if (state.account) setAccount(state.account);
|
||||
if (state.jobs) setJobs(state.jobs);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
const t = setInterval(() => void refresh(), 2000);
|
||||
return () => clearInterval(t);
|
||||
}, [refresh]);
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (msg: {
|
||||
type?: string;
|
||||
state?: string;
|
||||
account?: Account;
|
||||
job?: JobRecord;
|
||||
jobs?: JobRecord[];
|
||||
}) => {
|
||||
if (msg?.type === "conn.state") {
|
||||
setConnState(msg.state || "disconnected");
|
||||
if (msg.account) setAccount(msg.account);
|
||||
}
|
||||
if (msg?.type === "account.updated" && msg.account) {
|
||||
setAccount(msg.account);
|
||||
}
|
||||
if (msg?.type === "job.updated" && msg.job) {
|
||||
const job = msg.job;
|
||||
setJobs((prev) => [job, ...prev.filter((j) => j.id !== job.id)]);
|
||||
setSelectedJobId((id) => {
|
||||
if (
|
||||
id === job.id ||
|
||||
job.status === "completed" ||
|
||||
job.status === "failed" ||
|
||||
!id
|
||||
) {
|
||||
return job.id;
|
||||
}
|
||||
return id;
|
||||
});
|
||||
}
|
||||
if (msg?.type === "jobs.cleared" && msg.jobs) {
|
||||
setJobs(msg.jobs);
|
||||
}
|
||||
};
|
||||
chrome.runtime.onMessage.addListener(listener);
|
||||
return () => chrome.runtime.onMessage.removeListener(listener);
|
||||
}, []);
|
||||
|
||||
const createJob = useCallback(
|
||||
async (kind: JobKind, params: Record<string, unknown> = {}) => {
|
||||
const res = await send<{
|
||||
ok?: boolean;
|
||||
mode?: string;
|
||||
job?: JobRecord;
|
||||
}>({
|
||||
type: "popup.createJob",
|
||||
kind,
|
||||
params,
|
||||
preferAgent: true,
|
||||
});
|
||||
if (res?.job) {
|
||||
setJobs((prev) => [res.job!, ...prev.filter((j) => j.id !== res.job!.id)]);
|
||||
setSelectedJobId(res.job.id);
|
||||
showToast(res.mode === "agent" ? "已提交到桌面队列" : "独立任务已开始");
|
||||
return;
|
||||
}
|
||||
showToast("任务创建失败");
|
||||
},
|
||||
[showToast],
|
||||
);
|
||||
|
||||
const cancelJob = useCallback(
|
||||
async (jobId: string) => {
|
||||
await send({ type: "popup.cancelJob", jobId });
|
||||
showToast("已请求取消");
|
||||
},
|
||||
[showToast],
|
||||
);
|
||||
|
||||
const clearJobs = useCallback(async () => {
|
||||
const res = await send<{ jobs?: JobRecord[] }>({ type: "popup.clearJobs" });
|
||||
if (res?.jobs) setJobs(res.jobs);
|
||||
showToast("已清理");
|
||||
}, [showToast]);
|
||||
|
||||
const reconnect = useCallback(() => {
|
||||
void send({ type: "popup.reconnect" });
|
||||
showToast("正在重连桌面端…");
|
||||
}, [showToast]);
|
||||
|
||||
const openX = useCallback(() => {
|
||||
void send({ type: "popup.openX" });
|
||||
}, []);
|
||||
|
||||
const refreshAccount = useCallback(async () => {
|
||||
const res = await send<{ account?: Account }>({ type: "popup.refreshAccount" });
|
||||
if (res?.account?.username) {
|
||||
setAccount(res.account);
|
||||
showToast(`已识别 @${res.account.username}`);
|
||||
} else {
|
||||
setAccount(undefined);
|
||||
showToast("未检测到,请先刷新 x.com 页面");
|
||||
}
|
||||
}, [showToast]);
|
||||
|
||||
const selectedJob =
|
||||
jobs.find((j) => j.id === selectedJobId) || jobs[0] || null;
|
||||
|
||||
const lastNonFollowers = (() => {
|
||||
for (const j of jobs) {
|
||||
const list = nonFollowersFromJob(j);
|
||||
if (list.length) return list;
|
||||
}
|
||||
return [] as string[];
|
||||
})();
|
||||
|
||||
return {
|
||||
connState,
|
||||
account,
|
||||
jobs,
|
||||
selectedJobId,
|
||||
setSelectedJobId,
|
||||
selectedJob,
|
||||
tab,
|
||||
setTab,
|
||||
createJob,
|
||||
cancelJob,
|
||||
clearJobs,
|
||||
reconnect,
|
||||
openX,
|
||||
refreshAccount,
|
||||
lastNonFollowers,
|
||||
};
|
||||
}
|
||||
317
extensions/dylive-helper/src/popup.css
Normal file
317
extensions/dylive-helper/src/popup.css
Normal file
@ -0,0 +1,317 @@
|
||||
:root {
|
||||
--bg: #0f1419;
|
||||
--surface: #171d25;
|
||||
--surface-2: #1c2430;
|
||||
--fg: #e8eef5;
|
||||
--muted: #8b98a5;
|
||||
--accent: #ff8a65;
|
||||
--accent-2: #3dd6c3;
|
||||
--ok: #34d399;
|
||||
--warn: #fbbf24;
|
||||
--bad: #fb7185;
|
||||
--line: #2a3441;
|
||||
--danger: #fb7185;
|
||||
--font: "Manrope", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
--radius: 12px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
width: 390px;
|
||||
max-height: 600px;
|
||||
overflow: auto;
|
||||
font: 13px/1.45 var(--font);
|
||||
background:
|
||||
radial-gradient(120% 80% at 0% 0%, rgba(255, 138, 101, 0.16), transparent 55%),
|
||||
radial-gradient(90% 70% at 100% 0%, rgba(61, 214, 195, 0.1), transparent 50%),
|
||||
var(--bg);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 14px 8px;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.brand img {
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-weight: 800;
|
||||
font-size: 15px;
|
||||
letter-spacing: -0.02em;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.title-ico { color: var(--accent); }
|
||||
|
||||
.sub { color: var(--muted); font-size: 11px; margin-top: 2px; }
|
||||
|
||||
.top-right { display: flex; align-items: center; gap: 6px; }
|
||||
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
padding: 4px 9px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--surface);
|
||||
}
|
||||
.pill.ok { border-color: color-mix(in srgb, var(--ok) 45%, var(--line)); color: var(--ok); }
|
||||
.pill.warn { border-color: color-mix(in srgb, var(--warn) 45%, var(--line)); color: var(--warn); }
|
||||
.pill-dot {
|
||||
width: 7px; height: 7px; border-radius: 50%;
|
||||
background: currentColor;
|
||||
animation: pulse 1.8s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% { box-shadow: 0 0 0 0 color-mix(in srgb, currentColor 50%, transparent); }
|
||||
70% { box-shadow: 0 0 0 6px transparent; }
|
||||
100% { box-shadow: 0 0 0 0 transparent; }
|
||||
}
|
||||
|
||||
.account-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 0 14px 8px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.account-bar > span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.tabs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
gap: 4px;
|
||||
padding: 0 10px 8px;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
appearance: none;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
border-radius: 10px;
|
||||
padding: 8px 4px;
|
||||
font: 600 11px/1.2 var(--font);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease, transform 0.15s ease;
|
||||
}
|
||||
.tabs button:hover { color: var(--fg); background: var(--surface-2); }
|
||||
.tabs button.active {
|
||||
color: var(--fg);
|
||||
background: var(--surface);
|
||||
border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.panel-host { padding: 0 12px 8px; min-height: 180px; }
|
||||
|
||||
.tab-pane {
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(4px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.card {
|
||||
background: color-mix(in srgb, var(--surface) 94%, transparent);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
.card h2 { margin: 0 0 4px; font-size: 14px; }
|
||||
.card p { margin: 0 0 10px; color: var(--muted); font-size: 12px; }
|
||||
|
||||
.chip-row { display: flex; gap: 6px; margin-bottom: 8px; flex-wrap: wrap; }
|
||||
.active-chip {
|
||||
border-color: var(--accent) !important;
|
||||
color: var(--accent) !important;
|
||||
background: color-mix(in srgb, var(--accent) 12%, var(--surface)) !important;
|
||||
}
|
||||
|
||||
.row { display: flex; gap: 8px; align-items: end; flex-wrap: wrap; }
|
||||
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||
.actions { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
flex: 1;
|
||||
min-width: 100px;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.field input,
|
||||
.field textarea,
|
||||
.field select {
|
||||
width: 100%;
|
||||
border: 1px solid var(--line);
|
||||
background: #121820;
|
||||
color: var(--fg);
|
||||
border-radius: 10px;
|
||||
padding: 8px 10px;
|
||||
font: inherit;
|
||||
outline: none;
|
||||
transition: border-color 0.15s ease;
|
||||
}
|
||||
.field textarea { min-height: 72px; resize: vertical; }
|
||||
.field input:focus,
|
||||
.field textarea:focus { border-color: var(--accent); }
|
||||
|
||||
button.primary,
|
||||
button.danger,
|
||||
button.ghost {
|
||||
appearance: none;
|
||||
border-radius: 10px;
|
||||
border: 1px solid transparent;
|
||||
padding: 8px 12px;
|
||||
font: 700 12px/1.2 var(--font);
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
transition: transform 0.12s ease, filter 0.12s ease, background 0.15s ease;
|
||||
}
|
||||
button.primary:hover,
|
||||
button.danger:hover,
|
||||
button.ghost:hover { transform: translateY(-1px); }
|
||||
button.primary {
|
||||
background: linear-gradient(135deg, var(--accent), #ff6b4a);
|
||||
color: #1a1210;
|
||||
}
|
||||
button.danger {
|
||||
background: color-mix(in srgb, var(--danger) 18%, var(--surface));
|
||||
color: var(--danger);
|
||||
border-color: color-mix(in srgb, var(--danger) 40%, var(--line));
|
||||
}
|
||||
button.ghost {
|
||||
background: var(--surface-2);
|
||||
color: var(--fg);
|
||||
border-color: var(--line);
|
||||
}
|
||||
button.sm { padding: 5px 8px; font-size: 11px; }
|
||||
button.icon-btn { padding: 6px; }
|
||||
|
||||
.jobs-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.empty-hint { color: var(--muted); padding: 8px 0; }
|
||||
|
||||
.job-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid transparent;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
.job-item:hover { background: var(--surface-2); }
|
||||
.job-item.active {
|
||||
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||
border-color: color-mix(in srgb, var(--accent) 35%, var(--line));
|
||||
}
|
||||
.job-item .k { font-weight: 700; font-size: 12px; }
|
||||
.job-item .s { color: var(--muted); font-size: 11px; margin-top: 2px; }
|
||||
|
||||
.badge {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
padding: 2px 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--surface-2);
|
||||
color: var(--muted);
|
||||
}
|
||||
.badge.completed { color: var(--ok); background: color-mix(in srgb, var(--ok) 15%, transparent); }
|
||||
.badge.failed, .badge.cancelled { color: var(--bad); background: color-mix(in srgb, var(--bad) 15%, transparent); }
|
||||
.badge.running, .badge.queued { color: var(--accent); background: color-mix(in srgb, var(--accent) 15%, transparent); }
|
||||
|
||||
.result {
|
||||
margin: 0 12px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
padding: 10px;
|
||||
}
|
||||
.result-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.result-head strong {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.result-body {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
max-height: 140px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.ok-line { color: var(--ok); font-weight: 700; }
|
||||
.err-line { color: var(--bad); font-weight: 700; }
|
||||
|
||||
.foot {
|
||||
padding: 6px 14px 12px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: 16px;
|
||||
transform: translateX(-50%) translateY(8px);
|
||||
background: #e8eef5;
|
||||
color: #0f1419;
|
||||
padding: 8px 12px;
|
||||
border-radius: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 12px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
z-index: 20;
|
||||
}
|
||||
.toast.show {
|
||||
opacity: 1;
|
||||
transform: translateX(-50%) translateY(0);
|
||||
}
|
||||
12
extensions/dylive-helper/src/popup.html
Normal file
12
extensions/dylive-helper/src/popup.html
Normal file
@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>dylive Helper</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./popup.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
54
extensions/dylive-helper/src/popup.tsx
Normal file
54
extensions/dylive-helper/src/popup.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { useEffect, useState } from "react";
|
||||
import { PopupApp } from "./PopupApp";
|
||||
import { TikTokPanel } from "./TikTokPanel";
|
||||
import "./popup.css";
|
||||
import "./shell.css";
|
||||
|
||||
type TopTab = "tiktok" | "x";
|
||||
|
||||
function Shell() {
|
||||
const [tab, setTab] = useState<TopTab>("tiktok");
|
||||
|
||||
useEffect(() => {
|
||||
chrome.storage.local.get(["dyliveTopTab"], (data) => {
|
||||
if (data.dyliveTopTab === "x" || data.dyliveTopTab === "tiktok") {
|
||||
setTab(data.dyliveTopTab);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const switchTab = (next: TopTab) => {
|
||||
setTab(next);
|
||||
void chrome.storage.local.set({ dyliveTopTab: next });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="shell">
|
||||
<nav className="shell-tabs" role="tablist">
|
||||
<button
|
||||
type="button"
|
||||
className={tab === "tiktok" ? "active" : ""}
|
||||
onClick={() => switchTab("tiktok")}
|
||||
>
|
||||
TikTok
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={tab === "x" ? "active" : ""}
|
||||
onClick={() => switchTab("x")}
|
||||
>
|
||||
X
|
||||
</button>
|
||||
</nav>
|
||||
<div className={tab === "tiktok" ? "shell-pane active" : "shell-pane"}>
|
||||
<TikTokPanel />
|
||||
</div>
|
||||
<div className={tab === "x" ? "shell-pane active" : "shell-pane"}>
|
||||
{tab === "x" ? <PopupApp /> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<Shell />);
|
||||
116
extensions/dylive-helper/src/shell.css
Normal file
116
extensions/dylive-helper/src/shell.css
Normal file
@ -0,0 +1,116 @@
|
||||
.shell {
|
||||
min-height: 100%;
|
||||
}
|
||||
.shell-tabs {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 4px;
|
||||
padding: 8px 10px 0;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 20;
|
||||
background: color-mix(in srgb, var(--bg, #0f1419) 92%, transparent);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.shell-tabs button {
|
||||
appearance: none;
|
||||
border: 1px solid var(--line, #2a3441);
|
||||
border-radius: 10px;
|
||||
padding: 8px 10px;
|
||||
font: 700 12px/1.2 var(--font, system-ui, sans-serif);
|
||||
cursor: pointer;
|
||||
background: var(--surface-2, #1c2430);
|
||||
color: var(--muted, #8b98a5);
|
||||
}
|
||||
.shell-tabs button.active {
|
||||
color: #fff;
|
||||
background: #2a4a6b;
|
||||
border-color: #3d6a94;
|
||||
}
|
||||
.shell-pane {
|
||||
display: none;
|
||||
}
|
||||
.shell-pane.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.tt-panel {
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
.tt-head {
|
||||
padding: 12px 14px 8px;
|
||||
}
|
||||
.tt-head h1 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
.tt-head p {
|
||||
margin: 4px 0 0;
|
||||
color: var(--muted, #8b98a8);
|
||||
font-size: 12px;
|
||||
}
|
||||
.tt-panel .status {
|
||||
margin: 0 14px 10px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.tt-panel .status.idle {
|
||||
background: #1c2430;
|
||||
color: #9aa8b8;
|
||||
}
|
||||
.tt-panel .status.ok {
|
||||
background: #113228;
|
||||
color: #7ee0a8;
|
||||
}
|
||||
.tt-panel .status.err {
|
||||
background: #3a1518;
|
||||
color: #ff9aa3;
|
||||
}
|
||||
.tt-panel dl {
|
||||
margin: 0 14px 12px;
|
||||
display: grid;
|
||||
grid-template-columns: 110px 1fr;
|
||||
gap: 6px 8px;
|
||||
}
|
||||
.tt-panel dt {
|
||||
color: #8b98a8;
|
||||
}
|
||||
.tt-panel dd {
|
||||
margin: 0;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
.tt-actions {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
padding: 0 14px 8px;
|
||||
}
|
||||
.tt-actions button {
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
}
|
||||
.tt-actions button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.tt-primary {
|
||||
background: #ff2d55;
|
||||
}
|
||||
.tt-secondary {
|
||||
background: #2a3340;
|
||||
}
|
||||
.tt-muted {
|
||||
background: #1c2430;
|
||||
color: #d7e0ea !important;
|
||||
}
|
||||
.tt-hint {
|
||||
margin: 0;
|
||||
padding: 0 14px 14px;
|
||||
color: #8b98a8;
|
||||
font-size: 11px;
|
||||
}
|
||||
1
extensions/dylive-helper/src/vite-env.d.ts
vendored
Normal file
1
extensions/dylive-helper/src/vite-env.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
74
extensions/dylive-helper/tiktok-cookie.user.js
Normal file
74
extensions/dylive-helper/tiktok-cookie.user.js
Normal file
@ -0,0 +1,74 @@
|
||||
// ==UserScript==
|
||||
// @name dylive TikTok Cookie 导出
|
||||
// @namespace https://dylive.nomadro.com
|
||||
// @version 1.0.0
|
||||
// @description 在已登录的 tiktok.com 一键复制 sessionid / tt-target-idc(需 GM.cookie,可读取 HttpOnly)
|
||||
// @match https://www.tiktok.com/*
|
||||
// @match https://*.tiktok.com/*
|
||||
// @grant GM.cookie
|
||||
// @grant GM.setClipboard
|
||||
// @grant GM_setClipboard
|
||||
// @run-at document-idle
|
||||
// ==/UserScript==
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
function mask(v) {
|
||||
const s = String(v || "");
|
||||
if (s.length <= 8) return s ? "***" : "无";
|
||||
return s.slice(0, 4) + "…" + s.slice(-4);
|
||||
}
|
||||
|
||||
async function readCookies() {
|
||||
if (!GM?.cookie?.list) {
|
||||
throw new Error("当前油猴不支持 GM.cookie。请改用 Chrome 插件(能读 HttpOnly sessionid)。");
|
||||
}
|
||||
const list = await GM.cookie.list({ url: location.origin + "/" });
|
||||
const map = Object.fromEntries((list || []).map((c) => [c.name, c.value]));
|
||||
const sessionid = String(map.sessionid || map.sessionid_ss || "").trim();
|
||||
const dc_id = String(map["tt-target-idc"] || "").trim();
|
||||
if (!sessionid) throw new Error("未找到 sessionid,请先登录 TikTok");
|
||||
return { sessionid, dc_id, tiktok_username: "" };
|
||||
}
|
||||
|
||||
async function copyJson(payload) {
|
||||
const text = JSON.stringify(payload);
|
||||
if (typeof GM_setClipboard === "function") GM_setClipboard(text);
|
||||
else if (GM?.setClipboard) await GM.setClipboard(text);
|
||||
else await navigator.clipboard.writeText(text);
|
||||
}
|
||||
|
||||
const btn = document.createElement("button");
|
||||
btn.textContent = "导出 Cookie → dylive";
|
||||
btn.style.cssText = [
|
||||
"position:fixed",
|
||||
"right:16px",
|
||||
"bottom:16px",
|
||||
"z-index:2147483647",
|
||||
"padding:10px 14px",
|
||||
"border:0",
|
||||
"border-radius:999px",
|
||||
"background:#fe2c55",
|
||||
"color:#fff",
|
||||
"font:600 13px/1 system-ui,sans-serif",
|
||||
"cursor:pointer",
|
||||
"box-shadow:0 8px 24px rgba(0,0,0,.35)",
|
||||
].join(";");
|
||||
btn.addEventListener("click", async () => {
|
||||
try {
|
||||
const payload = await readCookies();
|
||||
await copyJson(payload);
|
||||
btn.textContent = "已复制 " + mask(payload.sessionid);
|
||||
setTimeout(() => {
|
||||
btn.textContent = "导出 Cookie → dylive";
|
||||
}, 2500);
|
||||
} catch (err) {
|
||||
btn.textContent = String(err.message || err);
|
||||
setTimeout(() => {
|
||||
btn.textContent = "导出 Cookie → dylive";
|
||||
}, 4000);
|
||||
}
|
||||
});
|
||||
document.documentElement.appendChild(btn);
|
||||
})();
|
||||
18
extensions/dylive-helper/tsconfig.json
Normal file
18
extensions/dylive-helper/tsconfig.json
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"types": ["chrome"],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@x2/shared": ["vendor/shared/src/index.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*", "vite.config.ts", "vendor/shared/src/**/*"]
|
||||
}
|
||||
22
extensions/dylive-helper/vendor/shared/package.json
vendored
Normal file
22
extensions/dylive-helper/vendor/shared/package.json
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@x2/shared",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"dev": "tsc -p tsconfig.json --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.8.2"
|
||||
}
|
||||
}
|
||||
74
extensions/dylive-helper/vendor/shared/src/i18n/index.ts
vendored
Normal file
74
extensions/dylive-helper/vendor/shared/src/i18n/index.ts
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
import {
|
||||
EN_MESSAGES,
|
||||
JOB_KIND_LABEL_EN,
|
||||
JOB_KIND_LABEL_ZH,
|
||||
LOCALE_LABEL,
|
||||
LOCALES,
|
||||
ZH_MESSAGES,
|
||||
type Locale,
|
||||
type MessageKey,
|
||||
} from "./messages.js";
|
||||
|
||||
export type { Locale, MessageKey };
|
||||
export { LOCALE_LABEL, LOCALES, ZH_MESSAGES, EN_MESSAGES, JOB_KIND_LABEL_EN, JOB_KIND_LABEL_ZH };
|
||||
|
||||
type Vars = Record<string, string | number>;
|
||||
|
||||
const CATALOG: Record<Locale, Record<MessageKey, string>> = {
|
||||
zh: ZH_MESSAGES,
|
||||
en: EN_MESSAGES,
|
||||
};
|
||||
|
||||
let currentLocale: Locale = "zh";
|
||||
const listeners = new Set<(locale: Locale) => void>();
|
||||
|
||||
export function normalizeLocale(raw?: string | null): Locale {
|
||||
if (!raw) return "zh";
|
||||
const v = raw.toLowerCase();
|
||||
if (v.startsWith("en")) return "en";
|
||||
if (v.startsWith("zh")) return "zh";
|
||||
return LOCALES.includes(raw as Locale) ? (raw as Locale) : "zh";
|
||||
}
|
||||
|
||||
export function getLocale(): Locale {
|
||||
return currentLocale;
|
||||
}
|
||||
|
||||
export function setLocale(locale: Locale | string) {
|
||||
const next = normalizeLocale(locale);
|
||||
if (next === currentLocale) return;
|
||||
currentLocale = next;
|
||||
for (const fn of listeners) fn(next);
|
||||
}
|
||||
|
||||
export function subscribeLocale(fn: (locale: Locale) => void) {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
}
|
||||
|
||||
function fill(template: string, vars?: Vars) {
|
||||
if (!vars) return template;
|
||||
return template.replace(/\{(\w+)\}/g, (_, key: string) =>
|
||||
vars[key] != null ? String(vars[key]) : `{${key}}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function t(key: MessageKey, vars?: Vars, locale = currentLocale): string {
|
||||
const table = CATALOG[locale] || ZH_MESSAGES;
|
||||
return fill(table[key] || ZH_MESSAGES[key] || key, vars);
|
||||
}
|
||||
|
||||
export function jobKindLabel(kind: string, locale = currentLocale): string {
|
||||
const map = locale === "en" ? JOB_KIND_LABEL_EN : JOB_KIND_LABEL_ZH;
|
||||
return map[kind] || t("common.operation", undefined, locale);
|
||||
}
|
||||
|
||||
export function statusLabel(status: string, locale = currentLocale): string {
|
||||
const key = `status.${status}` as MessageKey;
|
||||
if (key in ZH_MESSAGES) return t(key, undefined, locale);
|
||||
return status;
|
||||
}
|
||||
|
||||
export function localeTag(locale = currentLocale): string {
|
||||
return locale === "en" ? "en-US" : "zh-CN";
|
||||
}
|
||||
313
extensions/dylive-helper/vendor/shared/src/i18n/messages.ts
vendored
Normal file
313
extensions/dylive-helper/vendor/shared/src/i18n/messages.ts
vendored
Normal file
@ -0,0 +1,313 @@
|
||||
export type Locale = "zh" | "en";
|
||||
|
||||
export const LOCALES: Locale[] = ["zh", "en"];
|
||||
|
||||
export const LOCALE_LABEL: Record<Locale, string> = {
|
||||
zh: "中文",
|
||||
en: "English",
|
||||
};
|
||||
|
||||
export type MessageKey = keyof typeof ZH_MESSAGES;
|
||||
|
||||
/** Chinese is the source catalog; English must cover the same keys */
|
||||
export const ZH_MESSAGES = {
|
||||
"nav.workbench": "工作台",
|
||||
"nav.cleanup": "关系清理",
|
||||
"nav.scrape": "数据采集",
|
||||
"nav.engage": "互动",
|
||||
"nav.monitor": "粉丝监控",
|
||||
"nav.workflow": "工作流",
|
||||
"nav.accounts": "账号管理",
|
||||
"nav.settings": "系统设置",
|
||||
|
||||
"crumb.workbench": "首页",
|
||||
"crumb.cleanup": "清理 · 可见取关 · 静音/解除 · 屏蔽",
|
||||
"crumb.scrape": "首页 · 提及 · 话题 · 表现分析",
|
||||
"crumb.engage": "赞 · 转推 · 置顶 · 删帖 · 关注",
|
||||
"crumb.monitor": "粉丝 · 关注列表变化",
|
||||
"crumb.workflow": "多步自动跑",
|
||||
"crumb.accounts": "当前登录账号",
|
||||
"crumb.settings": "限速和其他",
|
||||
|
||||
"brand.sub": "本地运营工具",
|
||||
"link.label": "扩展连接",
|
||||
"link.ok": "已自动连接",
|
||||
"link.searching": "正在寻找扩展…",
|
||||
"feed.title": "最近操作",
|
||||
"feed.all": "全部",
|
||||
"feed.active": "进行中",
|
||||
"feed.completed": "已完成",
|
||||
"feed.failed": "失败",
|
||||
"result.title": "看结果",
|
||||
"result.stop": "停下",
|
||||
"result.pauseResume": "暂停/恢复",
|
||||
"result.copy": "复制说明",
|
||||
"result.exportJson": "导出 JSON",
|
||||
"result.exportCsv": "导出 CSV",
|
||||
"result.empty": "左边点一项功能开始,完成后这里会用大白话告诉你结果",
|
||||
"result.exported": "已顺手备份到本地导出文件夹(左下角可打开)",
|
||||
"footer.openExports": "打开导出文件夹",
|
||||
"footer.rerun": "重跑上次",
|
||||
"footer.clear": "清掉完成记录",
|
||||
|
||||
"status.queued": "排队中",
|
||||
"status.running": "进行中",
|
||||
"status.paused": "已暂停",
|
||||
"status.completed": "已完成",
|
||||
"status.failed": "出错了",
|
||||
"status.cancelled": "已取消",
|
||||
|
||||
"progress.queued": "在排队,马上开始",
|
||||
"progress.running": "正在做…",
|
||||
"progress.done": "已完成 {cur}/{total}",
|
||||
"progress.cancelled": "你已取消",
|
||||
"progress.failedPrefix": "没做成:",
|
||||
"progress.doneRelative": "完成 · {rel}",
|
||||
|
||||
"relative.justNow": "刚刚",
|
||||
"relative.sec": "{n} 秒前",
|
||||
"relative.min": "{n} 分钟前",
|
||||
"relative.hour": "{n} 小时前",
|
||||
"relative.day": "{n} 天前",
|
||||
|
||||
"settings.rateTitle": "限速设置",
|
||||
"settings.rateDesc": "影响取关 / 点赞 / 关注 / 发帖",
|
||||
"settings.minDelay": "最小间隔 ms",
|
||||
"settings.maxDelay": "最大间隔 ms",
|
||||
"settings.quota": "日配额",
|
||||
"settings.save": "保存",
|
||||
"settings.writesToday": "今日已写入",
|
||||
"settings.remaining": "剩余 {n} 次",
|
||||
"settings.theme": "主题",
|
||||
"settings.themeDark": "夜间",
|
||||
"settings.themeLight": "日间",
|
||||
"settings.language": "语言 / Language",
|
||||
"settings.about": "关于",
|
||||
"settings.aboutRunning": "本地服务运行中",
|
||||
"settings.apiHint": "本地 Agent API:http://127.0.0.1:17888 — 可用 @x2/sdk 调用",
|
||||
|
||||
"popup.tab.cleanup": "清理",
|
||||
"popup.tab.scrape": "采集",
|
||||
"popup.tab.engage": "互动",
|
||||
"popup.tab.monitor": "监控",
|
||||
"popup.tab.jobs": "任务",
|
||||
"popup.paired": "已连桌面",
|
||||
"popup.solo": "独立模式",
|
||||
"popup.lang": "语言",
|
||||
|
||||
"common.operation": "一项操作",
|
||||
"toast.extMissing": "扩展未连接,请先打开 x.com 并确保扩展已加载",
|
||||
"toast.jobStarted": "{name}开始了",
|
||||
"toast.jobFailed": "任务创建失败",
|
||||
"toast.stopped": "已停下",
|
||||
"toast.paused": "已暂停排队",
|
||||
"toast.resumed": "已恢复排队",
|
||||
"toast.exported": "已导出 {format}",
|
||||
"toast.exportFailed": "导出失败",
|
||||
"toast.copied": "已复制说明文字",
|
||||
"toast.rateSaved": "限速已保存",
|
||||
} as const;
|
||||
|
||||
export const EN_MESSAGES: Record<MessageKey, string> = {
|
||||
"nav.workbench": "Workbench",
|
||||
"nav.cleanup": "Cleanup",
|
||||
"nav.scrape": "Scrape",
|
||||
"nav.engage": "Engage",
|
||||
"nav.monitor": "Monitor",
|
||||
"nav.workflow": "Workflows",
|
||||
"nav.accounts": "Accounts",
|
||||
"nav.settings": "Settings",
|
||||
|
||||
"crumb.workbench": "Home",
|
||||
"crumb.cleanup": "Non-followers · unmute · block",
|
||||
"crumb.scrape": "Home · mentions · tags · analytics",
|
||||
"crumb.engage": "Like · retweet · pin · delete · follow",
|
||||
"crumb.monitor": "Followers · following diffs",
|
||||
"crumb.workflow": "Multi-step automation",
|
||||
"crumb.accounts": "Signed-in accounts",
|
||||
"crumb.settings": "Rate limits & more",
|
||||
|
||||
"brand.sub": "Local ops toolkit",
|
||||
"link.label": "Extension",
|
||||
"link.ok": "Connected",
|
||||
"link.searching": "Looking for extension…",
|
||||
"feed.title": "Recent",
|
||||
"feed.all": "All",
|
||||
"feed.active": "Active",
|
||||
"feed.completed": "Done",
|
||||
"feed.failed": "Failed",
|
||||
"result.title": "Results",
|
||||
"result.stop": "Stop",
|
||||
"result.pauseResume": "Pause/Resume",
|
||||
"result.copy": "Copy summary",
|
||||
"result.exportJson": "Export JSON",
|
||||
"result.exportCsv": "Export CSV",
|
||||
"result.empty": "Pick an action on the left — results show up here in plain language",
|
||||
"result.exported": "Also saved to the local export folder (open from the footer)",
|
||||
"footer.openExports": "Open exports",
|
||||
"footer.rerun": "Rerun last",
|
||||
"footer.clear": "Clear finished",
|
||||
|
||||
"status.queued": "Queued",
|
||||
"status.running": "Running",
|
||||
"status.paused": "Paused",
|
||||
"status.completed": "Completed",
|
||||
"status.failed": "Failed",
|
||||
"status.cancelled": "Cancelled",
|
||||
|
||||
"progress.queued": "Queued — starting soon",
|
||||
"progress.running": "Working…",
|
||||
"progress.done": "Done {cur}/{total}",
|
||||
"progress.cancelled": "Cancelled",
|
||||
"progress.failedPrefix": "Failed: ",
|
||||
"progress.doneRelative": "Done · {rel}",
|
||||
|
||||
"relative.justNow": "just now",
|
||||
"relative.sec": "{n}s ago",
|
||||
"relative.min": "{n}m ago",
|
||||
"relative.hour": "{n}h ago",
|
||||
"relative.day": "{n}d ago",
|
||||
|
||||
"settings.rateTitle": "Rate limits",
|
||||
"settings.rateDesc": "Applies to unfollow / like / follow / post",
|
||||
"settings.minDelay": "Min delay ms",
|
||||
"settings.maxDelay": "Max delay ms",
|
||||
"settings.quota": "Daily quota",
|
||||
"settings.save": "Save",
|
||||
"settings.writesToday": "Writes today",
|
||||
"settings.remaining": "{n} remaining",
|
||||
"settings.theme": "Theme",
|
||||
"settings.themeDark": "Dark",
|
||||
"settings.themeLight": "Light",
|
||||
"settings.language": "Language / 语言",
|
||||
"settings.about": "About",
|
||||
"settings.aboutRunning": "Local agent is running",
|
||||
"settings.apiHint": "Agent API: http://127.0.0.1:17888 — use @x2/sdk from other clients",
|
||||
|
||||
"popup.tab.cleanup": "Clean",
|
||||
"popup.tab.scrape": "Scrape",
|
||||
"popup.tab.engage": "Engage",
|
||||
"popup.tab.monitor": "Monitor",
|
||||
"popup.tab.jobs": "Jobs",
|
||||
"popup.paired": "Desktop linked",
|
||||
"popup.solo": "Standalone",
|
||||
"popup.lang": "Lang",
|
||||
|
||||
"common.operation": "an operation",
|
||||
"toast.extMissing": "Extension offline — open x.com with the extension loaded",
|
||||
"toast.jobStarted": "{name} started",
|
||||
"toast.jobFailed": "Failed to create job",
|
||||
"toast.stopped": "Stopped",
|
||||
"toast.paused": "Paused (queued)",
|
||||
"toast.resumed": "Resumed",
|
||||
"toast.exported": "Exported {format}",
|
||||
"toast.exportFailed": "Export failed",
|
||||
"toast.copied": "Summary copied",
|
||||
"toast.rateSaved": "Rate limits saved",
|
||||
};
|
||||
|
||||
export const JOB_KIND_LABEL_ZH: Record<string, string> = {
|
||||
"cleanup.non_followers": "扫描没回关的人",
|
||||
"cleanup.unfollow": "批量取关",
|
||||
"cleanup.unfollow_visible": "可见页快速取关",
|
||||
"cleanup.mute": "批量静音",
|
||||
"cleanup.unmute": "批量取消静音",
|
||||
"cleanup.block": "批量屏蔽",
|
||||
"cleanup.unblock": "批量取消屏蔽",
|
||||
"scrape.profile": "查看账号资料",
|
||||
"scrape.following": "抓取关注列表",
|
||||
"scrape.followers": "抓取粉丝列表",
|
||||
"scrape.tweets": "抓取推文",
|
||||
"scrape.search": "搜索推文",
|
||||
"scrape.bookmarks": "导出书签",
|
||||
"scrape.likers": "抓取点赞用户",
|
||||
"scrape.media": "提取媒体链接",
|
||||
"scrape.thread": "抓取推文串",
|
||||
"scrape.likes": "抓取点赞时间线",
|
||||
"scrape.list": "抓取列表成员",
|
||||
"scrape.hashtag": "抓取话题标签",
|
||||
"scrape.people": "搜索用户",
|
||||
"scrape.notifications": "抓取通知",
|
||||
"scrape.home": "抓取首页时间线",
|
||||
"scrape.mentions": "抓取提及",
|
||||
"scrape.retweeters": "抓取转推用户",
|
||||
"scrape.quotes": "抓取引用用户",
|
||||
"scrape.with_replies": "抓取推文含回复",
|
||||
"engage.like": "批量点赞",
|
||||
"engage.unlike": "批量取消点赞",
|
||||
"engage.follow": "批量关注",
|
||||
"engage.post": "发一条帖子",
|
||||
"engage.reply": "回复推文",
|
||||
"engage.retweet": "转推",
|
||||
"engage.unretweet": "取消转推",
|
||||
"engage.quote": "引用推文",
|
||||
"engage.bookmark": "收藏推文",
|
||||
"engage.unbookmark": "取消收藏",
|
||||
"engage.delete": "删除推文",
|
||||
"engage.pin": "置顶推文",
|
||||
"engage.unpin": "取消置顶",
|
||||
"engage.copy_link": "复制推文链接",
|
||||
"growth.engage": "关键词增长互动",
|
||||
"growth.home": "首页时间线互动",
|
||||
"content.tech_news": "科技新闻自动发帖",
|
||||
"content.tech_news_day": "科技新闻·24小时随机12条",
|
||||
"monitor.snapshot_followers": "粉丝变化快照",
|
||||
"monitor.snapshot_following": "关注列表快照",
|
||||
"monitor.diff_followers": "对比粉丝变化",
|
||||
"analyze.profiles": "对比账号画像",
|
||||
"analyze.tweets": "分析推文表现",
|
||||
"workflow.run": "跑工作流",
|
||||
};
|
||||
|
||||
export const JOB_KIND_LABEL_EN: Record<string, string> = {
|
||||
"cleanup.non_followers": "Scan non-followers",
|
||||
"cleanup.unfollow": "Bulk unfollow",
|
||||
"cleanup.unfollow_visible": "Unfollow visible",
|
||||
"cleanup.mute": "Bulk mute",
|
||||
"cleanup.unmute": "Bulk unmute",
|
||||
"cleanup.block": "Bulk block",
|
||||
"cleanup.unblock": "Bulk unblock",
|
||||
"scrape.profile": "Fetch profile",
|
||||
"scrape.following": "Scrape following",
|
||||
"scrape.followers": "Scrape followers",
|
||||
"scrape.tweets": "Scrape tweets",
|
||||
"scrape.search": "Search tweets",
|
||||
"scrape.bookmarks": "Export bookmarks",
|
||||
"scrape.likers": "Scrape likers",
|
||||
"scrape.media": "Extract media links",
|
||||
"scrape.thread": "Scrape thread",
|
||||
"scrape.likes": "Scrape likes timeline",
|
||||
"scrape.list": "Scrape list members",
|
||||
"scrape.hashtag": "Scrape hashtag",
|
||||
"scrape.people": "Search people",
|
||||
"scrape.notifications": "Scrape notifications",
|
||||
"scrape.home": "Scrape home timeline",
|
||||
"scrape.mentions": "Scrape mentions",
|
||||
"scrape.retweeters": "Scrape retweeters",
|
||||
"scrape.quotes": "Scrape quoters",
|
||||
"scrape.with_replies": "Scrape tweets & replies",
|
||||
"engage.like": "Bulk like",
|
||||
"engage.unlike": "Bulk unlike",
|
||||
"engage.follow": "Bulk follow",
|
||||
"engage.post": "Post a tweet",
|
||||
"engage.reply": "Reply to tweet",
|
||||
"engage.retweet": "Retweet",
|
||||
"engage.unretweet": "Undo retweet",
|
||||
"engage.quote": "Quote tweet",
|
||||
"engage.bookmark": "Bookmark tweet",
|
||||
"engage.unbookmark": "Remove bookmark",
|
||||
"engage.delete": "Delete tweet",
|
||||
"engage.pin": "Pin tweet",
|
||||
"engage.unpin": "Unpin tweet",
|
||||
"engage.copy_link": "Copy tweet link",
|
||||
"growth.engage": "Keyword growth engage",
|
||||
"growth.home": "Home timeline engage",
|
||||
"content.tech_news": "Auto-post tech news",
|
||||
"content.tech_news_day": "Tech news · 12 random posts / 24h",
|
||||
"monitor.snapshot_followers": "Followers snapshot",
|
||||
"monitor.snapshot_following": "Following snapshot",
|
||||
"monitor.diff_followers": "Diff followers",
|
||||
"analyze.profiles": "Compare profiles",
|
||||
"analyze.tweets": "Analyze tweet stats",
|
||||
"workflow.run": "Run workflow",
|
||||
};
|
||||
4
extensions/dylive-helper/vendor/shared/src/index.ts
vendored
Normal file
4
extensions/dylive-helper/vendor/shared/src/index.ts
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
export * from "./types.js";
|
||||
export * from "./protocol.js";
|
||||
export * from "./search.js";
|
||||
export * from "./i18n/index.js";
|
||||
118
extensions/dylive-helper/vendor/shared/src/protocol.ts
vendored
Normal file
118
extensions/dylive-helper/vendor/shared/src/protocol.ts
vendored
Normal file
@ -0,0 +1,118 @@
|
||||
import type {
|
||||
AccountInfo,
|
||||
JobKind,
|
||||
JobProgress,
|
||||
JobRecord,
|
||||
JobStatus,
|
||||
} from "./types.js";
|
||||
|
||||
export type ClientRole = "extension" | "renderer" | "agent";
|
||||
|
||||
/** Envelope for all WS / HTTP bridge messages */
|
||||
export type Envelope<T extends string = string, P = unknown> = {
|
||||
v: 1;
|
||||
id: string;
|
||||
type: T;
|
||||
ts: string;
|
||||
payload: P;
|
||||
};
|
||||
|
||||
export function envelope<T extends string, P>(
|
||||
type: T,
|
||||
payload: P,
|
||||
id = cryptoRandomId(),
|
||||
): Envelope<T, P> {
|
||||
return {
|
||||
v: 1,
|
||||
id,
|
||||
type,
|
||||
ts: new Date().toISOString(),
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
export function cryptoRandomId(): string {
|
||||
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
return `id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
/* —— client → agent —— */
|
||||
|
||||
export type HelloPayload = {
|
||||
role: ClientRole;
|
||||
token: string;
|
||||
/** extension reports current x.com user if known */
|
||||
account?: Partial<AccountInfo>;
|
||||
};
|
||||
|
||||
export type JobCreatePayload = {
|
||||
kind: JobKind;
|
||||
accountId?: string;
|
||||
params?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type JobCancelPayload = { jobId: string };
|
||||
|
||||
export type AccountBindPayload = {
|
||||
username: string;
|
||||
displayName?: string;
|
||||
avatarUrl?: string;
|
||||
};
|
||||
|
||||
export type ExtensionJobExecPayload = {
|
||||
jobId: string;
|
||||
kind: JobKind;
|
||||
params: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type ExtensionJobProgressPayload = {
|
||||
jobId: string;
|
||||
progress: JobProgress;
|
||||
};
|
||||
|
||||
export type ExtensionJobResultPayload = {
|
||||
jobId: string;
|
||||
ok: boolean;
|
||||
result?: unknown;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
/* —— agent → clients —— */
|
||||
|
||||
export type HelloOkPayload = {
|
||||
ok: true;
|
||||
agentVersion: string;
|
||||
accounts: AccountInfo[];
|
||||
jobs: JobRecord[];
|
||||
};
|
||||
|
||||
export type HelloErrPayload = { ok: false; error: string };
|
||||
|
||||
export type JobUpdatedPayload = {
|
||||
job: JobRecord;
|
||||
};
|
||||
|
||||
export type AccountsUpdatedPayload = {
|
||||
accounts: AccountInfo[];
|
||||
};
|
||||
|
||||
export type AgentEvent =
|
||||
| Envelope<"hello", HelloPayload>
|
||||
| Envelope<"hello.ok", HelloOkPayload>
|
||||
| Envelope<"hello.err", HelloErrPayload>
|
||||
| Envelope<"job.create", JobCreatePayload>
|
||||
| Envelope<"job.cancel", JobCancelPayload>
|
||||
| Envelope<"job.updated", JobUpdatedPayload>
|
||||
| Envelope<"job.exec", ExtensionJobExecPayload>
|
||||
| Envelope<"job.progress", ExtensionJobProgressPayload>
|
||||
| Envelope<"job.result", ExtensionJobResultPayload>
|
||||
| Envelope<"account.bind", AccountBindPayload>
|
||||
| Envelope<"accounts.updated", AccountsUpdatedPayload>
|
||||
| Envelope<"ping", Record<string, never>>
|
||||
| Envelope<"pong", { t: number }>;
|
||||
|
||||
export type JobStatusPatch = Partial<
|
||||
Pick<JobRecord, "status" | "progress" | "result" | "error">
|
||||
> & { status?: JobStatus };
|
||||
35
extensions/dylive-helper/vendor/shared/src/search.ts
vendored
Normal file
35
extensions/dylive-helper/vendor/shared/src/search.ts
vendored
Normal file
@ -0,0 +1,35 @@
|
||||
/** Build X advanced search operators into a query string */
|
||||
export function buildAdvancedSearch(opts: {
|
||||
keywords?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
since?: string;
|
||||
until?: string;
|
||||
minFaves?: number;
|
||||
minRetweets?: number;
|
||||
minReplies?: number;
|
||||
lang?: string;
|
||||
filterReplies?: boolean;
|
||||
onlyMedia?: boolean;
|
||||
onlyLinks?: boolean;
|
||||
}): string {
|
||||
const parts: string[] = [];
|
||||
const kw = (opts.keywords || "").trim();
|
||||
if (kw) parts.push(kw);
|
||||
const from = (opts.from || "").replace(/^@/, "").trim();
|
||||
if (from) parts.push(`from:${from}`);
|
||||
const to = (opts.to || "").replace(/^@/, "").trim();
|
||||
if (to) parts.push(`to:${to}`);
|
||||
if (opts.since) parts.push(`since:${opts.since}`);
|
||||
if (opts.until) parts.push(`until:${opts.until}`);
|
||||
if (opts.minFaves != null && opts.minFaves > 0) parts.push(`min_faves:${opts.minFaves}`);
|
||||
if (opts.minRetweets != null && opts.minRetweets > 0)
|
||||
parts.push(`min_retweets:${opts.minRetweets}`);
|
||||
if (opts.minReplies != null && opts.minReplies > 0)
|
||||
parts.push(`min_replies:${opts.minReplies}`);
|
||||
if (opts.lang) parts.push(`lang:${opts.lang}`);
|
||||
if (opts.filterReplies) parts.push("-filter:replies");
|
||||
if (opts.onlyMedia) parts.push("filter:media");
|
||||
if (opts.onlyLinks) parts.push("filter:links");
|
||||
return parts.join(" ").trim();
|
||||
}
|
||||
199
extensions/dylive-helper/vendor/shared/src/types.ts
vendored
Normal file
199
extensions/dylive-helper/vendor/shared/src/types.ts
vendored
Normal file
@ -0,0 +1,199 @@
|
||||
/** Agent listen defaults — localhost only */
|
||||
export const AGENT_HOST = "127.0.0.1";
|
||||
export const AGENT_PORT = 17888;
|
||||
export const AGENT_HTTP = `http://${AGENT_HOST}:${AGENT_PORT}`;
|
||||
export const AGENT_WS = `ws://${AGENT_HOST}:${AGENT_PORT}`;
|
||||
|
||||
export type AccountInfo = {
|
||||
id: string;
|
||||
username: string;
|
||||
displayName?: string;
|
||||
avatarUrl?: string;
|
||||
boundAt: string;
|
||||
lastSeenAt: string;
|
||||
};
|
||||
|
||||
export type JobKind =
|
||||
| "scrape.profile"
|
||||
| "scrape.followers"
|
||||
| "scrape.following"
|
||||
| "scrape.tweets"
|
||||
| "scrape.search"
|
||||
| "scrape.bookmarks"
|
||||
| "scrape.likers"
|
||||
| "scrape.media"
|
||||
| "scrape.thread"
|
||||
| "scrape.likes"
|
||||
| "scrape.list"
|
||||
| "scrape.hashtag"
|
||||
| "scrape.people"
|
||||
| "scrape.notifications"
|
||||
| "scrape.home"
|
||||
| "scrape.mentions"
|
||||
| "scrape.retweeters"
|
||||
| "scrape.quotes"
|
||||
| "scrape.with_replies"
|
||||
| "cleanup.non_followers"
|
||||
| "cleanup.unfollow"
|
||||
| "cleanup.unfollow_visible"
|
||||
| "cleanup.mute"
|
||||
| "cleanup.unmute"
|
||||
| "cleanup.block"
|
||||
| "cleanup.unblock"
|
||||
| "engage.like"
|
||||
| "engage.unlike"
|
||||
| "engage.follow"
|
||||
| "engage.post"
|
||||
| "engage.reply"
|
||||
| "engage.retweet"
|
||||
| "engage.unretweet"
|
||||
| "engage.quote"
|
||||
| "engage.bookmark"
|
||||
| "engage.unbookmark"
|
||||
| "engage.delete"
|
||||
| "engage.pin"
|
||||
| "engage.unpin"
|
||||
| "engage.copy_link"
|
||||
| "growth.engage"
|
||||
| "growth.home"
|
||||
| "content.tech_news"
|
||||
| "content.tech_news_day"
|
||||
| "monitor.snapshot_followers"
|
||||
| "monitor.snapshot_following"
|
||||
| "monitor.diff_followers"
|
||||
| "analyze.profiles"
|
||||
| "analyze.tweets"
|
||||
| "workflow.run";
|
||||
|
||||
export type JobStatus =
|
||||
| "queued"
|
||||
| "running"
|
||||
| "paused"
|
||||
| "completed"
|
||||
| "failed"
|
||||
| "cancelled";
|
||||
|
||||
export type JobProgress = {
|
||||
current: number;
|
||||
total: number;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
export type JobRecord = {
|
||||
id: string;
|
||||
kind: JobKind;
|
||||
status: JobStatus;
|
||||
accountId?: string;
|
||||
params: Record<string, unknown>;
|
||||
progress: JobProgress;
|
||||
result?: unknown;
|
||||
error?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type RateLimitConfig = {
|
||||
/** min delay between write actions (ms) */
|
||||
minDelayMs: number;
|
||||
/** max delay between write actions (ms) */
|
||||
maxDelayMs: number;
|
||||
/** max write actions per day per account */
|
||||
dailyWriteQuota: number;
|
||||
};
|
||||
|
||||
export const DEFAULT_RATE_LIMIT: RateLimitConfig = {
|
||||
minDelayMs: 2000,
|
||||
maxDelayMs: 5000,
|
||||
dailyWriteQuota: 80,
|
||||
};
|
||||
|
||||
export type UserRow = {
|
||||
username: string;
|
||||
name?: string;
|
||||
bio?: string;
|
||||
followersCount?: number;
|
||||
followingCount?: number;
|
||||
followsYou?: boolean;
|
||||
verified?: boolean;
|
||||
};
|
||||
|
||||
export type ProfileData = {
|
||||
username: string;
|
||||
name?: string;
|
||||
bio?: string;
|
||||
location?: string;
|
||||
website?: string;
|
||||
joined?: string;
|
||||
followingCount?: number;
|
||||
followersCount?: number;
|
||||
tweetsCount?: number;
|
||||
verified?: boolean;
|
||||
};
|
||||
|
||||
export type TweetRow = {
|
||||
id?: string;
|
||||
text?: string;
|
||||
author?: string;
|
||||
createdAt?: string;
|
||||
likes?: number;
|
||||
retweets?: number;
|
||||
replies?: number;
|
||||
views?: number;
|
||||
url?: string;
|
||||
mediaUrls?: string[];
|
||||
hashtags?: string[];
|
||||
};
|
||||
|
||||
export type NoticeRow = {
|
||||
text?: string;
|
||||
actors?: string[];
|
||||
type?: string;
|
||||
url?: string;
|
||||
};
|
||||
|
||||
export type WorkflowStep = {
|
||||
id: string;
|
||||
kind: JobKind;
|
||||
params?: Record<string, unknown>;
|
||||
/** stop workflow if step fails */
|
||||
stopOnError?: boolean;
|
||||
};
|
||||
|
||||
export type WorkflowDef = {
|
||||
id: string;
|
||||
name: string;
|
||||
steps: WorkflowStep[];
|
||||
/** cron-like or interval ms; null = manual */
|
||||
schedule?: { everyMs: number } | null;
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
/** 给人看的任务名 — UI / 通知 / 导出文件名统一用这个,禁止把 kind 原样甩给用户 */
|
||||
export { JOB_KIND_LABEL_ZH as JOB_KIND_LABEL, jobKindLabel } from "./i18n/index.js";
|
||||
|
||||
/** 写入类任务(计入日配额 / 默认不导出) */
|
||||
export const WRITE_JOB_KINDS: JobKind[] = [
|
||||
"cleanup.unfollow",
|
||||
"cleanup.unfollow_visible",
|
||||
"cleanup.mute",
|
||||
"cleanup.unmute",
|
||||
"cleanup.block",
|
||||
"cleanup.unblock",
|
||||
"engage.like",
|
||||
"engage.unlike",
|
||||
"engage.follow",
|
||||
"engage.post",
|
||||
"engage.reply",
|
||||
"engage.retweet",
|
||||
"engage.unretweet",
|
||||
"engage.quote",
|
||||
"engage.bookmark",
|
||||
"engage.unbookmark",
|
||||
"engage.delete",
|
||||
"engage.pin",
|
||||
"engage.unpin",
|
||||
"growth.engage",
|
||||
"growth.home",
|
||||
"content.tech_news",
|
||||
"content.tech_news_day",
|
||||
];
|
||||
14
extensions/dylive-helper/vendor/shared/tsconfig.json
vendored
Normal file
14
extensions/dylive-helper/vendor/shared/tsconfig.json
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
65
extensions/dylive-helper/vite.config.ts
Normal file
65
extensions/dylive-helper/vite.config.ts
Normal file
@ -0,0 +1,65 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { resolve } from "node:path";
|
||||
import { cpSync, mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
|
||||
function copyManifestAndAssets() {
|
||||
return {
|
||||
name: "copy-manifest-assets",
|
||||
closeBundle() {
|
||||
const dist = resolve(__dirname, "dist");
|
||||
mkdirSync(dist, { recursive: true });
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(resolve(__dirname, "manifest.json"), "utf8"),
|
||||
);
|
||||
writeFileSync(resolve(dist, "manifest.json"), JSON.stringify(manifest, null, 2));
|
||||
const iconsSrc = resolve(__dirname, "public/icons");
|
||||
if (existsSync(iconsSrc)) {
|
||||
mkdirSync(resolve(dist, "icons"), { recursive: true });
|
||||
cpSync(iconsSrc, resolve(dist, "icons"), { recursive: true });
|
||||
}
|
||||
// TikTok content is plain JS (not in rollup input as module)
|
||||
const dylive = resolve(__dirname, "src/content-dylive.js");
|
||||
if (existsSync(dylive)) {
|
||||
cpSync(dylive, resolve(dist, "content-dylive.js"));
|
||||
}
|
||||
const bridge = resolve(__dirname, "src/content-dylive-bridge.js");
|
||||
if (existsSync(bridge)) {
|
||||
cpSync(bridge, resolve(dist, "content-dylive-bridge.js"));
|
||||
}
|
||||
const icon = resolve(__dirname, "icon.png");
|
||||
if (existsSync(icon)) {
|
||||
cpSync(icon, resolve(dist, "icon.png"));
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
root: resolve(__dirname, "src"),
|
||||
base: "./",
|
||||
resolve: {
|
||||
alias: {
|
||||
"@x2/shared": resolve(__dirname, "vendor/shared/src/index.ts"),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: resolve(__dirname, "dist"),
|
||||
emptyOutDir: true,
|
||||
rollupOptions: {
|
||||
input: {
|
||||
background: resolve(__dirname, "src/background.ts"),
|
||||
content: resolve(__dirname, "src/content.ts"),
|
||||
popup: resolve(__dirname, "src/popup.html"),
|
||||
},
|
||||
output: {
|
||||
entryFileNames: "[name].js",
|
||||
chunkFileNames: "chunks/[name].js",
|
||||
assetFileNames: "[name][extname]",
|
||||
},
|
||||
},
|
||||
target: "es2022",
|
||||
minify: false,
|
||||
},
|
||||
plugins: [react(), copyManifestAndAssets()],
|
||||
});
|
||||
@ -1,26 +1,7 @@
|
||||
# dylive TikTok Cookie 助手
|
||||
# (已合并)请使用统一扩展
|
||||
|
||||
TikTok 的 `sessionid` 一般是 **HttpOnly**,页面 JS / 普通油猴读不到。
|
||||
**推荐 Chrome 插件**(`chrome.cookies` 可读 HttpOnly)。油猴脚本需要 Tampermonkey 的 `GM.cookie`。
|
||||
请加载:
|
||||
|
||||
## Chrome 插件(推荐)
|
||||
`../dylive-helper/dist`(先在 `dylive-helper` 目录执行 `npm install && npm run build`)
|
||||
|
||||
1. 打开 `chrome://extensions`
|
||||
2. 打开右上角「开发者模式」
|
||||
3. 「加载已解压的扩展程序」→ 选本目录 `extensions/tiktok-cookie-helper`
|
||||
4. 浏览器登录 [tiktok.com](https://www.tiktok.com)
|
||||
5. 点工具栏图标 → **复制 JSON** 或 **填入控制台**
|
||||
6. 到 [dylive /tiktok](https://dylive.nomadro.com/tiktok) 打开「粘贴 Cookie」,点保存
|
||||
|
||||
## 油猴脚本
|
||||
|
||||
1. 安装 Tampermonkey
|
||||
2. 导入 `tiktok-cookie.user.js`
|
||||
3. 打开并登录 tiktok.com,点右下角「导出 Cookie → dylive」
|
||||
4. 回到控制台「从剪贴板导入」
|
||||
|
||||
若提示不支持 `GM.cookie`,改用 Chrome 插件。
|
||||
|
||||
## 安全
|
||||
|
||||
`sessionid` 等同账号密码。不要发给别人,不要贴到聊天软件。
|
||||
顶栏含 TikTok + X(X2 原界面)。
|
||||
|
||||
@ -1,12 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Copy, RefreshCw, RotateCcw } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { RefreshCw, Square } from "lucide-react";
|
||||
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { useToast } from "@/components/Toast";
|
||||
import { fetchJson, fmtTs } from "@/lib/api";
|
||||
|
||||
type TabId = "workbench" | "cleanup" | "scrape" | "engage" | "jobs";
|
||||
|
||||
type X2Agent = {
|
||||
id: string;
|
||||
label?: string;
|
||||
@ -19,7 +21,6 @@ type X2Account = {
|
||||
id: string;
|
||||
username?: string;
|
||||
display_name?: string;
|
||||
agent_id?: string;
|
||||
last_seen_at?: string;
|
||||
};
|
||||
|
||||
@ -35,26 +36,68 @@ type X2Job = {
|
||||
received_at?: number;
|
||||
job_updated_at?: string;
|
||||
result?: Record<string, unknown>;
|
||||
params?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type X2Event = {
|
||||
id: string;
|
||||
event?: string;
|
||||
message?: string;
|
||||
created_at?: number;
|
||||
agent_id?: string;
|
||||
const TABS: { id: TabId; label: string }[] = [
|
||||
{ id: "workbench", label: "工作台" },
|
||||
{ id: "cleanup", label: "清理" },
|
||||
{ id: "scrape", label: "采集" },
|
||||
{ id: "engage", label: "互动" },
|
||||
{ id: "jobs", label: "任务" },
|
||||
];
|
||||
|
||||
const STATUS_ZH: Record<string, string> = {
|
||||
queued: "排队",
|
||||
running: "执行中",
|
||||
completed: "完成",
|
||||
failed: "失败",
|
||||
cancelled: "已取消",
|
||||
};
|
||||
|
||||
function kindLabel(kind?: string) {
|
||||
const m: Record<string, string> = {
|
||||
"cleanup.non_followers": "不互关扫描",
|
||||
"cleanup.unfollow": "限速取关",
|
||||
"cleanup.unfollow_visible": "可见取关",
|
||||
"scrape.profile": "画像",
|
||||
"scrape.following": "关注列表",
|
||||
"scrape.followers": "粉丝列表",
|
||||
"scrape.tweets": "推文",
|
||||
"scrape.search": "搜索",
|
||||
"scrape.home": "首页",
|
||||
"scrape.notifications": "通知",
|
||||
"engage.like": "点赞",
|
||||
"engage.follow": "关注",
|
||||
"engage.post": "发帖",
|
||||
"engage.reply": "回复",
|
||||
"engage.retweet": "转推",
|
||||
};
|
||||
return (kind && m[kind]) || kind || "任务";
|
||||
}
|
||||
|
||||
export default function XPage() {
|
||||
const toast = useToast();
|
||||
const [tab, setTab] = useState<TabId>("workbench");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [agents, setAgents] = useState<X2Agent[]>([]);
|
||||
const [accounts, setAccounts] = useState<X2Account[]>([]);
|
||||
const [jobs, setJobs] = useState<X2Job[]>([]);
|
||||
const [events, setEvents] = useState<X2Event[]>([]);
|
||||
const [stats, setStats] = useState<Record<string, number>>({});
|
||||
const [ingestToken, setIngestToken] = useState("");
|
||||
const [ingestUrl, setIngestUrl] = useState("/api/x2/ingest");
|
||||
const [extOnline, setExtOnline] = useState(false);
|
||||
|
||||
const [username, setUsername] = useState("");
|
||||
const [limit, setLimit] = useState(80);
|
||||
const [query, setQuery] = useState("");
|
||||
const [cleanupList, setCleanupList] = useState("");
|
||||
const [minD, setMinD] = useState(2000);
|
||||
const [maxD, setMaxD] = useState(5000);
|
||||
const [likeN, setLikeN] = useState(10);
|
||||
const [followN, setFollowN] = useState(5);
|
||||
const [postText, setPostText] = useState("");
|
||||
const [statusUrl, setStatusUrl] = useState("");
|
||||
const [replyText, setReplyText] = useState("");
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
@ -62,274 +105,487 @@ export default function XPage() {
|
||||
setAgents(st?.agents || []);
|
||||
setAccounts(st?.accounts || []);
|
||||
setJobs(st?.jobs || []);
|
||||
setEvents(st?.events || []);
|
||||
setStats(st?.stats || {});
|
||||
setIngestToken(String(st?.ingest_token || ""));
|
||||
setIngestUrl(String(st?.ingest_url || "/api/x2/ingest"));
|
||||
setExtOnline(Boolean(st?.extension_online));
|
||||
const accs: X2Account[] = st?.accounts || [];
|
||||
if (!username && accs[0]?.username) setUsername(String(accs[0].username));
|
||||
} catch (e: any) {
|
||||
toast.push(e?.message || "加载失败", "err");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [toast]);
|
||||
}, [toast, username]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const t = setInterval(() => void load(), 8000);
|
||||
const t = setInterval(() => void load(), 4000);
|
||||
return () => clearInterval(t);
|
||||
}, [load]);
|
||||
|
||||
const copyToken = async () => {
|
||||
const createJob = async (kind: string, params: Record<string, unknown> = {}) => {
|
||||
if (!extOnline) {
|
||||
toast.push("插件未在线:请加载 dylive Helper,并打开本站任意页完成自动配对", "err");
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(ingestToken);
|
||||
toast.push("已复制 X2 Token", "ok");
|
||||
} catch {
|
||||
toast.push("复制失败", "err");
|
||||
const merged = {
|
||||
...(username.trim() ? { username: username.trim().replace(/^@/, "") } : {}),
|
||||
export: "none",
|
||||
...params,
|
||||
};
|
||||
const r = await fetchJson("/api/x2/jobs", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ kind, params: merged }),
|
||||
});
|
||||
if (r?.job) {
|
||||
setJobs((prev) => [r.job, ...prev.filter((j) => j.id !== r.job.id)]);
|
||||
setSelectedId(r.job.id);
|
||||
toast.push(`已下发:${kindLabel(kind)}(插件领取后执行)`, "ok");
|
||||
setTab("jobs");
|
||||
} else {
|
||||
toast.push("创建失败", "err");
|
||||
}
|
||||
} catch (e: any) {
|
||||
toast.push(e?.message || "创建失败", "err");
|
||||
}
|
||||
};
|
||||
|
||||
const rotateToken = async () => {
|
||||
const r = await fetchJson("/api/x2/token/rotate", { method: "POST" });
|
||||
setIngestToken(String(r?.ingest_token || ""));
|
||||
toast.push("Token 已轮换,请同步到 X2 设置", "ok");
|
||||
const cancelJob = async (id: string) => {
|
||||
try {
|
||||
const r = await fetchJson(`/api/x2/jobs/${encodeURIComponent(id)}/cancel`, {
|
||||
method: "POST",
|
||||
});
|
||||
if (r?.job) {
|
||||
setJobs((prev) => [r.job, ...prev.filter((j) => j.id !== r.job.id)]);
|
||||
toast.push("已请求取消", "ok");
|
||||
}
|
||||
} catch (e: any) {
|
||||
toast.push(e?.message || "取消失败", "err");
|
||||
}
|
||||
};
|
||||
|
||||
const origin =
|
||||
typeof window !== "undefined" ? window.location.origin : "https://dylive.nomadro.com";
|
||||
const fullIngest = `${origin}${ingestUrl.startsWith("/") ? ingestUrl : `/${ingestUrl}`}`;
|
||||
const selected = useMemo(
|
||||
() => jobs.find((j) => j.id === selectedId) || jobs[0] || null,
|
||||
[jobs, selectedId],
|
||||
);
|
||||
|
||||
const field =
|
||||
"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100";
|
||||
const btnPrimary =
|
||||
"rounded-lg bg-cyan-600/90 px-3 py-2 text-xs font-medium text-white hover:bg-cyan-500";
|
||||
const btnGhost =
|
||||
"rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300 hover:bg-white/10";
|
||||
const panel = "rounded-2xl border border-white/10 bg-black/25 p-4";
|
||||
|
||||
return (
|
||||
<Shell>
|
||||
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5 text-xl text-slate-100">
|
||||
𝕏
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="font-display text-xl font-semibold text-white sm:text-2xl">X / X2</h2>
|
||||
<p className="mt-1 text-sm text-slate-400">
|
||||
接收 PVE 上 X2 插件/Agent 推送的账号、任务与心跳
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="font-display text-xl font-semibold text-white sm:text-2xl">X Ops</h2>
|
||||
<p className="mt-1 text-sm text-slate-400">
|
||||
Web 下发任务 · Chrome 插件在浏览器执行(插件 popup 仍可独立操作)
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void load()}
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300 hover:bg-white/10"
|
||||
>
|
||||
<RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||
<button type="button" onClick={() => void load()} className={btnGhost}>
|
||||
<RefreshCw className={`mr-1 inline h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section className="mb-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<div className="mb-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
{[
|
||||
["在线 Agent", stats.agents ? `${stats.online_count ?? 0}/${stats.agents}` : String(stats.online_count ?? 0)],
|
||||
["账号", String(stats.accounts ?? accounts.length)],
|
||||
["运行中", String(stats.running ?? 0)],
|
||||
["近完成/失败", `${stats.completed ?? 0} / ${stats.failed ?? 0}`],
|
||||
].map(([k, v]) => (
|
||||
["插件", extOnline ? "在线" : "离线", extOnline ? "text-emerald-300" : "text-amber-300"],
|
||||
["账号", String(stats.accounts ?? accounts.length), "text-white"],
|
||||
["排队/执行", `${stats.queued ?? 0} / ${stats.running ?? 0}`, "text-white"],
|
||||
["完成/失败", `${stats.completed ?? 0} / ${stats.failed ?? 0}`, "text-white"],
|
||||
].map(([k, v, c]) => (
|
||||
<div key={k} className="rounded-xl border border-white/10 bg-black/25 p-3">
|
||||
<div className="text-[11px] text-slate-500">{k}</div>
|
||||
<div className="mt-1 font-display text-2xl text-white">{v}</div>
|
||||
<div className={`mt-1 font-display text-2xl ${c}`}>{v}</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<section className="mb-4 rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4">
|
||||
<h3 className="text-sm font-medium text-slate-100">接入配置(填到 X2)</h3>
|
||||
<p className="mt-1 text-[11px] text-slate-500">
|
||||
X2 Desktop 设置里填写下方 URL + Token;Agent 会推送心跳与任务结果到本站。
|
||||
</p>
|
||||
<div className="mt-3 grid gap-2 sm:grid-cols-[1fr_auto]">
|
||||
<label className="text-xs text-slate-400">
|
||||
Ingest URL
|
||||
<input
|
||||
readOnly
|
||||
value={fullIngest}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 font-mono text-xs text-slate-200"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void navigator.clipboard.writeText(fullIngest)}
|
||||
className="rounded-lg border border-white/10 px-3 py-2 text-xs text-slate-300"
|
||||
>
|
||||
复制 URL
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 grid gap-2 sm:grid-cols-[1fr_auto]">
|
||||
<label className="text-xs text-slate-400">
|
||||
X-X2-Token
|
||||
<input
|
||||
readOnly
|
||||
value={ingestToken}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 font-mono text-xs text-slate-200"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copyToken()}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 px-3 py-2 text-xs text-slate-300"
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
复制
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void rotateToken()}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-100"
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
轮换
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="mb-4 grid gap-4 xl:grid-cols-2">
|
||||
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-slate-100">Agent</h3>
|
||||
{agents.length === 0 ? (
|
||||
<p className="text-xs text-slate-500">尚无心跳。请启动 X2 并配置推送。</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{agents.map((a) => (
|
||||
<div
|
||||
key={a.id}
|
||||
className="flex items-center justify-between gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm text-slate-100">{a.label || a.id}</div>
|
||||
<div className="text-[10px] text-slate-500">
|
||||
{a.id}
|
||||
{a.last_seen_at ? ` · ${fmtTs(a.last_seen_at)}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col items-end gap-0.5 text-[10px]">
|
||||
<span className={a.online ? "text-teal-300" : "text-slate-500"}>
|
||||
{a.online ? "在线" : "离线"}
|
||||
</span>
|
||||
<span className={a.extension_connected ? "text-sky-300" : "text-slate-600"}>
|
||||
{a.extension_connected ? "扩展已连" : "扩展未连"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-slate-100">账号</h3>
|
||||
{accounts.length === 0 ? (
|
||||
<p className="text-xs text-slate-500">暂无同步账号。</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{accounts.map((a) => (
|
||||
<div
|
||||
key={a.id}
|
||||
className="flex items-center justify-between gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm text-slate-100">@{a.username}</div>
|
||||
<div className="truncate text-[10px] text-slate-500">
|
||||
{a.display_name || "—"} · {a.agent_id || ""}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="mb-4 rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-slate-100">最近任务</h3>
|
||||
<div className="table-scroll">
|
||||
<table className="w-full min-w-[640px] text-left text-xs sm:text-sm">
|
||||
<thead className="text-[11px] text-slate-500">
|
||||
<tr>
|
||||
<th className="pb-2 pr-2">时间</th>
|
||||
<th className="pb-2 pr-2">类型</th>
|
||||
<th className="pb-2 pr-2">状态</th>
|
||||
<th className="pb-2 pr-2">账号</th>
|
||||
<th className="pb-2">进度 / 错误</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{jobs.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="py-6 text-center text-slate-500">
|
||||
暂无任务推送
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
jobs.map((j) => (
|
||||
<tr key={j.id} className="border-t border-white/5 align-top">
|
||||
<td className="py-2 pr-2 text-slate-400">
|
||||
{j.received_at ? fmtTs(j.received_at) : j.job_updated_at || "—"}
|
||||
</td>
|
||||
<td className="py-2 pr-2 text-slate-200">{j.kind || "—"}</td>
|
||||
<td className="py-2 pr-2">
|
||||
<span
|
||||
className={
|
||||
j.status === "completed"
|
||||
? "text-teal-300"
|
||||
: j.status === "failed"
|
||||
? "text-rose-300"
|
||||
: j.status === "running"
|
||||
? "text-amber-200"
|
||||
: "text-slate-400"
|
||||
}
|
||||
>
|
||||
{j.status || "—"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-2 pr-2 text-slate-300">
|
||||
{j.account_username ? `@${j.account_username}` : "—"}
|
||||
</td>
|
||||
<td className="py-2 text-slate-400">
|
||||
{j.progress_total
|
||||
? `${j.progress_current || 0}/${j.progress_total}`
|
||||
: j.progress_message || ""}
|
||||
{j.error ? (
|
||||
<div className="mt-0.5 max-w-md truncate text-rose-300/90" title={j.error}>
|
||||
{j.error}
|
||||
</div>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{!extOnline ? (
|
||||
<div className="mb-4 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-xs text-amber-100">
|
||||
插件未在线。加载 <code className="text-amber-50">extensions/dylive-helper/dist</code>
|
||||
,登录本站并打开本页即可<strong className="font-medium">自动配对</strong>
|
||||
(无需在插件里手填 Token)。X 页签功能仍可在插件内独立使用。
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-slate-100">事件</h3>
|
||||
{events.length === 0 ? (
|
||||
<p className="text-xs text-slate-500">暂无事件。</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{events.map((e) => (
|
||||
<li
|
||||
key={e.id}
|
||||
className="rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-xs text-slate-300"
|
||||
>
|
||||
<span className="text-slate-500">
|
||||
{e.created_at ? fmtTs(e.created_at) : ""} · {e.event}
|
||||
</span>
|
||||
<div className="mt-0.5 text-slate-200">{e.message || "—"}</div>
|
||||
</li>
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
<label className="text-xs text-slate-400">
|
||||
目标账号
|
||||
<input
|
||||
className={field}
|
||||
style={{ width: 180 }}
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder={accounts[0]?.username || "可空=当前登录"}
|
||||
list="x-accs"
|
||||
/>
|
||||
<datalist id="x-accs">
|
||||
{accounts.map((a) => (
|
||||
<option key={a.id} value={a.username || ""} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</datalist>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
条数
|
||||
<input
|
||||
type="number"
|
||||
className={field}
|
||||
style={{ width: 100 }}
|
||||
value={limit}
|
||||
onChange={(e) => setLimit(Number(e.target.value) || 80)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<nav className="mb-4 flex flex-wrap gap-1">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
onClick={() => setTab(t.id)}
|
||||
className={
|
||||
"rounded-lg px-3 py-2 text-xs font-medium " +
|
||||
(tab === t.id
|
||||
? "bg-white/15 text-white"
|
||||
: "bg-white/5 text-slate-400 hover:bg-white/10")
|
||||
}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{tab === "workbench" ? (
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<section className={panel}>
|
||||
<h3 className="text-sm font-medium text-slate-100">快捷下发</h3>
|
||||
<p className="mt-1 text-[11px] text-slate-500">与插件 X 页签同类能力,由 Web 入队、插件领取执行</p>
|
||||
<div className="mt-3 grid grid-cols-2 gap-2">
|
||||
{(
|
||||
[
|
||||
["cleanup.non_followers", "扫描不互关"],
|
||||
["scrape.profile", "画像"],
|
||||
["scrape.followers", "粉丝"],
|
||||
["scrape.tweets", "推文"],
|
||||
["scrape.home", "首页时间线"],
|
||||
["engage.like", "可见点赞"],
|
||||
] as const
|
||||
).map(([kind, label]) => (
|
||||
<button
|
||||
key={kind}
|
||||
type="button"
|
||||
className={btnPrimary}
|
||||
onClick={() =>
|
||||
void createJob(kind, {
|
||||
limit: kind.startsWith("engage") ? likeN : limit,
|
||||
})
|
||||
}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className={panel}>
|
||||
<h3 className="text-sm font-medium text-slate-100">Agent</h3>
|
||||
{agents.length === 0 ? (
|
||||
<p className="mt-2 text-xs text-slate-500">等待插件心跳…</p>
|
||||
) : (
|
||||
<ul className="mt-2 space-y-2 text-xs text-slate-300">
|
||||
{agents.map((a) => (
|
||||
<li key={a.id} className="flex justify-between gap-2 border-b border-white/5 pb-2">
|
||||
<span>
|
||||
{a.label || a.id}
|
||||
{a.extension_connected ? " · 扩展" : ""}
|
||||
</span>
|
||||
<span className={a.online ? "text-emerald-300" : "text-slate-500"}>
|
||||
{a.online ? "在线" : "离线"}
|
||||
{a.last_seen_at ? ` · ${fmtTs(a.last_seen_at)}` : ""}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{tab === "cleanup" ? (
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<section className={panel}>
|
||||
<h3 className="text-sm font-medium text-slate-100">不互关扫描</h3>
|
||||
<button
|
||||
type="button"
|
||||
className={`${btnPrimary} mt-3`}
|
||||
onClick={() => void createJob("cleanup.non_followers", { limit })}
|
||||
>
|
||||
扫描
|
||||
</button>
|
||||
</section>
|
||||
<section className={panel}>
|
||||
<h3 className="text-sm font-medium text-slate-100">限速取关</h3>
|
||||
<textarea
|
||||
className={`${field} min-h-[120px] font-mono text-xs`}
|
||||
placeholder="每行一个用户名"
|
||||
value={cleanupList}
|
||||
onChange={(e) => setCleanupList(e.target.value)}
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
<input
|
||||
type="number"
|
||||
className={field}
|
||||
style={{ width: 110 }}
|
||||
value={minD}
|
||||
onChange={(e) => setMinD(Number(e.target.value))}
|
||||
title="最小间隔 ms"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
className={field}
|
||||
style={{ width: 110 }}
|
||||
value={maxD}
|
||||
onChange={(e) => setMaxD(Number(e.target.value))}
|
||||
title="最大间隔 ms"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-lg border border-rose-500/40 bg-rose-500/15 px-3 py-2 text-xs text-rose-100"
|
||||
onClick={() => {
|
||||
const usernames = cleanupList
|
||||
.split(/[\n,,\s]+/)
|
||||
.map((s) => s.replace(/^@/, "").trim())
|
||||
.filter(Boolean);
|
||||
if (!usernames.length) return toast.push("名单为空", "err");
|
||||
if (!confirm(`确认取关 ${usernames.length} 人?`)) return;
|
||||
void createJob("cleanup.unfollow", {
|
||||
usernames,
|
||||
minDelayMs: minD,
|
||||
maxDelayMs: maxD,
|
||||
});
|
||||
}}
|
||||
>
|
||||
开始取关
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{tab === "scrape" ? (
|
||||
<section className={panel}>
|
||||
<h3 className="text-sm font-medium text-slate-100">数据采集</h3>
|
||||
<label className="mt-3 block text-xs text-slate-400">
|
||||
搜索词
|
||||
<input className={field} value={query} onChange={(e) => setQuery(e.target.value)} />
|
||||
</label>
|
||||
<div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-3">
|
||||
{(
|
||||
[
|
||||
["scrape.profile", "画像"],
|
||||
["scrape.following", "关注"],
|
||||
["scrape.followers", "粉丝"],
|
||||
["scrape.tweets", "推文"],
|
||||
["scrape.home", "首页"],
|
||||
["scrape.notifications", "通知"],
|
||||
["scrape.bookmarks", "书签"],
|
||||
] as const
|
||||
).map(([kind, label]) => (
|
||||
<button
|
||||
key={kind}
|
||||
type="button"
|
||||
className={btnPrimary}
|
||||
onClick={() => void createJob(kind, { limit })}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={btnGhost}
|
||||
onClick={() => {
|
||||
if (!query.trim()) return toast.push("先填搜索词", "err");
|
||||
void createJob("scrape.search", { query: query.trim(), limit });
|
||||
}}
|
||||
>
|
||||
搜索推文
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === "engage" ? (
|
||||
<section className={panel}>
|
||||
<h3 className="text-sm font-medium text-slate-100">互动</h3>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<label className="text-xs text-slate-400">
|
||||
点赞数
|
||||
<input
|
||||
type="number"
|
||||
className={field}
|
||||
style={{ width: 90 }}
|
||||
value={likeN}
|
||||
onChange={(e) => setLikeN(Number(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
关注数
|
||||
<input
|
||||
type="number"
|
||||
className={field}
|
||||
style={{ width: 90 }}
|
||||
value={followN}
|
||||
onChange={(e) => setFollowN(Number(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={btnPrimary}
|
||||
onClick={() => void createJob("engage.like", { limit: likeN })}
|
||||
>
|
||||
点赞
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={btnPrimary}
|
||||
onClick={() => void createJob("engage.follow", { limit: followN })}
|
||||
>
|
||||
关注
|
||||
</button>
|
||||
</div>
|
||||
<label className="mt-3 block text-xs text-slate-400">
|
||||
发帖
|
||||
<textarea
|
||||
className={`${field} min-h-[72px]`}
|
||||
value={postText}
|
||||
onChange={(e) => setPostText(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={`${btnPrimary} mt-2`}
|
||||
onClick={() => {
|
||||
if (!postText.trim()) return toast.push("内容为空", "err");
|
||||
void createJob("engage.post", { text: postText.trim() });
|
||||
}}
|
||||
>
|
||||
发帖
|
||||
</button>
|
||||
<label className="mt-3 block text-xs text-slate-400">
|
||||
推文链接
|
||||
<input className={field} value={statusUrl} onChange={(e) => setStatusUrl(e.target.value)} />
|
||||
</label>
|
||||
<label className="mt-2 block text-xs text-slate-400">
|
||||
回复内容
|
||||
<input className={field} value={replyText} onChange={(e) => setReplyText(e.target.value)} />
|
||||
</label>
|
||||
<div className="mt-2 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={btnPrimary}
|
||||
onClick={() => {
|
||||
if (!statusUrl.trim() || !replyText.trim()) return toast.push("链接和回复都要填", "err");
|
||||
void createJob("engage.reply", {
|
||||
statusUrl: statusUrl.trim(),
|
||||
text: replyText.trim(),
|
||||
});
|
||||
}}
|
||||
>
|
||||
回复
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={btnGhost}
|
||||
onClick={() => {
|
||||
if (!statusUrl.trim()) return toast.push("先填链接", "err");
|
||||
void createJob("engage.retweet", { statusUrl: statusUrl.trim() });
|
||||
}}
|
||||
>
|
||||
转推
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{tab === "jobs" || selected ? (
|
||||
<div className={`grid gap-4 lg:grid-cols-2 ${tab === "jobs" ? "" : "mt-4"}`}>
|
||||
{(tab === "jobs" || true) && tab === "jobs" ? (
|
||||
<section className={panel}>
|
||||
<h3 className="mb-2 text-sm font-medium text-slate-100">任务队列</h3>
|
||||
<div className="max-h-[420px] space-y-2 overflow-auto">
|
||||
{jobs.length === 0 ? (
|
||||
<p className="text-xs text-slate-500">暂无任务</p>
|
||||
) : (
|
||||
jobs.map((j) => (
|
||||
<button
|
||||
key={j.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedId(j.id)}
|
||||
className={
|
||||
"flex w-full items-start justify-between gap-2 rounded-lg border px-3 py-2 text-left text-xs " +
|
||||
(selected?.id === j.id
|
||||
? "border-cyan-500/40 bg-cyan-500/10"
|
||||
: "border-white/10 bg-black/20")
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<div className="text-slate-100">{kindLabel(j.kind)}</div>
|
||||
<div className="text-slate-500">
|
||||
{STATUS_ZH[j.status || ""] || j.status} · {j.progress_message || ""}
|
||||
</div>
|
||||
</div>
|
||||
{(j.status === "running" || j.status === "queued") && (
|
||||
<span
|
||||
role="button"
|
||||
className="inline-flex items-center gap-1 text-rose-300"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void cancelJob(j.id);
|
||||
}}
|
||||
>
|
||||
<Square className="h-3 w-3" /> 取消
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
{tab === "jobs" ? (
|
||||
<section className={panel}>
|
||||
<h3 className="text-sm font-medium text-slate-100">结果</h3>
|
||||
{!selected ? (
|
||||
<p className="mt-2 text-xs text-slate-500">点选左侧任务</p>
|
||||
) : (
|
||||
<pre className="mt-2 max-h-[420px] overflow-auto whitespace-pre-wrap break-words rounded-lg bg-black/40 p-3 font-mono text-[11px] text-slate-300">
|
||||
{JSON.stringify(
|
||||
{
|
||||
id: selected.id,
|
||||
kind: selected.kind,
|
||||
status: selected.status,
|
||||
error: selected.error,
|
||||
progress: {
|
||||
current: selected.progress_current,
|
||||
total: selected.progress_total,
|
||||
message: selected.progress_message,
|
||||
},
|
||||
result: selected.result,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user