# -*- 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(), "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"), }