douyinWEB/backend/app/tiktok_schedule.py
eric d8fdeaa71c TikTok: Cookie 上传(TiktokAutoUploader),替代开发者 OAuth
账号粘贴 sessionid 即可上传;TikTok 模块独立,默认关闭不影响监控/Shorts。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 10:16:20 -05:00

154 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""TikTok upload scheduling — Beijing day staggered slots."""
from __future__ import annotations
import random
import time
from pathlib import Path
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
def _day_end_ts(push_date: str) -> float:
return beijing_day_bounds(push_date)[1]
def _occupied_slots(push_date: str) -> list[tuple[float, str]]:
data = tiktok_db.list_tiktok_jobs(push_date=push_date, limit=500, offset=0)
slots: list[tuple[float, str]] = []
for j in data.get("jobs") or []:
st = str(j.get("status") or "")
ch = str(j.get("channel_pk") or "")
if st in {"scheduled", "recorded", "uploading"}:
ts = float(j.get("upload_at") or 0) or float(j.get("updated_at") or 0)
if ts > 0:
slots.append((ts, ch))
elif st in {"uploaded", "done"}:
ts = float(j.get("finished_at") or j.get("updated_at") or 0)
if ts > 0:
slots.append((ts, ch))
return slots
def pick_upload_at(*, channel_pk: str, push_date: str = "", cfg: dict[str, Any] | None = None) -> float:
settings = cfg or db.get_settings_map()
now = time.time()
day = push_date or push_date_from_ts(now)
day_end = _day_end_ts(day)
latest = day_end - 45
if not settings.get("tiktok_upload_spread", True):
return min(now + random.uniform(20, 120), latest)
global_min = max(300.0, float(settings.get("tiktok_upload_min_gap_sec") or 720))
channel_min = max(global_min, float(settings.get("tiktok_channel_min_gap_sec") or 2400))
earliest = now + random.uniform(180, 1500)
if earliest >= latest:
earliest = now + random.uniform(30, max(90.0, global_min * 0.4))
slots = _occupied_slots(day)
def conflicts(ts: float) -> bool:
for other_ts, other_ch in slots:
gap = abs(ts - other_ts)
if gap < global_min * 0.9:
return True
if other_ch == channel_pk and gap < channel_min * 0.9:
return True
return False
window_end = max(earliest + 60, latest)
for _ in range(48):
cand = random.uniform(earliest, window_end)
if not conflicts(cand):
return float(min(cand, latest))
last_ts = max((s[0] for s in slots), default=now)
return float(min(max(earliest, last_ts + global_min), latest))
def schedule_board(limit: int = 24) -> dict[str, Any]:
day = push_date_from_ts(time.time())
now = time.time()
day_start, day_end = beijing_day_bounds(day)
data = tiktok_db.list_tiktok_jobs(push_date=day, limit=500, offset=0)
upcoming: list[dict[str, Any]] = []
by_ch: dict[str, dict[str, int]] = {}
for j in data.get("jobs") or []:
ch = str(j.get("channel_pk") or "")
st = str(j.get("status") or "")
bucket = by_ch.setdefault(ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0})
if st not in {"failed", "skipped"}:
bucket["used"] += 1
if st in {"uploaded", "done"}:
bucket["uploaded"] += 1
if st == "scheduled":
bucket["scheduled"] += 1
if st in {"pending", "recording"}:
bucket["pending"] += 1
clip = str(j.get("clip_path") or "").strip()
clip_ready = bool(clip) and Path(clip).is_file()
if st in {"scheduled", "recorded"} and clip_ready:
upcoming.append(j)
upcoming.sort(key=lambda x: float(x.get("upload_at") or x.get("updated_at") or 0))
channels = tiktok_db.list_tiktok_channels(enabled=None)
channel_map = {str(c["id"]): c for c in channels}
enriched = []
for j in upcoming:
if len(enriched) >= limit:
break
pk = str(j.get("channel_pk") or "")
ch = channel_map.get(pk, {})
if not ch:
continue
clip = str(j.get("clip_path") or "").strip()
enriched.append(
{
"id": j.get("id"),
"upload_at": j.get("upload_at"),
"anchor_name": j.get("anchor_name"),
"room_id": j.get("room_id"),
"channel_pk": pk,
"channel_name": ch.get("name") or "",
"status": j.get("status"),
"clip_ready": bool(clip) and Path(clip).is_file(),
"can_upload_now": str(j.get("status") or "") in {"scheduled", "recorded"},
}
)
channel_rows = []
day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start)))
total_gap = 0
for c in channels:
cid = str(c["id"])
stats = by_ch.get(cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0})
used = int(stats["used"])
gap = max(0, TIKTOK_DAILY_FORCE - used)
if c.get("enabled"):
total_gap += gap
channel_rows.append(
{
"id": cid,
"name": c.get("name"),
"tiktok_username": c.get("tiktok_username"),
"enabled": bool(c.get("enabled")),
"authorized": tiktok_session.channel_has_session(c),
"daily_min": TIKTOK_DAILY_FORCE,
"daily_max": TIKTOK_DAILY_FORCE,
"gap": gap,
"max_met": used >= TIKTOK_DAILY_FORCE,
**stats,
}
)
return {
"push_date": day,
"now": now,
"seconds_left": max(0, int(day_end - now)),
"day_progress": round(day_progress, 4),
"total_gap": total_gap,
"beijing_window": f"{day} 00:00–24:00",
"upcoming": enriched,
"channels": channel_rows,
"beijing_hint": beijing_from_ts(now).strftime("%Y-%m-%d %H:%M"),
}