账号粘贴 sessionid 即可上传;TikTok 模块独立,默认关闭不影响监控/Shorts。 Co-authored-by: Cursor <cursoragent@cursor.com>
195 lines
6.0 KiB
Python
195 lines
6.0 KiB
Python
# -*- 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
|