From 4c8eafacb3a740329f954df7db1f3b388a7965d6 Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 14 Aug 2026 13:19:06 -0500 Subject: [PATCH] =?UTF-8?q?feat:=20TikTok=20Cookie=20=E6=8C=89=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E8=AE=A1=E6=97=B6=EF=BC=8C=E5=B9=B6=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=A4=9A=E8=B4=A6=E5=8F=B7=E7=8B=AC=E7=AB=8B=E4=BC=9A=E8=AF=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- backend/app/db.py | 6 ++ backend/app/main.py | 3 + backend/app/tiktok_db.py | 2 +- backend/app/tiktok_session.py | 42 ++++++++- backend/tests/test_tiktok_session.py | 52 +++++++++++- frontend/src/app/tiktok/page.tsx | 122 +++++++++++++++++++++++++-- 6 files changed, 218 insertions(+), 9 deletions(-) diff --git a/backend/app/db.py b/backend/app/db.py index fee9119..fa41a9e 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -233,6 +233,7 @@ def init_db() -> None: oauth_checked_at REAL NOT NULL DEFAULT 0, oauth_error TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '', + cookie_saved_at REAL NOT NULL DEFAULT 0, created_at REAL NOT NULL, updated_at REAL NOT NULL ); @@ -266,6 +267,11 @@ def init_db() -> None: CREATE INDEX IF NOT EXISTS idx_tiktok_jobs_upload ON tiktok_jobs(status, upload_at); """ ) + tt_cols = {r[1] for r in conn.execute("PRAGMA table_info(tiktok_channels)").fetchall()} + if "cookie_saved_at" not in tt_cols: + conn.execute( + "ALTER TABLE tiktok_channels ADD COLUMN cookie_saved_at REAL NOT NULL DEFAULT 0" + ) sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()} for col, ddl in [ ("oauth_ok", "INTEGER NOT NULL DEFAULT -1"), diff --git a/backend/app/main.py b/backend/app/main.py index 2b49e39..8446b0f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -829,6 +829,7 @@ def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: out["authorized"] = tiktok_session.channel_has_session(ch) out["auth_mode"] = "cookie" if out["authorized"] else "" out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1) + out.update(tiktok_session.cookie_age_info(ch, persist_backfill=True)) return out @@ -899,6 +900,7 @@ async def tiktok_channel_session_delete(channel_pk: str) -> dict[str, Any]: oauth_ok=0, oauth_error="Cookie 已清除", refresh_token="", + cookie_saved_at=0, ) return {"ok": True, "channel": _public_tiktok_channel(updated)} @@ -1003,6 +1005,7 @@ async def tiktok_channels_update(channel_pk: str, body: TikTokChannelUpdate) -> async def tiktok_channels_delete(channel_pk: str) -> dict[str, Any]: from . import tiktok_db + await asyncio.to_thread(tiktok_session.delete_session_cookies, channel_pk) ok = await _db(tiktok_db.delete_tiktok_channel, channel_pk) if not ok: raise HTTPException(404, "账号不存在") diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index a1c3c70..2548161 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -96,7 +96,7 @@ def update_tiktok_channel(channel_pk: str, **fields: Any) -> dict[str, Any] | No "name", "tiktok_open_id", "tiktok_username", "client_key", "client_secret", "refresh_token", "access_token", "token_expires_at", "enabled", "daily_min", "daily_max", "title_template", "description_template", "privacy_level", "last_assigned_at", - "oauth_ok", "oauth_checked_at", "oauth_error", "note", + "oauth_ok", "oauth_checked_at", "oauth_error", "note", "cookie_saved_at", } with _lock: conn = _connect() diff --git a/backend/app/tiktok_session.py b/backend/app/tiktok_session.py index 42385e3..a2f6cbc 100644 --- a/backend/app/tiktok_session.py +++ b/backend/app/tiktok_session.py @@ -17,6 +17,7 @@ if str(_VENDOR_ROOT) not in sys.path: sys.path.insert(0, str(_VENDOR_ROOT)) DEFAULT_DC = "useast2a" +COOKIE_TTL_DAYS = 30.0 REQUIRED_COOKIES = ("sessionid", "tt-target-idc") _DC_CANDIDATES = ("useast5a", "useast1a", "useast2a", "euwest1a", "alisg", "no1a", "useast8") _PROBE_UA = ( @@ -99,11 +100,13 @@ def save_session_from_values( {"name": "tt-target-idc", "value": dc, "domain": ".tiktok.com", "path": "/"}, ] save_session_cookies(channel_pk, cookies) + now = time.time() patch: dict[str, Any] = { "oauth_ok": 1, - "oauth_checked_at": time.time(), + "oauth_checked_at": now, "oauth_error": "", "refresh_token": "cookie", + "cookie_saved_at": now, } if username.strip(): patch["tiktok_username"] = username.strip() @@ -121,6 +124,43 @@ def channel_has_session(channel: dict[str, Any] | None) -> bool: return "sessionid" in names and bool(next((c.get("value") for c in cookies if c.get("name") == "sessionid"), "")) +def cookie_age_info(channel: dict[str, Any] | None, *, persist_backfill: bool = False) -> dict[str, Any]: + """Days since this account's Cookie was pasted. Probe/DC rewrite must not reset the clock.""" + ch = channel or {} + pk = str(ch.get("id") or "") + has = channel_has_session(ch) if pk else False + saved = float(ch.get("cookie_saved_at") or 0) + if has and saved <= 0 and pk: + path = session_cookie_path(pk) + if path.is_file(): + saved = float(path.stat().st_mtime) + if persist_backfill: + tiktok_db.update_tiktok_channel(pk, cookie_saved_at=saved) + if not has or saved <= 0: + return { + "cookie_saved_at": 0.0, + "cookie_age_days": None, + "cookie_ttl_days": COOKIE_TTL_DAYS, + "cookie_expires_in_days": None, + "cookie_status": "missing", + } + age_days = max(0.0, (time.time() - saved) / 86400.0) + left_days = COOKIE_TTL_DAYS - age_days + if left_days <= 0: + status = "expired" + elif left_days <= 5: + status = "warn" + else: + status = "ok" + return { + "cookie_saved_at": saved, + "cookie_age_days": round(age_days, 1), + "cookie_ttl_days": COOKIE_TTL_DAYS, + "cookie_expires_in_days": round(max(0.0, left_days), 1), + "cookie_status": status, + } + + def probe_channel_session(channel: dict[str, Any] | None) -> dict[str, Any]: ch = channel or {} pk = str(ch.get("id") or "") diff --git a/backend/tests/test_tiktok_session.py b/backend/tests/test_tiktok_session.py index ac2d77b..3992da3 100644 --- a/backend/tests/test_tiktok_session.py +++ b/backend/tests/test_tiktok_session.py @@ -8,12 +8,62 @@ from app import tiktok_session def test_save_and_load_session_cookies(temp_db, tmp_path, monkeypatch): monkeypatch.setattr(tiktok_session, "cookies_dir", lambda: tmp_path) ch = tiktok_db.create_tiktok_channel(name="tt1") - tiktok_session.save_session_from_values(ch["id"], sessionid="abc123", dc_id="useast2a") + saved = tiktok_session.save_session_from_values(ch["id"], sessionid="abc123", dc_id="useast2a") assert tiktok_session.channel_has_session(ch) cookies = tiktok_session.load_session_cookies(ch["id"]) names = {c["name"] for c in cookies} assert "sessionid" in names assert "tt-target-idc" in names + assert float(saved.get("cookie_saved_at") or 0) > 0 + + +def test_cookie_timer_not_reset_by_probe(temp_db, tmp_path, monkeypatch): + monkeypatch.setattr(tiktok_session, "cookies_dir", lambda: tmp_path) + now = 1_700_000_000.0 + monkeypatch.setattr(tiktok_session.time, "time", lambda: now) + ch = tiktok_db.create_tiktok_channel(name="tt-timer") + saved = tiktok_session.save_session_from_values(ch["id"], sessionid="abc123", dc_id="useast5a") + assert float(saved["cookie_saved_at"]) == now + monkeypatch.setattr(tiktok_session.time, "time", lambda: now + 86_400 * 3) + tiktok_session.probe_channel_session(saved) + ch2 = tiktok_db.get_tiktok_channel(ch["id"]) + assert float(ch2["cookie_saved_at"]) == now + info = tiktok_session.cookie_age_info(ch2) + assert info["cookie_age_days"] == 3.0 + assert info["cookie_expires_in_days"] == 27.0 + assert info["cookie_status"] == "ok" + + +def test_cookie_timer_warn_and_expired(temp_db, tmp_path, monkeypatch): + monkeypatch.setattr(tiktok_session, "cookies_dir", lambda: tmp_path) + now = 1_700_000_000.0 + monkeypatch.setattr(tiktok_session.time, "time", lambda: now) + ch = tiktok_db.create_tiktok_channel(name="tt-exp") + saved = tiktok_session.save_session_from_values(ch["id"], sessionid="sid", dc_id="useast5a") + monkeypatch.setattr(tiktok_session.time, "time", lambda: now + 86_400 * 27) + warn = tiktok_session.cookie_age_info(saved) + assert warn["cookie_status"] == "warn" + monkeypatch.setattr(tiktok_session.time, "time", lambda: now + 86_400 * 31) + expired = tiktok_session.cookie_age_info(saved) + assert expired["cookie_status"] == "expired" + assert expired["cookie_expires_in_days"] == 0.0 + + +def test_two_accounts_independent_cookies(temp_db, tmp_path, monkeypatch): + monkeypatch.setattr(tiktok_session, "cookies_dir", lambda: tmp_path) + a = tiktok_db.create_tiktok_channel(name="acc-a") + b = tiktok_db.create_tiktok_channel(name="acc-b") + tiktok_session.save_session_from_values(a["id"], sessionid="sid-a", dc_id="useast5a") + tiktok_session.save_session_from_values(b["id"], sessionid="sid-b", dc_id="useast2a") + sid_a = next(c["value"] for c in tiktok_session.load_session_cookies(a["id"]) if c["name"] == "sessionid") + sid_b = next(c["value"] for c in tiktok_session.load_session_cookies(b["id"]) if c["name"] == "sessionid") + assert sid_a == "sid-a" + assert sid_b == "sid-b" + tiktok_session.delete_session_cookies(a["id"]) + tiktok_db.update_tiktok_channel(a["id"], cookie_saved_at=0) + assert not tiktok_session.channel_has_session({"id": a["id"]}) + assert tiktok_session.channel_has_session({"id": b["id"]}) + assert tiktok_session.cookie_age_info(tiktok_db.get_tiktok_channel(b["id"]))["cookie_status"] == "ok" def test_manual_upload_rejects_in_flight_uploading(temp_db, tmp_path): diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index 2f98978..a08cca6 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -33,6 +33,11 @@ type Channel = { title_template?: string; description_template?: string; note?: string; + cookie_saved_at?: number; + cookie_age_days?: number | null; + cookie_ttl_days?: number; + cookie_expires_in_days?: number | null; + cookie_status?: "ok" | "warn" | "expired" | "missing" | string; }; type BoardChannel = { @@ -92,6 +97,7 @@ export default function TikTokPage() { const [formDesc, setFormDesc] = useState("{anchor}\n{url}"); const [sessionChannelId, setSessionChannelId] = useState(""); + const [sessionChannelName, setSessionChannelName] = useState(""); const [sessionId, setSessionId] = useState(""); const [sessionDcId, setSessionDcId] = useState(""); const [sessionUsername, setSessionUsername] = useState(""); @@ -279,6 +285,7 @@ export default function TikTokPage() { const openSessionForm = (id: string, ch?: Channel) => { setSessionChannelId(id); + setSessionChannelName(ch?.name || ""); setSessionId(""); setSessionDcId(""); setSessionUsername(ch?.tiktok_username || ""); @@ -286,6 +293,15 @@ export default function TikTokPage() { setShowSessionForm(true); }; + const toggleChannelEnabled = async (ch: Channel) => { + await fetchJson(`/api/tiktok/channels/${ch.id}`, { + method: "PATCH", + body: JSON.stringify({ enabled: !ch.enabled }), + }); + toast.push(ch.enabled ? "已停用此账号" : "已启用此账号", "ok"); + void load(); + }; + const sampleNow = async () => { const r = await fetchJson("/api/tiktok/sample-now", { method: "POST" }); const n = Number(r.enqueued || 0); @@ -339,9 +355,45 @@ export default function TikTokPage() { [], ); - const displayChannels: BoardChannel[] = boardChannels.length - ? boardChannels - : channels.map((c) => ({ + const cookieAgeLabel = (ch?: Channel) => { + if (!ch?.authorized) return "未配置 Cookie"; + const days = Number(ch.cookie_age_days ?? 0); + const left = Number(ch.cookie_expires_in_days ?? 0); + const used = + days < 1 ? `已用 ${Math.max(0, Math.round(days * 24))} 小时` : `已用 ${days} 天`; + if (ch.cookie_status === "expired") return `${used} · 已过期,请更新`; + if (ch.cookie_status === "warn") return `${used} · 即将过期(剩 ${left} 天)`; + return `${used} · 约剩 ${left} 天`; + }; + + const cookieAgeClass = (ch?: Channel) => { + if (!ch?.authorized || ch.cookie_status === "missing") return "text-rose-300"; + if (ch.cookie_status === "expired") return "text-rose-300"; + if (ch.cookie_status === "warn") return "text-amber-300"; + return "text-teal-300"; + }; + + const displayChannels: BoardChannel[] = (() => { + const fromBoard = boardChannels.length + ? boardChannels + : channels.map((c) => ({ + id: c.id, + name: c.name, + tiktok_username: c.tiktok_username, + enabled: c.enabled, + authorized: c.authorized, + used: 0, + scheduled: 0, + uploaded: 0, + pending: 0, + gap: 9, + max_met: false, + daily_max: 9, + })); + const seen = new Set(fromBoard.map((c) => c.id)); + const extra = channels + .filter((c) => !seen.has(c.id)) + .map((c) => ({ id: c.id, name: c.name, tiktok_username: c.tiktok_username, @@ -355,6 +407,8 @@ export default function TikTokPage() { max_met: false, daily_max: 9, })); + return [...fromBoard, ...extra]; + })(); if (loading && !status) { return ( @@ -498,6 +552,9 @@ export default function TikTokPage() { {showForm && (

{editId ? "编辑账号" : "新增 TikTok 账号"}

+

+ 可添加多个账号,每个账号各自粘贴 Cookie、各自计时,互不影响。 +