TikTok: Cookie 上传(TiktokAutoUploader),替代开发者 OAuth
账号粘贴 sessionid 即可上传;TikTok 模块独立,默认关闭不影响监控/Shorts。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
01c6bf4507
commit
d8fdeaa71c
4
.gitignore
vendored
4
.gitignore
vendored
@ -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/
|
||||
|
||||
@ -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})
|
||||
|
||||
@ -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 = ""
|
||||
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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,
|
||||
|
||||
194
backend/app/tiktok_session.py
Normal file
194
backend/app/tiktok_session.py
Normal file
@ -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
|
||||
@ -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,
|
||||
}
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
20
backend/tests/test_tiktok_session.py
Normal file
20
backend/tests/test_tiktok_session.py
Normal file
@ -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)
|
||||
@ -88,17 +88,17 @@ export default function TikTokPage() {
|
||||
const [jobs, setJobs] = useState<Job[]>([]);
|
||||
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() {
|
||||
<Music2 className="h-6 w-6 text-pink-400" />
|
||||
TikTok 自动上传
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-slate-500">独立模块 · 不影响 Shorts · 抖音直播录屏 → TikTok</p>
|
||||
<p className="mt-1 text-sm text-slate-500">
|
||||
Cookie 上传 · TiktokAutoUploader · 抖音直播录屏 → TikTok
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
@ -352,8 +355,11 @@ export default function TikTokPage() {
|
||||
{/* Setup wizard */}
|
||||
{!setupDone && (
|
||||
<section className="mb-6 rounded-2xl border border-pink-500/25 bg-gradient-to-br from-pink-500/10 to-transparent p-5">
|
||||
<h2 className="mb-1 text-base font-medium text-slate-100">🚀 三步完成配置(约 5 分钟)</h2>
|
||||
<p className="mb-4 text-sm text-slate-400">按顺序完成下面步骤,即可自动上传。未审核应用只能发「仅自己可见」。</p>
|
||||
<h2 className="mb-1 text-base font-medium text-slate-100">🚀 Cookie 会话配置(无需开发者 API)</h2>
|
||||
<p className="mb-4 text-sm text-slate-400">
|
||||
浏览器登录 tiktok.com 后导出 <code className="text-pink-300">sessionid</code>,粘贴到账号即可上传。
|
||||
模式:{authMode}
|
||||
</p>
|
||||
|
||||
<div className="mb-5 space-y-3">
|
||||
{(setup?.steps || []).map((step: SetupStep, i: number) => (
|
||||
@ -382,45 +388,7 @@ export default function TikTokPage() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!oauthConfigured && (
|
||||
<div className="rounded-xl border border-white/10 bg-black/30 p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-slate-100">填写 TikTok 应用凭证</h3>
|
||||
<p className="mb-3 text-xs text-slate-500">
|
||||
Redirect URI 填:<code className="text-pink-300">{redirectUri}</code>
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="block text-xs text-slate-400">
|
||||
Client Key
|
||||
<input
|
||||
value={clientKey}
|
||||
onChange={(e) => setClientKey(e.target.value)}
|
||||
placeholder="从 TikTok 开发者后台复制"
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-slate-400">
|
||||
Client Secret
|
||||
<input
|
||||
type="password"
|
||||
value={clientSecret}
|
||||
onChange={(e) => setClientSecret(e.target.value)}
|
||||
placeholder="从 TikTok 开发者后台复制"
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={savingCreds}
|
||||
onClick={() => void saveCredentials()}
|
||||
className="mt-3 rounded-lg bg-pink-500 px-4 py-2 text-sm font-medium text-white hover:bg-pink-400 disabled:opacity-50"
|
||||
>
|
||||
{savingCreds ? "保存中…" : "保存凭证"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{oauthConfigured && channels.length === 0 && (
|
||||
{channels.length === 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
@ -434,9 +402,12 @@ export default function TikTokPage() {
|
||||
</button>
|
||||
)}
|
||||
|
||||
{setup?.note_unaudited && (
|
||||
<p className="mt-4 text-xs text-amber-300/90">⚠️ {setup.note_unaudited}</p>
|
||||
{setup?.note && (
|
||||
<p className="mt-4 text-xs text-amber-300/90">⚠️ {setup.note}</p>
|
||||
)}
|
||||
{cookiesDir ? (
|
||||
<p className="mt-2 text-[11px] text-slate-500">Cookie 存储:{cookiesDir}</p>
|
||||
) : null}
|
||||
</section>
|
||||
)}
|
||||
|
||||
@ -469,7 +440,7 @@ export default function TikTokPage() {
|
||||
)}
|
||||
|
||||
{/* Control bar */}
|
||||
{oauthConfigured && (
|
||||
{channels.length >= 0 && (
|
||||
<div className="mb-6 flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
@ -484,12 +455,12 @@ export default function TikTokPage() {
|
||||
新增账号
|
||||
</button>
|
||||
<Link
|
||||
href="https://developers.tiktok.com/apps"
|
||||
href="https://github.com/makiisthenes/TiktokAutoUploader"
|
||||
target="_blank"
|
||||
className="flex items-center gap-1 rounded-xl border border-white/10 px-3 py-2 text-xs text-slate-400 hover:text-slate-200"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
开发者后台
|
||||
TiktokAutoUploader
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
@ -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"
|
||||
>
|
||||
<option value="SELF_ONLY">仅自己可见(未审核应用)</option>
|
||||
<option value="PUBLIC_TO_EVERYONE">公开</option>
|
||||
<option value="SELF_ONLY">仅自己可见</option>
|
||||
<option value="MUTUAL_FOLLOW_FRIENDS">互关好友</option>
|
||||
<option value="PUBLIC_TO_EVERYONE">公开(需审核通过)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400 sm:col-span-2">
|
||||
@ -547,6 +518,65 @@ export default function TikTokPage() {
|
||||
</section>
|
||||
)}
|
||||
|
||||
{showSessionForm && (
|
||||
<section className="mb-6 rounded-2xl border border-pink-500/30 bg-black/30 p-4">
|
||||
<h3 className="mb-2 text-sm font-medium text-slate-100">粘贴 TikTok Cookie</h3>
|
||||
<p className="mb-3 text-xs leading-relaxed text-slate-500">
|
||||
在浏览器登录 tiktok.com → F12 → Application → Cookies → 复制{" "}
|
||||
<code className="text-pink-300">sessionid</code> 和{" "}
|
||||
<code className="text-pink-300">tt-target-idc</code>(后者默认 useast2a)。
|
||||
sessionid 等同密码,请勿泄露。
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="text-xs text-slate-400 sm:col-span-2">
|
||||
sessionid
|
||||
<input
|
||||
type="password"
|
||||
value={sessionId}
|
||||
onChange={(e) => setSessionId(e.target.value)}
|
||||
placeholder="必填"
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
tt-target-idc
|
||||
<input
|
||||
value={sessionDcId}
|
||||
onChange={(e) => setSessionDcId(e.target.value)}
|
||||
placeholder="useast2a"
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
TikTok 用户名(可选)
|
||||
<input
|
||||
value={sessionUsername}
|
||||
onChange={(e) => setSessionUsername(e.target.value)}
|
||||
placeholder="@handle"
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={savingSession}
|
||||
onClick={() => void saveSession()}
|
||||
className="rounded-lg bg-pink-500 px-4 py-2 text-sm text-white hover:bg-pink-400 disabled:opacity-50"
|
||||
>
|
||||
{savingSession ? "保存中…" : "保存 Cookie"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSessionForm(false)}
|
||||
className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-400"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Two-column board */}
|
||||
{channels.length > 0 && (
|
||||
<div className="mb-6 grid gap-4 xl:grid-cols-[1.4fr_1fr] xl:items-start">
|
||||
@ -572,7 +602,7 @@ export default function TikTokPage() {
|
||||
<div className="truncate text-[10px] text-slate-500">{ch.tiktok_username || "—"}</div>
|
||||
</div>
|
||||
<span className={`text-[10px] ${full?.authorized ? "text-teal-300" : "text-rose-300"}`}>
|
||||
{full?.authorized ? "已授权" : "未授权"}
|
||||
{full?.authorized ? "Cookie 就绪" : "未配置"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-white/10">
|
||||
@ -589,11 +619,11 @@ export default function TikTokPage() {
|
||||
<div className="mt-2 flex flex-wrap gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => authorize(ch.id)}
|
||||
onClick={() => openSessionForm(ch.id, full)}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-pink-500/15 px-2 py-1 text-[11px] text-pink-200"
|
||||
>
|
||||
<KeyRound className="h-3 w-3" />
|
||||
授权
|
||||
{full?.authorized ? "更新 Cookie" : "粘贴 Cookie"}
|
||||
</button>
|
||||
{full && (
|
||||
<button
|
||||
|
||||
108
scripts/deploy_tiktok_cookie.py
Normal file
108
scripts/deploy_tiktok_cookie.py
Normal file
@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Safe deploy: TikTok Cookie upload test — code only, never touch monitor.db."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOST = "107.173.30.245"
|
||||
USER = "root"
|
||||
PASSWORD = "Xiao4669805"
|
||||
REPO = "/opt/douyinWEB"
|
||||
VENV = f"{REPO}/backend/.venv/bin/python"
|
||||
PIP = f"{REPO}/backend/.venv/bin/pip"
|
||||
|
||||
CODE_CONFLICT_FILES = [
|
||||
"backend/app/main.py",
|
||||
"backend/app/models.py",
|
||||
"backend/app/tiktok_db.py",
|
||||
"backend/app/tiktok_pipeline.py",
|
||||
"backend/app/tiktok_schedule.py",
|
||||
"backend/app/tiktok_upload.py",
|
||||
"backend/requirements.txt",
|
||||
"frontend/src/app/tiktok/page.tsx",
|
||||
".gitignore",
|
||||
]
|
||||
|
||||
|
||||
def run(c, cmd: str, timeout: int = 300) -> tuple[str, str]:
|
||||
print("$", cmd[:200])
|
||||
_s, out, err = c.exec_command(cmd, timeout=timeout)
|
||||
o = out.read().decode("utf-8", "replace").strip()
|
||||
e = err.read().decode("utf-8", "replace").strip()
|
||||
if o:
|
||||
print(o)
|
||||
if e and "warning" not in e.lower():
|
||||
print("ERR:", e[:500])
|
||||
return o, e
|
||||
|
||||
|
||||
def main() -> int:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
|
||||
|
||||
print("=== pre-check (business health) ===")
|
||||
run(c, "systemctl is-active douyinweb-api douyinweb-web douyinweb-pb")
|
||||
run(c, f"ls -lh {REPO}/backend/data/monitor.db")
|
||||
run(
|
||||
c,
|
||||
f"{VENV} -c \"import sqlite3; c=sqlite3.connect('{REPO}/backend/data/monitor.db'); "
|
||||
"print('shorts_channels', c.execute('SELECT COUNT(*) FROM shorts_channels').fetchone()[0]); "
|
||||
"print('rooms', c.execute('SELECT COUNT(*) FROM rooms').fetchone()[0])\"",
|
||||
)
|
||||
|
||||
print("\n=== git pull (stash code conflicts only, not db) ===")
|
||||
run(c, f"cd {REPO} && git status --short | head -15")
|
||||
files = " ".join(CODE_CONFLICT_FILES)
|
||||
run(c, f"cd {REPO} && git stash push -m 'pre-tiktok-cookie-deploy' -- {files} 2>&1 || true")
|
||||
o, e = run(c, f"cd {REPO} && git pull origin dev 2>&1", timeout=90)
|
||||
if "error:" in (o + e).lower() and "already up to date" not in (o + e).lower():
|
||||
print("ABORT: git pull failed — not restarting services")
|
||||
c.close()
|
||||
return 1
|
||||
run(c, f"cd {REPO} && git log --oneline -1")
|
||||
|
||||
print("\n=== tiktok vendor + python deps ===")
|
||||
run(c, f"cd {REPO} && python3 scripts/setup_tiktok_uploader.py", timeout=600)
|
||||
run(c, f"{PIP} install -r {REPO}/backend/requirements.txt -q", timeout=180)
|
||||
|
||||
print("\n=== restart API ===")
|
||||
c.exec_command("systemctl restart douyinweb-api", timeout=5)
|
||||
time.sleep(12)
|
||||
run(c, "systemctl is-active douyinweb-api")
|
||||
|
||||
print("\n=== verify core business APIs ===")
|
||||
run(c, "curl -sS http://127.0.0.1:8014/api/health")
|
||||
run(c, "curl -sS http://127.0.0.1:8014/api/monitor/status | head -c 400")
|
||||
run(c, "curl -sS http://127.0.0.1:8014/api/shorts/status | head -c 400")
|
||||
run(c, "curl -sS http://127.0.0.1:8014/api/tiktok/setup | head -c 500")
|
||||
|
||||
print("\n=== confirm tiktok still disabled ===")
|
||||
run(
|
||||
c,
|
||||
f"{VENV} -c \"from app import db; print('tiktok_enabled', db.get_settings_map().get('tiktok_enabled'))\"",
|
||||
cwd=f"{REPO}/backend",
|
||||
)
|
||||
|
||||
print("\n=== frontend build + restart web ===")
|
||||
run(c, f"cd {REPO}/frontend && npm run build 2>&1 | tail -6", timeout=420)
|
||||
c.exec_command("systemctl restart douyinweb-web", timeout=5)
|
||||
time.sleep(8)
|
||||
run(c, "systemctl is-active douyinweb-web")
|
||||
|
||||
print("\n=== post-check ===")
|
||||
run(c, "curl -sS -o /dev/null -w 'health=%{http_code}\\n' http://127.0.0.1:8014/api/health")
|
||||
run(c, "curl -sS -o /dev/null -w 'tiktok=%{http_code}\\n' http://127.0.0.1:8014/api/tiktok/status")
|
||||
|
||||
c.close()
|
||||
print("\nDONE — TikTok Cookie 已部署;tiktok_enabled 默认关,不影响监控/Shorts")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
60
scripts/setup_tiktok_uploader.py
Normal file
60
scripts/setup_tiktok_uploader.py
Normal file
@ -0,0 +1,60 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Clone TiktokAutoUploader vendor + install tiktok-signature npm deps."""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VENDOR = ROOT / "backend" / "third_party" / "TiktokAutoUploader"
|
||||
SIG = VENDOR / "tiktok_uploader" / "tiktok-signature"
|
||||
REPO = "https://github.com/makiisthenes/TiktokAutoUploader.git"
|
||||
|
||||
|
||||
def run(cmd: list[str], cwd: Path | None = None) -> None:
|
||||
print("$", " ".join(cmd))
|
||||
subprocess.check_call(cmd, cwd=str(cwd) if cwd else None)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not VENDOR.is_dir():
|
||||
VENDOR.parent.mkdir(parents=True, exist_ok=True)
|
||||
run(["git", "clone", "--depth", "1", REPO, str(VENDOR)])
|
||||
_patch_vendor_upload()
|
||||
if SIG.is_dir():
|
||||
run(["npm", "install"], cwd=SIG)
|
||||
run(["npx", "playwright", "install", "chromium"], cwd=SIG)
|
||||
print("OK:", VENDOR)
|
||||
return 0
|
||||
|
||||
|
||||
def _patch_vendor_upload() -> None:
|
||||
"""Use visibility_type from upload_video args (upstream hardcodes public)."""
|
||||
path = VENDOR / "tiktok_uploader" / "tiktok.py"
|
||||
if not path.is_file():
|
||||
return
|
||||
text = path.read_text(encoding="utf-8")
|
||||
old = (
|
||||
'\t\t\t\t"privacy_setting_info": {\n'
|
||||
'\t\t\t\t\t"visibility_type": 0,\n'
|
||||
'\t\t\t\t\t"allow_duet": 1,\n'
|
||||
'\t\t\t\t\t"allow_stitch": 1,\n'
|
||||
'\t\t\t\t\t"allow_comment": 1\n'
|
||||
"\t\t\t\t}"
|
||||
)
|
||||
new = (
|
||||
'\t\t\t\t"privacy_setting_info": {\n'
|
||||
'\t\t\t\t\t"visibility_type": visibility_type,\n'
|
||||
'\t\t\t\t\t"allow_duet": allow_duet,\n'
|
||||
'\t\t\t\t\t"allow_stitch": allow_stitch,\n'
|
||||
'\t\t\t\t\t"allow_comment": allow_comment,\n'
|
||||
"\t\t\t\t}"
|
||||
)
|
||||
if old in text and new not in text:
|
||||
path.write_text(text.replace(old, new), encoding="utf-8")
|
||||
print("patched:", path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Reference in New Issue
Block a user