Pairs Android devices over WSS for TikTok/YouTube preview and go-live from monitored Douyin sources; also spreads TikTok uploads across the Beijing day with per-channel claim cooldown. Co-authored-by: Cursor <cursoragent@cursor.com>
223 lines
8.7 KiB
Python
223 lines
8.7 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""TikTok upload scheduling — Beijing day random stagger (anti burst)."""
|
||
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:
|
||
"""Pick a random upload time within the Beijing calendar day.
|
||
|
||
Not "soon after now" clustering — spread across remaining daytime so two
|
||
accounts never dump a backlog in one burst.
|
||
"""
|
||
settings = cfg or db.get_settings_map()
|
||
now = time.time()
|
||
day = push_date or push_date_from_ts(now)
|
||
day_start, day_end = beijing_day_bounds(day)
|
||
latest = day_end - 90.0
|
||
if not settings.get("tiktok_upload_spread", True):
|
||
return float(min(now + random.uniform(120, 900), latest))
|
||
|
||
# Global gap between ANY account; per-channel gap keeps each account sparse across 24h.
|
||
global_min = max(600.0, float(settings.get("tiktok_upload_min_gap_sec") or 900))
|
||
channel_min = max(global_min, float(settings.get("tiktok_channel_min_gap_sec") or 5400))
|
||
|
||
# Prefer random point in the remaining Beijing day (not just next 25 minutes).
|
||
earliest = max(now + random.uniform(300, 1200), day_start + 60)
|
||
if earliest >= latest - 60:
|
||
# Near day end → spill into tomorrow with random morning/afternoon offset
|
||
next_day = push_date_from_ts(day_end + 10)
|
||
n_start, n_end = beijing_day_bounds(next_day)
|
||
earliest = n_start + random.uniform(3600, 6 * 3600)
|
||
latest = n_end - 90
|
||
day = next_day
|
||
|
||
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.85:
|
||
return True
|
||
if other_ch and other_ch == channel_pk and gap < channel_min * 0.85:
|
||
return True
|
||
return False
|
||
|
||
lo = float(earliest)
|
||
hi = float(max(lo + 60.0, latest))
|
||
for _ in range(96):
|
||
cand = random.uniform(lo, hi)
|
||
if not conflicts(cand):
|
||
return float(min(cand, latest))
|
||
|
||
# Fallback: push after last occupied slot with channel gap jitter
|
||
last_ch = max((s[0] for s in slots if s[1] == channel_pk), default=now)
|
||
last_any = max((s[0] for s in slots), default=now)
|
||
base = max(lo, last_ch + channel_min, last_any + global_min)
|
||
return float(min(base + random.uniform(60, 900), latest))
|
||
|
||
|
||
def channel_upload_cooldown_left(channel_pk: str, *, cfg: dict[str, Any] | None = None) -> float:
|
||
"""Seconds until this channel may start another upload (0 = free)."""
|
||
pk = str(channel_pk or "").strip()
|
||
if not pk:
|
||
return 0.0
|
||
settings = cfg or db.get_settings_map()
|
||
channel_min = max(600.0, float(settings.get("tiktok_channel_min_gap_sec") or 5400))
|
||
now = time.time()
|
||
day = push_date_from_ts(now)
|
||
# Recent success / in-flight
|
||
last = 0.0
|
||
data = tiktok_db.list_tiktok_jobs(push_date=day, limit=200, offset=0)
|
||
for j in data.get("jobs") or []:
|
||
if str(j.get("channel_pk") or "") != pk:
|
||
continue
|
||
st = str(j.get("status") or "")
|
||
if st == "uploading":
|
||
last = max(last, float(j.get("updated_at") or 0), float(j.get("upload_at") or 0))
|
||
elif st in {"uploaded", "done"}:
|
||
last = max(last, float(j.get("finished_at") or j.get("updated_at") or 0))
|
||
if last <= 0:
|
||
return 0.0
|
||
left = (last + channel_min) - now
|
||
return float(max(0.0, left))
|
||
|
||
|
||
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(),
|
||
"clip_seconds": float(j.get("clip_seconds") or 0),
|
||
"can_upload_now": (
|
||
str(j.get("status") or "") in {"scheduled", "recorded", "uploading", "failed"}
|
||
and bool(str(j.get("clip_path") or "").strip())
|
||
),
|
||
}
|
||
)
|
||
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"])
|
||
daily_max = max(1, int(c.get("daily_max") or TIKTOK_DAILY_FORCE))
|
||
try:
|
||
from .db import _normalize_daily_quota
|
||
|
||
daily_max = _normalize_daily_quota(daily_max, default=TIKTOK_DAILY_FORCE, lo=1, hi=30)
|
||
except Exception:
|
||
pass
|
||
gap = max(0, daily_max - used)
|
||
if c.get("enabled"):
|
||
total_gap += gap
|
||
channel_rows.append(
|
||
{
|
||
"id": cid,
|
||
"name": c.get("name"),
|
||
"tiktok_username": c.get("tiktok_username"),
|
||
"nickname": c.get("nickname") or "",
|
||
"avatar_url": c.get("avatar_url") or "",
|
||
"tiktok_uid": c.get("tiktok_uid") or "",
|
||
"follower_count": int(c.get("follower_count") or 0),
|
||
"video_count": int(c.get("video_count") or 0),
|
||
"heart_count": int(c.get("heart_count") or 0),
|
||
"enabled": bool(c.get("enabled")),
|
||
"authorized": tiktok_session.channel_has_session(c),
|
||
"daily_min": int(c.get("daily_min") or TIKTOK_DAILY_FORCE),
|
||
"daily_max": daily_max,
|
||
"gap": gap,
|
||
"max_met": used >= daily_max,
|
||
**stats,
|
||
}
|
||
)
|
||
from .upload_timeline import build_timeline
|
||
|
||
timeline = build_timeline(enriched, now=now, day_start=day_start, day_end=day_end)
|
||
return {
|
||
"push_date": day,
|
||
"now": now,
|
||
"day_start": day_start,
|
||
"day_end": day_end,
|
||
"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,
|
||
"timeline": timeline,
|
||
"channels": channel_rows,
|
||
"beijing_hint": beijing_from_ts(now).strftime("%Y-%m-%d %H:%M"),
|
||
}
|