From d8fdeaa71ce105bca79026ca1963b2b92815e6f5 Mon Sep 17 00:00:00 2001 From: eric Date: Fri, 14 Aug 2026 10:16:20 -0500 Subject: [PATCH] =?UTF-8?q?TikTok:=20Cookie=20=E4=B8=8A=E4=BC=A0=EF=BC=88T?= =?UTF-8?q?iktokAutoUploader=EF=BC=89=EF=BC=8C=E6=9B=BF=E4=BB=A3=E5=BC=80?= =?UTF-8?q?=E5=8F=91=E8=80=85=20OAuth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 账号粘贴 sessionid 即可上传;TikTok 模块独立,默认关闭不影响监控/Shorts。 Co-authored-by: Cursor --- .gitignore | 4 + backend/app/main.py | 107 +++++++------- backend/app/models.py | 8 +- backend/app/tiktok_db.py | 4 +- backend/app/tiktok_pipeline.py | 32 ++-- backend/app/tiktok_schedule.py | 3 +- backend/app/tiktok_session.py | 194 ++++++++++++++++++++++++ backend/app/tiktok_upload.py | 213 ++++++++++----------------- backend/requirements.txt | 4 +- backend/tests/test_tiktok_session.py | 20 +++ frontend/src/app/tiktok/page.tsx | 204 ++++++++++++++----------- scripts/deploy_tiktok_cookie.py | 108 ++++++++++++++ scripts/setup_tiktok_uploader.py | 60 ++++++++ 13 files changed, 663 insertions(+), 298 deletions(-) create mode 100644 backend/app/tiktok_session.py create mode 100644 backend/tests/test_tiktok_session.py create mode 100644 scripts/deploy_tiktok_cookie.py create mode 100644 scripts/setup_tiktok_uploader.py diff --git a/.gitignore b/.gitignore index 4736241..460c501 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,10 @@ backend/data/monitor.db-shm backend/data/monitor.db-wal backend/data/covers/ backend/data/clips/ +backend/data/tiktok_cookies/ + +# TiktokAutoUploader vendor (run scripts/setup_tiktok_uploader.py) +backend/third_party/TiktokAutoUploader/ # PocketBase data & binary pb/pb_data/ diff --git a/backend/app/main.py b/backend/app/main.py index 7c152d5..3038fa1 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -47,6 +47,7 @@ from .models import ( TikTokChannelUpdate, TikTokJobsBulkBody, TikTokOAuthConfig, + TikTokSessionBody, YouTubeVideoUpdate, ) from .monitor import monitor @@ -66,7 +67,7 @@ from .session_auth import ( from .youtube_monitor import yt_monitor from .shorts_pipeline import shorts_pipeline from .tiktok_pipeline import tiktok_pipeline -from . import tiktok_oauth +from . import tiktok_session from .timeutil import stamp_beijing @@ -821,7 +822,8 @@ def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: out[f"has_{k}"] = bool(v.strip()) if v: out[k] = ("***" + v[-4:]) if len(v) > 4 else "***" - out["authorized"] = bool(str(ch.get("refresh_token") or "").strip()) + 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) return out @@ -845,9 +847,10 @@ def _enrich_tiktok_job(job: dict[str, Any] | None) -> dict[str, Any] | None: async def tiktok_status() -> dict[str, Any]: st = await asyncio.to_thread(tiktok_pipeline.status) cfg = await _db(db.get_settings_map) - st["oauth_configured"] = tiktok_oauth.oauth_configured(cfg) - st["oauth_redirect_uri"] = tiktok_oauth.resolve_redirect_uri("https://dylive.nomadro.com") - st["setup"] = tiktok_oauth.setup_checklist(cfg) + setup = tiktok_session.setup_checklist(cfg) + st["auth_mode"] = "cookie" + st["session_ready"] = bool(setup.get("steps") and setup["steps"][-1].get("done")) + st["setup"] = setup st["channels"] = [_public_tiktok_channel(c) for c in (await _db(tiktok_db.list_tiktok_channels))] return st @@ -855,63 +858,45 @@ async def tiktok_status() -> dict[str, Any]: @app.get("/api/tiktok/setup") async def tiktok_setup() -> dict[str, Any]: cfg = await _db(db.get_settings_map) - return tiktok_oauth.setup_checklist(cfg) + return tiktok_session.setup_checklist(cfg) -@app.post("/api/tiktok/oauth/config") -async def tiktok_oauth_config(body: TikTokOAuthConfig) -> dict[str, Any]: - patch: dict[str, Any] = {} - key = str(body.client_key or "").strip() - secret = str(body.client_secret or "").strip() - if key: - patch["tiktok_oauth_client_key"] = key - if secret and not secret.startswith("***"): - patch["tiktok_oauth_client_secret"] = secret - if not patch: - raise HTTPException(400, "请填写 Client Key / Client Secret") - cfg = await _db(db.update_settings_map, patch) - return {"ok": True, "oauth_configured": tiktok_oauth.oauth_configured(cfg)} +@app.post("/api/tiktok/channels/{channel_pk}/session") +async def tiktok_channel_session(channel_pk: str, body: TikTokSessionBody) -> dict[str, Any]: + from . import tiktok_db - -@app.get("/api/tiktok/oauth/start") -async def tiktok_oauth_start(channel_pk: str, request: Request) -> RedirectResponse: + ch = tiktok_db.get_tiktok_channel(channel_pk) + if not ch: + raise HTTPException(404, "账号不存在") try: - url = tiktok_oauth.build_authorize_url(channel_pk=channel_pk, request_base=_request_public_base(request)) + updated = await asyncio.to_thread( + tiktok_session.save_session_from_values, + channel_pk, + sessionid=str(body.sessionid or "").strip(), + dc_id=str(body.dc_id or "useast2a").strip(), + username=str(body.tiktok_username or "").strip(), + ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc - return RedirectResponse(url, status_code=302) + return {"ok": True, "channel": _public_tiktok_channel(updated)} -@app.get("/api/tiktok/oauth/callback/tiktokSac63LUYsqRR1brRHZ2v2hw9x0RjXR9L.txt") -async def tiktok_url_prefix_verify_file() -> FileResponse: - """TikTok URL prefix ownership verification.""" - from pathlib import Path +@app.delete("/api/tiktok/channels/{channel_pk}/session") +async def tiktok_channel_session_delete(channel_pk: str) -> dict[str, Any]: + from . import tiktok_db - path = Path(__file__).resolve().parent.parent / "tiktok_verify" / "tiktokSac63LUYsqRR1brRHZ2v2hw9x0RjXR9L.txt" - if not path.is_file(): - raise HTTPException(404, "verification file missing") - return FileResponse(path, media_type="text/plain") - - -@app.get("/api/tiktok/oauth/callback") -@app.get("/api/tiktok/oauth/callback/") -async def tiktok_oauth_callback( - request: Request, - code: str = "", - state: str = "", - error: str = "", -) -> RedirectResponse: - base = _request_public_base(request) - if error: - return RedirectResponse(f"{base}/tiktok?oauth=error&msg={quote(error)}", status_code=302) - if not code or not state: - return RedirectResponse(f"{base}/tiktok?oauth=error&msg={quote('缺少 code/state')}", status_code=302) - try: - result = await tiktok_oauth.exchange_code(code=code, state=state, request_base=base) - title = quote(str(result.get("username") or "ok")) - return RedirectResponse(f"{base}/tiktok?oauth=ok&title={title}", status_code=302) - except Exception as exc: - return RedirectResponse(f"{base}/tiktok?oauth=error&msg={quote(str(exc)[:180])}", status_code=302) + ch = tiktok_db.get_tiktok_channel(channel_pk) + if not ch: + raise HTTPException(404, "账号不存在") + await asyncio.to_thread(tiktok_session.delete_session_cookies, channel_pk) + updated = await _db( + tiktok_db.update_tiktok_channel, + channel_pk, + oauth_ok=0, + oauth_error="Cookie 已清除", + refresh_token="", + ) + return {"ok": True, "channel": _public_tiktok_channel(updated)} @app.post("/api/tiktok/oauth/probe") @@ -922,14 +907,24 @@ async def tiktok_oauth_probe(channel_pk: str = "") -> dict[str, Any]: ch = tiktok_db.get_tiktok_channel(channel_pk.strip()) if not ch: raise HTTPException(404, "账号不存在") - return await tiktok_oauth.probe_channel_oauth(ch) + return await asyncio.to_thread(tiktok_session.probe_channel_session, ch) results = [] for ch in tiktok_db.list_tiktok_channels(enabled=True): - if str(ch.get("refresh_token") or "").strip(): - results.append(await tiktok_oauth.probe_channel_oauth(ch)) + results.append(await asyncio.to_thread(tiktok_session.probe_channel_session, ch)) return {"checked": len(results), "results": results} +@app.get("/api/tiktok/oauth/callback/tiktokSac63LUYsqRR1brRHZ2v2hw9x0RjXR9L.txt") +async def tiktok_url_prefix_verify_file() -> FileResponse: + """TikTok URL prefix ownership verification (legacy).""" + from pathlib import Path + + path = Path(__file__).resolve().parent.parent / "tiktok_verify" / "tiktokSac63LUYsqRR1brRHZ2v2hw9x0RjXR9L.txt" + if not path.is_file(): + raise HTTPException(404, "verification file missing") + return FileResponse(path, media_type="text/plain") + + @app.post("/api/tiktok/start") async def tiktok_start() -> dict[str, Any]: db.update_settings_map({"tiktok_enabled": True}) diff --git a/backend/app/models.py b/backend/app/models.py index 1eaa5e0..285a49b 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -277,12 +277,18 @@ class TikTokOAuthConfig(BaseModel): client_secret: str = "" +class TikTokSessionBody(BaseModel): + sessionid: str = "" + dc_id: str = "useast2a" + tiktok_username: str = "" + + class TikTokChannelCreate(BaseModel): name: str = "TikTok 账号" enabled: bool = True title_template: str = "{anchor} #fyp" description_template: str = "{anchor}\n{url}" - privacy_level: str = "SELF_ONLY" + privacy_level: str = "PUBLIC_TO_EVERYONE" note: str = "" diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index 3e74049..756ef5f 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -158,12 +158,14 @@ def tiktok_channel_upload_count(channel_pk: str, push_date: str) -> int: def pick_tiktok_channel(push_date: str) -> dict[str, Any] | None: + from . import tiktok_session + channels = list_tiktok_channels(enabled=True) if not channels: return None scored: list[tuple[int, int, float, dict[str, Any]]] = [] for ch in channels: - if not str(ch.get("refresh_token") or "").strip(): + if not tiktok_session.channel_has_session(ch): continue used = tiktok_channel_upload_count(str(ch["id"]), push_date) daily_max = TIKTOK_DAILY_FORCE diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index be2cb79..10ebd32 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -10,7 +10,7 @@ from typing import Any, Optional from . import db from . import tiktok_db -from . import tiktok_oauth +from . import tiktok_session from .shorts_clip import record_clip, resolve_stream_url from .tiktok_schedule import pick_upload_at, schedule_board from .tiktok_upload import upload_tiktok_mp4 @@ -57,7 +57,7 @@ def _enqueue_job( channel: dict[str, Any] | None = None if channel_pk: ch = tiktok_db.get_tiktok_channel(channel_pk) - if ch and ch.get("enabled") and str(ch.get("refresh_token") or "").strip(): + if ch and ch.get("enabled") and tiktok_session.channel_has_session(ch): used = tiktok_db.tiktok_channel_upload_count(channel_pk, day) if used < db.TIKTOK_DAILY_FORCE: channel = ch @@ -128,7 +128,7 @@ class TikTokPipeline: oauth_issues = [] for ch in tiktok_db.list_tiktok_channels(enabled=True): ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1) - if ok_flag == 0 or not str(ch.get("refresh_token") or "").strip(): + if ok_flag == 0 or not tiktok_session.channel_has_session(ch): oauth_issues.append( { "id": ch.get("id"), @@ -191,12 +191,11 @@ class TikTokPipeline: n = try_sample_live_rooms(cfg) if n: self.sampled += n - oauth_interval = max(600.0, float(cfg.get("tiktok_oauth_check_interval_sec") or 3600)) - if (time.time() - self._last_oauth_check_at) >= oauth_interval: + session_interval = max(600.0, float(cfg.get("tiktok_oauth_check_interval_sec") or 3600)) + if (time.time() - self._last_oauth_check_at) >= session_interval: self._last_oauth_check_at = time.time() for ch in tiktok_db.list_tiktok_channels(enabled=True): - if str(ch.get("refresh_token") or "").strip(): - asyncio.create_task(tiktok_oauth.probe_channel_oauth(ch, cfg)) + asyncio.create_task(asyncio.to_thread(tiktok_session.probe_channel_session, ch)) retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300)) if cfg.get("tiktok_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval: self._last_auto_retry_at = time.time() @@ -315,9 +314,8 @@ class TikTokPipeline: channel = tiktok_db.get_tiktok_channel(str(fresh.get("channel_pk") or "")) if not channel: raise ValueError("账号不存在") - creds = tiktok_oauth.channel_oauth_creds(channel, cfg) - if not creds["refresh_token"]: - tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未授权") + if not tiktok_session.channel_has_session(channel): + tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未配置 Cookie") return title_tpl = str(channel.get("title_template") or "{anchor} #fyp") desc_tpl = str(channel.get("description_template") or "") @@ -331,12 +329,8 @@ class TikTokPipeline: file_path=clip, title=title, description=desc, - privacy_level=str(channel.get("privacy_level") or "SELF_ONLY"), - client_key=creds["client_key"], - client_secret=creds["client_secret"], - refresh_token=creds["refresh_token"], - access_token=creds["access_token"], - token_expires_at=float(creds.get("token_expires_at") or 0), + privacy_level=str(channel.get("privacy_level") or "PUBLIC_TO_EVERYONE"), + channel_pk=str(channel["id"]), ) if not tiktok_db.finalize_tiktok_upload( jid, @@ -346,9 +340,9 @@ class TikTokPipeline: return tiktok_db.update_tiktok_channel( str(channel["id"]), - access_token=str(result.get("access_token") or creds["access_token"]), - refresh_token=str(result.get("refresh_token") or creds["refresh_token"]), - token_expires_at=time.time() + 82800, + oauth_ok=1, + oauth_checked_at=time.time(), + oauth_error="", ) if cfg.get("tiktok_delete_clip_after_upload", True): try: diff --git a/backend/app/tiktok_schedule.py b/backend/app/tiktok_schedule.py index db25396..de98cf3 100644 --- a/backend/app/tiktok_schedule.py +++ b/backend/app/tiktok_schedule.py @@ -9,6 +9,7 @@ from typing import Any from . import db from . import tiktok_db +from . import tiktok_session from .db import TIKTOK_DAILY_FORCE from .timeutil import beijing_day_bounds, beijing_from_ts, push_date_from_ts @@ -131,7 +132,7 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: "name": c.get("name"), "tiktok_username": c.get("tiktok_username"), "enabled": bool(c.get("enabled")), - "authorized": bool(str(c.get("refresh_token") or "").strip()), + "authorized": tiktok_session.channel_has_session(c), "daily_min": TIKTOK_DAILY_FORCE, "daily_max": TIKTOK_DAILY_FORCE, "gap": gap, diff --git a/backend/app/tiktok_session.py b/backend/app/tiktok_session.py new file mode 100644 index 0000000..479ab7f --- /dev/null +++ b/backend/app/tiktok_session.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +"""TikTok cookie session — TiktokAutoUploader style, no developer OAuth.""" +from __future__ import annotations + +import os +import pickle +import sys +import time +from pathlib import Path +from typing import Any + +from . import db +from . import tiktok_db + +_VENDOR_ROOT = Path(__file__).resolve().parent.parent / "third_party" / "TiktokAutoUploader" +if str(_VENDOR_ROOT) not in sys.path: + sys.path.insert(0, str(_VENDOR_ROOT)) + +DEFAULT_DC = "useast2a" +REQUIRED_COOKIES = ("sessionid", "tt-target-idc") + + +def cookies_dir() -> Path: + raw = str(db.get_settings_map().get("tiktok_cookies_dir") or "").strip() + if raw: + p = Path(raw) + else: + p = Path(__file__).resolve().parent.parent / "data" / "tiktok_cookies" + p.mkdir(parents=True, exist_ok=True) + return p + + +def session_filename(channel_pk: str) -> str: + return f"tiktok_session-{channel_pk}" + + +def session_cookie_path(channel_pk: str) -> Path: + return cookies_dir() / f"{session_filename(channel_pk)}.cookie" + + +def _normalize_cookie(raw: dict[str, Any]) -> dict[str, Any]: + c = dict(raw) + if c.get("sameSite") == "None": + c["sameSite"] = "Strict" + return c + + +def load_session_cookies(channel_pk: str) -> list[dict[str, Any]]: + path = session_cookie_path(channel_pk) + if not path.is_file(): + return [] + try: + data = pickle.load(path.open("rb")) + except Exception: + return [] + if not isinstance(data, list): + return [] + out: list[dict[str, Any]] = [] + for item in data: + if isinstance(item, dict) and item.get("name"): + out.append(_normalize_cookie(item)) + return out + + +def save_session_cookies(channel_pk: str, cookies: list[dict[str, Any]]) -> None: + path = session_cookie_path(channel_pk) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("wb") as f: + pickle.dump([_normalize_cookie(c) for c in cookies if c.get("name")], f) + + +def delete_session_cookies(channel_pk: str) -> None: + path = session_cookie_path(channel_pk) + if path.is_file(): + path.unlink() + + +def save_session_from_values( + channel_pk: str, + *, + sessionid: str, + dc_id: str = DEFAULT_DC, + username: str = "", +) -> dict[str, Any]: + sid = str(sessionid or "").strip() + if not sid: + raise ValueError("sessionid 不能为空") + dc = str(dc_id or DEFAULT_DC).strip() or DEFAULT_DC + cookies = [ + {"name": "sessionid", "value": sid, "domain": ".tiktok.com", "path": "/"}, + {"name": "tt-target-idc", "value": dc, "domain": ".tiktok.com", "path": "/"}, + ] + save_session_cookies(channel_pk, cookies) + patch: dict[str, Any] = { + "oauth_ok": 1, + "oauth_checked_at": time.time(), + "oauth_error": "", + "refresh_token": "cookie", + } + if username.strip(): + patch["tiktok_username"] = username.strip() + return tiktok_db.update_tiktok_channel(channel_pk, **patch) or {} + + +def channel_has_session(channel: dict[str, Any] | None) -> bool: + if not channel: + return False + pk = str(channel.get("id") or "") + if not pk: + return False + cookies = load_session_cookies(pk) + names = {str(c.get("name") or "") for c in cookies} + return "sessionid" in names and bool(next((c.get("value") for c in cookies if c.get("name") == "sessionid"), "")) + + +def probe_channel_session(channel: dict[str, Any] | None) -> dict[str, Any]: + ch = channel or {} + pk = str(ch.get("id") or "") + if not pk: + return {"ok": False, "error": "账号不存在"} + if channel_has_session(ch): + tiktok_db.update_tiktok_channel( + pk, + oauth_ok=1, + oauth_checked_at=time.time(), + oauth_error="", + refresh_token="cookie", + ) + return {"ok": True, "channel_pk": pk, "mode": "cookie"} + tiktok_db.update_tiktok_channel( + pk, + oauth_ok=0, + oauth_checked_at=time.time(), + oauth_error="未配置 Cookie 会话", + refresh_token="", + ) + return {"ok": False, "channel_pk": pk, "error": "未配置 Cookie 会话"} + + +def setup_checklist(cfg: dict[str, Any] | None = None) -> dict[str, Any]: + channels = tiktok_db.list_tiktok_channels() + ready = [c for c in channels if channel_has_session(c)] + vendor_ok = _VENDOR_ROOT.is_dir() and (_VENDOR_ROOT / "tiktok_uploader" / "tiktok.py").is_file() + sig_js = _VENDOR_ROOT / "tiktok_uploader" / "tiktok-signature" / "browser.js" + node_ok = bool(os.environ.get("NODE_PATH") or _which("node")) + return { + "mode": "cookie", + "vendor_ready": vendor_ok, + "signature_ready": sig_js.is_file(), + "node_available": node_ok, + "cookies_dir": str(cookies_dir()), + "steps": [ + { + "id": "browser_login", + "title": "浏览器登录 tiktok.com,导出 sessionid(及 tt-target-idc)", + "url": "https://www.tiktok.com", + "done": len(ready) > 0, + }, + { + "id": "paste_cookie", + "title": "在 TikTok 页为每个账号粘贴 Cookie / sessionid", + "done": len(ready) > 0, + }, + { + "id": "account", + "title": "添加 TikTok 账号并完成 Cookie 授权", + "done": len(channels) > 0 and len(ready) == len(channels), + }, + ], + "note": ( + "使用 TiktokAutoUploader Cookie 方案,无需 TikTok 开发者应用。" + " sessionid 等同账号密码,请勿泄露;约 30 天过期需重新粘贴。" + ), + "note_unaudited": "", + } + + +def _which(name: str) -> str | None: + from shutil import which + + return which(name) + + +def configure_vendor_paths() -> None: + """Point vendored Config at our cookies directory.""" + os.environ.setdefault("TIKTOK_VENDOR_ROOT", str(_VENDOR_ROOT)) + try: + from tiktok_uploader.Config import Config + + cfg = Config.get() + cfg._insert_option("COOKIES_DIR", str(cookies_dir())) + cfg._insert_option("VIDEOS_DIR", str(cookies_dir())) + except Exception: + pass diff --git a/backend/app/tiktok_upload.py b/backend/app/tiktok_upload.py index 14b30a3..56282fc 100644 --- a/backend/app/tiktok_upload.py +++ b/backend/app/tiktok_upload.py @@ -1,51 +1,78 @@ # -*- coding: utf-8 -*- -"""TikTok video upload via Content Posting API (Direct Post).""" +"""TikTok upload via TiktokAutoUploader (cookie session + requests).""" from __future__ import annotations import asyncio +import sys +import uuid from pathlib import Path from typing import Any -import httpx +from . import tiktok_session -from . import tiktok_oauth +_VENDOR_ROOT = Path(__file__).resolve().parent.parent / "third_party" / "TiktokAutoUploader" +if str(_VENDOR_ROOT) not in sys.path: + sys.path.insert(0, str(_VENDOR_ROOT)) -async def _ensure_access_token( +def _privacy_to_visibility(privacy_level: str) -> int: + pl = str(privacy_level or "").strip().upper() + if pl in {"SELF_ONLY", "PRIVATE"}: + return 1 + return 0 + + +def _upload_sync( *, - client_key: str, - client_secret: str, - refresh_token: str, - access_token: str = "", - token_expires_at: float = 0, -) -> tuple[str, str]: - import time + channel_pk: str, + file_path: str, + title: str, + privacy_level: str = "PUBLIC_TO_EVERYONE", + allow_comment: int = 1, + allow_duet: int = 0, + allow_stitch: int = 0, + proxy: str | None = None, +) -> dict[str, Any]: + path = Path(file_path) + if not path.is_file(): + raise ValueError("成片文件不存在") + cookies = tiktok_session.load_session_cookies(channel_pk) + if not cookies: + raise ValueError("账号未配置 Cookie 会话,请先粘贴 sessionid") + sessionid = next((c.get("value") for c in cookies if c.get("name") == "sessionid"), "") + if not sessionid: + raise ValueError("Cookie 缺少 sessionid") - if access_token and token_expires_at > time.time() + 120: - return access_token, refresh_token - tok = await tiktok_oauth.refresh_access_token( - client_key=client_key, - client_secret=client_secret, - refresh_token=refresh_token, + tiktok_session.configure_vendor_paths() + from tiktok_uploader import tiktok as ttuploader + + # Ensure cookie file exists where upstream loader expects it. + from tiktok_uploader.cookies import save_cookies_to_file + + save_cookies_to_file(cookies, tiktok_session.session_filename(channel_pk), str(tiktok_session.cookies_dir())) + + session_user = channel_pk + visibility = _privacy_to_visibility(privacy_level) + ok = ttuploader.upload_video( + session_user, + str(path.resolve()), + (title or "video")[:2200], + schedule_time=0, + allow_comment=int(allow_comment), + allow_duet=int(allow_duet), + allow_stitch=int(allow_stitch), + visibility_type=visibility, + proxy=proxy or None, ) - return tok["access_token"], tok.get("refresh_token") or refresh_token - - -async def query_creator_info(access_token: str) -> dict[str, Any]: - async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client: - resp = await client.post( - "https://open.tiktokapis.com/v2/post/publish/creator_info/query/", - headers={ - "Authorization": f"Bearer {access_token}", - "Content-Type": "application/json; charset=UTF-8", - }, - json={}, - ) - data = resp.json() if resp.content else {} - if resp.status_code >= 400: - err = (data.get("error") or {}).get("message") or data or resp.text - raise ValueError(f"查询创作者信息失败: {err}") - return (data.get("data") or {}) + if not ok: + raise ValueError("TikTok 上传失败,请检查 Cookie 是否过期或 Node.js 是否可用") + return { + "ok": True, + "publish_id": f"cookie-{uuid.uuid4().hex[:12]}", + "video_id": "", + "mode": "cookie", + "privacy_level": privacy_level, + } async def upload_tiktok_mp4( @@ -53,7 +80,8 @@ async def upload_tiktok_mp4( file_path: str, title: str, description: str = "", - privacy_level: str = "SELF_ONLY", + privacy_level: str = "PUBLIC_TO_EVERYONE", + channel_pk: str = "", client_key: str = "", client_secret: str = "", refresh_token: str = "", @@ -62,101 +90,22 @@ async def upload_tiktok_mp4( disable_duet: bool = False, disable_comment: bool = False, disable_stitch: bool = False, + proxy: str | None = None, ) -> dict[str, Any]: - path = Path(file_path) - if not path.is_file(): - raise ValueError("成片文件不存在") - access, new_refresh = await _ensure_access_token( - client_key=client_key, - client_secret=client_secret, - refresh_token=refresh_token, - access_token=access_token, - token_expires_at=token_expires_at, + _ = (description, client_key, client_secret, refresh_token, access_token, token_expires_at) + if not channel_pk: + raise ValueError("缺少 channel_pk") + caption = (title or "").strip() + if description.strip() and description.strip() not in caption: + caption = f"{caption}\n{description.strip()}"[:2200] + return await asyncio.to_thread( + _upload_sync, + channel_pk=channel_pk, + file_path=file_path, + title=caption, + privacy_level=privacy_level, + allow_comment=0 if disable_comment else 1, + allow_duet=0 if disable_duet else 1, + allow_stitch=0 if disable_stitch else 1, + proxy=proxy, ) - creator = await query_creator_info(access) - allowed = creator.get("privacy_level_options") or ["SELF_ONLY"] - pl = privacy_level if privacy_level in allowed else (allowed[0] if allowed else "SELF_ONLY") - - try: - size = path.stat().st_size - raw = path.read_bytes() - except FileNotFoundError as exc: - raise ValueError("成片文件不存在") from exc - - chunk_size = min(size, 10 * 1024 * 1024) or size - chunk_count = max(1, (size + chunk_size - 1) // chunk_size) - - init_body = { - "post_info": { - "title": (title or "video")[:150], - "description": (description or "")[:2200], - "privacy_level": pl, - "disable_duet": disable_duet, - "disable_comment": disable_comment, - "disable_stitch": disable_stitch, - "video_cover_timestamp_ms": 1000, - }, - "source_info": { - "source": "FILE_UPLOAD", - "video_size": size, - "chunk_size": chunk_size, - "total_chunk_count": chunk_count, - }, - } - - async with httpx.AsyncClient(timeout=300.0, trust_env=False) as client: - init = await client.post( - "https://open.tiktokapis.com/v2/post/publish/video/init/", - headers={ - "Authorization": f"Bearer {access}", - "Content-Type": "application/json; charset=UTF-8", - }, - json=init_body, - ) - init_data = init.json() if init.content else {} - if init.status_code >= 400: - err = (init_data.get("error") or {}).get("message") or init_data or init.text - raise ValueError(f"初始化上传失败: {str(err)[:400]}") - upload_url = (init_data.get("data") or {}).get("upload_url") or "" - publish_id = (init_data.get("data") or {}).get("publish_id") or "" - if not upload_url or not publish_id: - raise ValueError(f"初始化上传失败: 缺少 upload_url/publish_id") - - headers = { - "Content-Type": "video/mp4", - "Content-Length": str(size), - "Content-Range": f"bytes 0-{size - 1}/{size}", - } - put = await client.put(upload_url, headers=headers, content=raw) - if put.status_code >= 400: - raise ValueError(f"上传视频失败: {put.text[:400]}") - - # Poll publish status - for _ in range(60): - st_resp = await client.post( - "https://open.tiktokapis.com/v2/post/publish/status/fetch/", - headers={ - "Authorization": f"Bearer {access}", - "Content-Type": "application/json; charset=UTF-8", - }, - json={"publish_id": publish_id}, - ) - st_data = st_resp.json() if st_resp.content else {} - status = str((st_data.get("data") or {}).get("status") or "") - if status in {"PUBLISH_COMPLETE", "SEND_TO_USER_INBOX"}: - break - if status in {"FAILED"}: - fail = (st_data.get("data") or {}).get("fail_reason") or status - raise ValueError(f"TikTok 发布失败: {fail}") - await asyncio.sleep(3) - else: - raise ValueError("TikTok 发布超时,请稍后在 TikTok 查看") - - return { - "ok": True, - "publish_id": publish_id, - "video_id": publish_id, - "access_token": access, - "refresh_token": new_refresh, - "privacy_level": pl, - } diff --git a/backend/requirements.txt b/backend/requirements.txt index b6e6d3c..1cd5705 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -7,5 +7,7 @@ pydantic-settings==2.7.0 python-multipart==0.0.20 aiofiles==24.1.0 boto3==1.35.99 -pytest==8.3.4 +fake-useragent>=1.4 +requests-auth-aws-sigv4>=0.7 +requests>=2.31 diff --git a/backend/tests/test_tiktok_session.py b/backend/tests/test_tiktok_session.py new file mode 100644 index 0000000..ebabfac --- /dev/null +++ b/backend/tests/test_tiktok_session.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +from app import tiktok_db +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") + 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 + + +def test_channel_has_session_false_when_missing(temp_db, tmp_path, monkeypatch): + monkeypatch.setattr(tiktok_session, "cookies_dir", lambda: tmp_path) + ch = tiktok_db.create_tiktok_channel(name="tt2") + assert not tiktok_session.channel_has_session(ch) diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index 199d6eb..113dc80 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -88,17 +88,17 @@ export default function TikTokPage() { const [jobs, setJobs] = useState([]); const [jobTotal, setJobTotal] = useState(0); - const [clientKey, setClientKey] = useState(""); - const [clientSecret, setClientSecret] = useState(""); - const [savingCreds, setSavingCreds] = useState(false); - - const [showForm, setShowForm] = useState(false); - const [editId, setEditId] = useState(""); - const [formName, setFormName] = useState("TikTok 账号"); - const [formPrivacy, setFormPrivacy] = useState("SELF_ONLY"); + const [formPrivacy, setFormPrivacy] = useState("PUBLIC_TO_EVERYONE"); const [formTitle, setFormTitle] = useState("{anchor} #fyp"); const [formDesc, setFormDesc] = useState("{anchor}\n{url}"); + const [sessionChannelId, setSessionChannelId] = useState(""); + const [sessionId, setSessionId] = useState(""); + const [sessionDcId, setSessionDcId] = useState("useast2a"); + const [sessionUsername, setSessionUsername] = useState(""); + const [savingSession, setSavingSession] = useState(false); + const [showSessionForm, setShowSessionForm] = useState(false); + const [uploadingId, setUploadingId] = useState(""); const load = useCallback(async () => { @@ -133,26 +133,14 @@ export default function TikTokPage() { return () => ro.disconnect(); }); - useEffect(() => { - const params = new URLSearchParams(window.location.search); - const oauth = params.get("oauth"); - if (oauth === "ok") { - toast.push(`TikTok 授权成功:${params.get("title") || ""}`, "ok"); - window.history.replaceState({}, "", "/tiktok"); - } else if (oauth === "error") { - toast.push(`授权失败:${params.get("msg") || ""}`, "err"); - window.history.replaceState({}, "", "/tiktok"); - } - }, [toast]); - const setup = status?.setup; const setupDone = setup?.steps?.every((s: SetupStep) => s.done); const board = status?.board || {}; const boardChannels: BoardChannel[] = board.channels || []; const upcoming: Upcoming[] = board.upcoming || []; const beijingWindow = board.beijing_window || ""; - const oauthConfigured = status?.oauth_configured; - const redirectUri = status?.oauth_redirect_uri || ""; + const cookiesDir = status?.setup?.cookies_dir || ""; + const authMode = status?.auth_mode || "cookie"; const togglePipeline = async () => { const on = status?.enabled; @@ -161,24 +149,33 @@ export default function TikTokPage() { void load(); }; - const saveCredentials = async () => { - if (!clientKey.trim()) { - toast.push("请填写 Client Key", "err"); + const saveSession = async () => { + if (!sessionChannelId) { + toast.push("请选择账号", "err"); return; } - setSavingCreds(true); + if (!sessionId.trim()) { + toast.push("请填写 sessionid", "err"); + return; + } + setSavingSession(true); try { - await fetchJson("/api/tiktok/oauth/config", { + await fetchJson(`/api/tiktok/channels/${sessionChannelId}/session`, { method: "POST", - body: JSON.stringify({ client_key: clientKey.trim(), client_secret: clientSecret.trim() }), + body: JSON.stringify({ + sessionid: sessionId.trim(), + dc_id: sessionDcId.trim() || "useast2a", + tiktok_username: sessionUsername.trim(), + }), }); - toast.push("凭证已保存", "ok"); - setClientSecret(""); + toast.push("Cookie 会话已保存", "ok"); + setShowSessionForm(false); + setSessionId(""); void load(); } catch (e: any) { toast.push(e?.message || "保存失败", "err"); } finally { - setSavingCreds(false); + setSavingSession(false); } }; @@ -192,7 +189,7 @@ export default function TikTokPage() { description_template: formDesc, }), }); - toast.push("账号已添加,请点击「授权」", "ok"); + toast.push("账号已添加,请粘贴 Cookie", "ok"); setShowForm(false); void load(); }; @@ -227,8 +224,12 @@ export default function TikTokPage() { void load(); }; - const authorize = (id: string) => { - window.location.href = `/api/tiktok/oauth/start?channel_pk=${encodeURIComponent(id)}`; + const openSessionForm = (id: string, ch?: Channel) => { + setSessionChannelId(id); + setSessionId(""); + setSessionDcId("useast2a"); + setSessionUsername(ch?.tiktok_username || ""); + setShowSessionForm(true); }; const sampleNow = async () => { @@ -259,7 +260,7 @@ export default function TikTokPage() { const startEdit = (ch: Channel) => { setEditId(ch.id); setFormName(ch.name || "TikTok 账号"); - setFormPrivacy(ch.privacy_level || "SELF_ONLY"); + setFormPrivacy(ch.privacy_level || "PUBLIC_TO_EVERYONE"); setFormTitle(ch.title_template || "{anchor} #fyp"); setFormDesc(ch.description_template || "{anchor}\n{url}"); setShowForm(true); @@ -313,7 +314,9 @@ export default function TikTokPage() { TikTok 自动上传 -

独立模块 · 不影响 Shorts · 抖音直播录屏 → TikTok

+

+ Cookie 上传 · TiktokAutoUploader · 抖音直播录屏 → TikTok +

-
- )} - - {oauthConfigured && channels.length === 0 && ( + {channels.length === 0 && ( )} - {setup?.note_unaudited && ( -

⚠️ {setup.note_unaudited}

+ {setup?.note && ( +

⚠️ {setup.note}

)} + {cookiesDir ? ( +

Cookie 存储:{cookiesDir}

+ ) : null} )} @@ -469,7 +440,7 @@ export default function TikTokPage() { )} {/* Control bar */} - {oauthConfigured && ( + {channels.length >= 0 && (
)} @@ -514,9 +485,9 @@ export default function TikTokPage() { onChange={(e) => setFormPrivacy(e.target.value)} className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm" > - + + -