feat: TikTok Cookie 按账号计时,并支持多账号独立会话
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
dcead62399
commit
4c8eafacb3
@ -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"),
|
||||
|
||||
@ -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, "账号不存在")
|
||||
|
||||
@ -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()
|
||||
|
||||
@ -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 "")
|
||||
|
||||
@ -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):
|
||||
|
||||
@ -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 && (
|
||||
<section className="mb-6 rounded-2xl border border-white/10 bg-black/30 p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-slate-100">{editId ? "编辑账号" : "新增 TikTok 账号"}</h3>
|
||||
<p className="mb-3 text-xs text-slate-500">
|
||||
可添加多个账号,每个账号各自粘贴 Cookie、各自计时,互不影响。
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="text-xs text-slate-400">
|
||||
显示名称
|
||||
@ -551,8 +608,44 @@ export default function TikTokPage() {
|
||||
<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">
|
||||
推荐用 Chrome 插件或油猴导出 Cookie(无需 F12)。sessionid 等同密码,请勿泄露。
|
||||
每个账号单独保存 Cookie。sessionid 约 30 天过期,保存后会开始计时。sessionid 等同密码,请勿泄露。
|
||||
</p>
|
||||
<label className="mb-3 block text-xs text-slate-400">
|
||||
保存到账号
|
||||
<select
|
||||
value={sessionChannelId}
|
||||
onChange={(e) => {
|
||||
const id = e.target.value;
|
||||
const ch = channels.find((c) => c.id === id);
|
||||
setSessionChannelId(id);
|
||||
setSessionChannelName(ch?.name || sessionChannelName);
|
||||
setSessionUsername(ch?.tiktok_username || "");
|
||||
}}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100"
|
||||
>
|
||||
{sessionChannelId && !channels.some((c) => c.id === sessionChannelId) && (
|
||||
<option value={sessionChannelId}>{sessionChannelName || "新账号"}</option>
|
||||
)}
|
||||
{channels.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
{c.tiktok_username ? ` · ${c.tiktok_username}` : ""}
|
||||
{c.authorized ? ` · ${cookieAgeLabel(c)}` : " · 未配置 Cookie"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{(() => {
|
||||
const current = channels.find((c) => c.id === sessionChannelId);
|
||||
if (!current?.authorized) return null;
|
||||
return (
|
||||
<p className={`mb-3 text-xs ${cookieAgeClass(current)}`}>
|
||||
当前 Cookie:{cookieAgeLabel(current)}
|
||||
{current.cookie_saved_at ? ` · 保存于 ${fmtTs(current.cookie_saved_at)}` : ""}
|
||||
。保存新 Cookie 会重新开始计时。
|
||||
</p>
|
||||
);
|
||||
})()}
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
@ -638,7 +731,11 @@ export default function TikTokPage() {
|
||||
<div
|
||||
key={ch.id}
|
||||
className={`rounded-xl border bg-gradient-to-br from-white/[0.04] to-transparent p-3 ${
|
||||
ch.max_met ? "border-teal-500/30" : "border-white/10"
|
||||
full?.enabled === false
|
||||
? "border-white/10 opacity-60"
|
||||
: ch.max_met
|
||||
? "border-teal-500/30"
|
||||
: "border-white/10"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
@ -646,10 +743,14 @@ export default function TikTokPage() {
|
||||
<div className="truncate font-medium text-slate-100">{ch.name || "未命名"}</div>
|
||||
<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"}`}>
|
||||
<span className={`shrink-0 text-[10px] ${cookieAgeClass(full)}`}>
|
||||
{full?.authorized ? "Cookie 就绪" : "未配置"}
|
||||
</span>
|
||||
</div>
|
||||
<div className={`mt-1 text-[10px] ${cookieAgeClass(full)}`}>{cookieAgeLabel(full)}</div>
|
||||
{full?.authorized && full.cookie_saved_at ? (
|
||||
<div className="text-[10px] text-slate-500">保存于 {fmtTs(full.cookie_saved_at)}</div>
|
||||
) : null}
|
||||
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-white/10">
|
||||
<div className="h-full rounded-full bg-pink-500/70" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
@ -670,6 +771,15 @@ export default function TikTokPage() {
|
||||
<KeyRound className="h-3 w-3" />
|
||||
{full?.authorized ? "更新 Cookie" : "粘贴 Cookie"}
|
||||
</button>
|
||||
{full && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void toggleChannelEnabled(full)}
|
||||
className="rounded-lg bg-white/5 px-2 py-1 text-[11px]"
|
||||
>
|
||||
{full.enabled === false ? "启用" : "停用"}
|
||||
</button>
|
||||
)}
|
||||
{full && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user