From b59c39d4b89507f2ffe0a1827b2410cb6c589b3c Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 15 Aug 2026 04:59:15 -0500 Subject: [PATCH] =?UTF-8?q?feat(test1):=20=E6=97=B6=E9=97=B4=E8=BD=B4/?= =?UTF-8?q?=E5=9C=BA=E6=AC=A1=E6=B7=B1=E9=93=BE/=E6=8C=89=E6=88=BF?= =?UTF-8?q?=E6=97=B6=E9=95=BF/=E7=9B=AF=E6=A2=A2=E6=8E=A8=E8=8D=90/?= =?UTF-8?q?=E9=85=8D=E9=A2=9D=E9=A2=84=E6=BC=94/X=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- backend/app/db.py | 95 +++++++++++++++- backend/app/main.py | 42 +++++++- backend/app/models.py | 3 + backend/app/monitor.py | 11 ++ backend/app/notify.py | 2 + backend/app/room_recommend.py | 101 ++++++++++++++++++ backend/app/shorts_pipeline.py | 12 +++ backend/app/shorts_schedule.py | 27 ++++- backend/app/tiktok_db.py | 8 ++ backend/app/tiktok_pipeline.py | 8 ++ backend/app/tiktok_schedule.py | 6 ++ backend/app/upload_timeline.py | 59 ++++++++++ backend/app/watch_remind.py | 74 +++++++++++++ frontend/src/app/anchors/page.tsx | 45 +++++++- frontend/src/app/rooms/page.tsx | 84 ++++++++++++++- frontend/src/app/shorts/page.tsx | 26 ++++- frontend/src/app/tiktok/page.tsx | 13 +++ frontend/src/app/x/XOpsPanels.tsx | 42 ++++++++ frontend/src/app/x/page.tsx | 15 +++ .../src/components/SessionDetailModal.tsx | 100 ++++++++++++++++- frontend/src/components/UploadTimeline.tsx | 92 ++++++++++++++++ 21 files changed, 852 insertions(+), 13 deletions(-) create mode 100644 backend/app/room_recommend.py create mode 100644 backend/app/upload_timeline.py create mode 100644 backend/app/watch_remind.py create mode 100644 frontend/src/components/UploadTimeline.tsx diff --git a/backend/app/db.py b/backend/app/db.py index 5e1cd9a..5892488 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -194,6 +194,8 @@ def init_db() -> None: cols = {r[1] for r in conn.execute("PRAGMA table_info(rooms)").fetchall()} if "tags" not in cols: conn.execute("ALTER TABLE rooms ADD COLUMN tags TEXT NOT NULL DEFAULT ''") + if "clip_sec" not in cols: + conn.execute("ALTER TABLE rooms ADD COLUMN clip_sec INTEGER NOT NULL DEFAULT 0") gcols = {r[1] for r in conn.execute("PRAGMA table_info(channel_groups)").fetchall()} for col, ddl in [ ("last_status", "TEXT NOT NULL DEFAULT 'unknown'"), @@ -390,6 +392,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "notify_on_shorts_fail": True, "notify_on_shorts_ok": False, "notify_on_shorts_quota": True, + "notify_on_watch_remind": True, + "watch_remind_window_sec": 1800, "quiet_hours_enabled": False, "quiet_hours_start": 2, "quiet_hours_end": 7, @@ -1015,6 +1019,7 @@ def update_room( note: Optional[str] = None, enabled: Optional[bool] = None, tags: Any = None, + clip_sec: Optional[int] = None, ) -> dict[str, Any]: with _lock: conn = _connect() @@ -1027,12 +1032,24 @@ def update_room( new_note = note if note is not None else row["note"] new_enabled = (1 if enabled else 0) if enabled is not None else row["enabled"] new_tags = _normalize_tags(tags) if tags is not None else (row["tags"] if "tags" in row.keys() else "") + keys = row.keys() + cur_clip = int(row["clip_sec"] or 0) if "clip_sec" in keys else 0 + new_clip = cur_clip + if clip_sec is not None: + try: + new_clip = int(clip_sec) + except Exception: + new_clip = 0 + if new_clip < 0: + new_clip = 0 + if new_clip > 120: + new_clip = 120 conn.execute( """ - UPDATE rooms SET url = ?, room_id = ?, note = ?, enabled = ?, tags = ?, updated_at = ? + UPDATE rooms SET url = ?, room_id = ?, note = ?, enabled = ?, tags = ?, clip_sec = ?, updated_at = ? WHERE id = ? """, - (new_url, new_rid, new_note, new_enabled, new_tags, time.time(), room_pk), + (new_url, new_rid, new_note, new_enabled, new_tags, new_clip, time.time(), room_pk), ) conn.commit() return _row_to_dict(conn.execute("SELECT * FROM rooms WHERE id = ?", (room_pk,)).fetchone()) # type: ignore @@ -1040,6 +1057,59 @@ def update_room( conn.close() +def room_clip_seconds(room_or_pk: Any, *, default: int = 15, platform: str = "shorts") -> int: + """Per-room clip length override; 0 means use global default.""" + room = None + if isinstance(room_or_pk, dict): + room = room_or_pk + elif room_or_pk: + room = get_room(str(room_or_pk)) + override = 0 + if room: + try: + override = int(room.get("clip_sec") or 0) + except Exception: + override = 0 + if override > 0: + return max(5, min(120, override)) + try: + d = int(default or 0) + except Exception: + d = 0 + if d <= 0: + return 0 + return max(5, min(120, d)) + + +def get_kv(key: str) -> Any: + with _lock: + conn = _connect() + try: + row = conn.execute("SELECT value FROM kv_settings WHERE key = ?", (key,)).fetchone() + if not row: + return None + try: + return json.loads(row["value"]) + except Exception: + return row["value"] + finally: + conn.close() + + +def set_kv(key: str, value: Any) -> None: + with _lock: + conn = _connect() + try: + conn.execute( + "INSERT INTO kv_settings(key, value) VALUES(?, ?) " + "ON CONFLICT(key) DO UPDATE SET value = excluded.value", + (key, json.dumps(value)), + ) + conn.commit() + finally: + conn.close() + + def bulk_rooms(action: str, ids: list[str], *, tags: Any = None) -> dict[str, Any]: action = (action or "").strip().lower() ids = [i for i in ids if i] @@ -2183,6 +2253,17 @@ def list_upcoming_opens(*, limit: int = 20, priority_only: bool = False) -> list hint = schedule.get("next_open_hint") if not hint or not hint.get("eta_ts"): continue + n_sess = len(sessions) + avg_gap = schedule.get("avg_gap_hours") + confidence = 0.35 + if n_sess >= 8 and avg_gap and float(avg_gap) < 48: + confidence = 0.85 + elif n_sess >= 4: + confidence = 0.65 + elif n_sess >= 2: + confidence = 0.5 + if is_priority: + confidence = min(0.95, confidence + 0.1) items.append( { "anchor_name": (sessions[0].get("anchor_name") if sessions else "") or key, @@ -2196,6 +2277,8 @@ def list_upcoming_opens(*, limit: int = 20, priority_only: bool = False) -> list "peak_slot_label": schedule.get("peak_slot_label") or "", "next_open_hint": hint, "eta_ts": float(hint["eta_ts"]), + "confidence": round(confidence, 2), + "sessions_sampled": n_sess, } ) items.sort(key=lambda x: (0 if x.get("priority") else 1, float(x.get("eta_ts") or 0))) @@ -3397,6 +3480,8 @@ def list_shorts_jobs( status: str = "", push_date: str = "", channel_pk: str = "", + session_id: str = "", + room_id: str = "", limit: int = 100, offset: int = 0, ) -> dict[str, Any]: @@ -3414,6 +3499,12 @@ def list_shorts_jobs( if channel_pk.strip(): clauses.append("channel_pk = ?") params.append(channel_pk.strip()) + if session_id.strip(): + clauses.append("session_id = ?") + params.append(session_id.strip()) + if room_id.strip(): + clauses.append("room_id = ?") + params.append(room_id.strip()) where = ("WHERE " + " AND ".join(clauses)) if clauses else "" total = conn.execute(f"SELECT COUNT(*) AS c FROM shorts_jobs {where}", params).fetchone()["c"] rows = conn.execute( diff --git a/backend/app/main.py b/backend/app/main.py index fe8272d..02352d7 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -651,11 +651,19 @@ async def shorts_jobs_list( status: str = "", push_date: str = "", channel_pk: str = "", + session_id: str = "", + room_id: str = "", limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0), ) -> dict[str, Any]: data = db.list_shorts_jobs( - status=status, push_date=push_date, channel_pk=channel_pk, limit=limit, offset=offset + status=status, + push_date=push_date, + channel_pk=channel_pk, + session_id=session_id, + room_id=room_id, + limit=limit, + offset=offset, ) data["jobs"] = [_enrich_shorts_job(j) for j in data.get("jobs") or []] return data @@ -1341,6 +1349,8 @@ async def tiktok_jobs_list( status: str = "", push_date: str = "", channel_pk: str = "", + session_id: str = "", + room_id: str = "", limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0), ) -> dict[str, Any]: @@ -1351,6 +1361,8 @@ async def tiktok_jobs_list( status=status, push_date=push_date, channel_pk=channel_pk, + session_id=session_id, + room_id=room_id, limit=limit, offset=offset, ) @@ -1491,6 +1503,16 @@ async def rooms_tags() -> dict[str, Any]: return {"tags": db.list_all_tags()} +@app.get("/api/rooms/recommend") +async def rooms_recommend( + limit: int = Query(20, ge=1, le=100), + lookback_days: int = Query(14, ge=3, le=60), +) -> dict[str, Any]: + from .room_recommend import recommend_rooms + + return recommend_rooms(limit=limit, lookback_days=lookback_days) + + @app.post("/api/rooms") async def rooms_create(body: RoomCreate) -> dict[str, Any]: try: @@ -1609,6 +1631,7 @@ async def rooms_update(room_pk: str, body: RoomUpdate) -> dict[str, Any]: note=body.note, enabled=body.enabled, tags=body.tags, + clip_sec=body.clip_sec, ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc @@ -2294,7 +2317,22 @@ async def sessions_detail(session_id: str) -> dict[str, Any]: session = db.get_session(session_id) if not session: raise HTTPException(404, "场次不存在") - return {"session": session} + shorts = db.list_shorts_jobs(session_id=session_id, limit=30, offset=0) + from . import tiktok_db + + tiktok = tiktok_db.list_tiktok_jobs(session_id=session_id, limit=30, offset=0) + return { + "session": session, + "shorts_jobs": [_enrich_shorts_job(j) for j in shorts.get("jobs") or []], + "tiktok_jobs": [_enrich_tiktok_job(j) for j in tiktok.get("jobs") or []], + } + + +@app.post("/api/watch-remind/check") +async def watch_remind_check() -> dict[str, Any]: + from .watch_remind import check_and_notify + + return await check_and_notify() @app.get("/api/sessions/{session_id}/cover") diff --git a/backend/app/models.py b/backend/app/models.py index a05be20..203058a 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -132,6 +132,7 @@ class RoomUpdate(BaseModel): note: Optional[str] = None enabled: Optional[bool] = None tags: Optional[str] = None + clip_sec: Optional[int] = None class RoomBulkAction(BaseModel): @@ -196,6 +197,8 @@ class SettingsUpdate(BaseModel): notify_on_shorts_fail: Optional[bool] = None notify_on_shorts_ok: Optional[bool] = None notify_on_shorts_quota: Optional[bool] = None + notify_on_watch_remind: Optional[bool] = None + watch_remind_window_sec: Optional[int] = None quiet_hours_enabled: Optional[bool] = None quiet_hours_start: Optional[int] = None quiet_hours_end: Optional[int] = None diff --git a/backend/app/monitor.py b/backend/app/monitor.py index 4e48e06..5245a46 100644 --- a/backend/app/monitor.py +++ b/backend/app/monitor.py @@ -25,6 +25,7 @@ class MonitorService: self._last_request_at = 0.0 self._lock = asyncio.Lock() self._last_reconcile_at = 0.0 + self._last_watch_remind_at = 0.0 @property def running(self) -> bool: @@ -392,6 +393,16 @@ class MonitorService: self.last_error = f"reconcile: {exc}" self._last_reconcile_at = time.time() + # High-confidence watch reminders (webhook), ~5 min cadence + if time.time() - self._last_watch_remind_at > 300: + try: + from .watch_remind import check_and_notify + + await check_and_notify() + except Exception as exc: + self.last_error = f"watch_remind: {exc}" + self._last_watch_remind_at = time.time() + rooms = db.due_rooms(limit=int(cfg.get("max_concurrency", settings.max_concurrency)) * 3) if self._in_quiet_hours(cfg) and bool(cfg.get("quiet_hours_allow_priority", True)): rooms = [r for r in rooms if self._is_priority(r)] diff --git a/backend/app/notify.py b/backend/app/notify.py index 4560fec..61cee01 100644 --- a/backend/app/notify.py +++ b/backend/app/notify.py @@ -31,6 +31,8 @@ async def send_webhook(event: str, payload: dict[str, Any]) -> None: return if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True): return + if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True): + return # allow ops/test always when URL configured body = { diff --git a/backend/app/room_recommend.py b/backend/app/room_recommend.py new file mode 100644 index 0000000..eb25058 --- /dev/null +++ b/backend/app/room_recommend.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +"""Room sampling recommendations from historical Shorts/TikTok job success.""" +from __future__ import annotations + +import time +from typing import Any + +from .db import _connect, _lock, _row_to_dict + + +def recommend_rooms(*, limit: int = 20, lookback_days: int = 14) -> dict[str, Any]: + """Rank Douyin rooms by historical clip→upload success rate.""" + since = time.time() - max(1, int(lookback_days)) * 86400 + with _lock: + conn = _connect() + try: + # Shorts stats + shorts = conn.execute( + """ + SELECT room_id, + COUNT(*) AS total, + SUM(CASE WHEN status IN ('uploaded','done') THEN 1 ELSE 0 END) AS ok, + SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS fail + FROM shorts_jobs + WHERE room_id != '' AND created_at >= ? + GROUP BY room_id + """, + (since,), + ).fetchall() + tiktok = conn.execute( + """ + SELECT room_id, + COUNT(*) AS total, + SUM(CASE WHEN status IN ('uploaded','done') THEN 1 ELSE 0 END) AS ok, + SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS fail + FROM tiktok_jobs + WHERE room_id != '' AND created_at >= ? + GROUP BY room_id + """, + (since,), + ).fetchall() + rooms = { + str(r["room_id"]): _row_to_dict(r) + for r in conn.execute( + "SELECT id, room_id, url, note, tags, last_anchor, last_status, enabled " + "FROM rooms WHERE room_id != '' AND room_id NOT LIKE 'yt:%'" + ).fetchall() + } + finally: + conn.close() + + merged: dict[str, dict[str, Any]] = {} + for row in shorts: + rid = str(row["room_id"] or "") + if not rid: + continue + merged.setdefault(rid, {"room_id": rid, "shorts_total": 0, "shorts_ok": 0, "tiktok_total": 0, "tiktok_ok": 0}) + merged[rid]["shorts_total"] = int(row["total"] or 0) + merged[rid]["shorts_ok"] = int(row["ok"] or 0) + for row in tiktok: + rid = str(row["room_id"] or "") + if not rid: + continue + merged.setdefault(rid, {"room_id": rid, "shorts_total": 0, "shorts_ok": 0, "tiktok_total": 0, "tiktok_ok": 0}) + merged[rid]["tiktok_total"] = int(row["total"] or 0) + merged[rid]["tiktok_ok"] = int(row["ok"] or 0) + + out: list[dict[str, Any]] = [] + for rid, st in merged.items(): + total = int(st["shorts_total"]) + int(st["tiktok_total"]) + ok = int(st["shorts_ok"]) + int(st["tiktok_ok"]) + if total < 2: + continue + rate = ok / total if total else 0.0 + room = rooms.get(rid) or {} + tags = room.get("tags") or [] + if isinstance(tags, str): + tags = [t for t in tags.split(",") if t.strip()] + suggest = [] + if rate >= 0.45 and "shorts" not in tags and "shorts_only" not in tags: + suggest.append("shorts") + if rate >= 0.45 and "tiktok" not in tags and "tiktok_only" not in tags: + suggest.append("tiktok") + out.append( + { + "room_id": rid, + "room_pk": room.get("id") or "", + "anchor": room.get("last_anchor") or "", + "url": room.get("url") or "", + "tags": tags, + "enabled": bool(room.get("enabled")), + "total": total, + "ok": ok, + "fail": total - ok, + "success_rate": round(rate, 3), + "suggest_tags": suggest, + "reason": f"近{lookback_days}天成功率 {round(rate*100)}%({ok}/{total})", + } + ) + out.sort(key=lambda x: (-float(x["success_rate"]), -int(x["total"]))) + return {"lookback_days": lookback_days, "rooms": out[: max(1, min(int(limit), 100))]} diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 538d045..9c6b434 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -1092,6 +1092,18 @@ class ShortsPipeline: ) return sec = int(cfg.get("shorts_clip_sec") or 15) + try: + room_pk = str(job.get("room_pk") or "") + room = db.get_room(room_pk) if room_pk else None + if not room and job.get("room_id"): + # best-effort by room_id + for r in db.list_live_douyin_rooms_for_shorts(limit=500): + if str(r.get("room_id") or "") == str(job.get("room_id") or ""): + room = r + break + sec = db.room_clip_seconds(room, default=sec, platform="shorts") + except Exception: + pass outcome = await record_clip(job_id=jid, stream_urls=candidates, seconds=sec) stream = str(outcome.get("stream_url") or stream) if not outcome.get("ok"): diff --git a/backend/app/shorts_schedule.py b/backend/app/shorts_schedule.py index 473544d..ad7a900 100644 --- a/backend/app/shorts_schedule.py +++ b/backend/app/shorts_schedule.py @@ -209,12 +209,15 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start))) total_gap = 0 min_unmet = 0 + from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota + from .upload_timeline import build_timeline + for c in channels: cid = str(c["id"]) - from .db import SHORTS_DAILY_FORCE - - daily_min = SHORTS_DAILY_FORCE - daily_max = SHORTS_DAILY_FORCE + daily_min = _normalize_daily_quota(c.get("daily_min"), default=SHORTS_DAILY_FORCE) + daily_max = _normalize_daily_quota(c.get("daily_max"), default=SHORTS_DAILY_FORCE) + if daily_max < daily_min: + daily_max = daily_min stats = by_ch.get(cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0}) used = int(stats["used"]) gap = max(0, daily_max - used) @@ -241,6 +244,20 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: **stats, } ) + timeline = build_timeline(enriched, now=now, day_start=day_start, day_end=day_end) + # Lightweight YT quota forecast: if many uploads still pending vs remaining day hours + pending_uploads = sum(1 for x in enriched if str(x.get("status") or "") in {"scheduled", "recorded"}) + hours_left = max(0.1, (day_end - now) / 3600.0) + quota_forecast = { + "pending_uploads": pending_uploads, + "hours_left": round(hours_left, 2), + "per_hour_pace": round(pending_uploads / hours_left, 2) if hours_left else pending_uploads, + "warn": pending_uploads >= 8 and hours_left < 4, + "message": ( + f"今日仍有 {pending_uploads} 条待传,约剩 {hours_left:.1f} 小时" + + (",节奏偏紧,建议错开或延后低优任务" if pending_uploads >= 8 and hours_left < 4 else "") + ), + } return { "push_date": day, "now": now, @@ -252,6 +269,8 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: "min_unmet_channels": min_unmet, "beijing_window": f"{day} 00:00–24:00", "upcoming": enriched, + "timeline": timeline, + "quota_forecast": quota_forecast, "channels": channel_rows, "beijing_hint": beijing_from_ts(now).strftime("%Y-%m-%d %H:%M"), } diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index b1cd85e..dc150ef 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -375,6 +375,8 @@ def list_tiktok_jobs( status: str = "", push_date: str = "", channel_pk: str = "", + session_id: str = "", + room_id: str = "", limit: int = 100, offset: int = 0, ) -> dict[str, Any]: @@ -392,6 +394,12 @@ def list_tiktok_jobs( if channel_pk.strip(): clauses.append("channel_pk = ?") params.append(channel_pk.strip()) + if session_id.strip(): + clauses.append("session_id = ?") + params.append(session_id.strip()) + if room_id.strip(): + clauses.append("room_id = ?") + params.append(room_id.strip()) where = ("WHERE " + " AND ".join(clauses)) if clauses else "" total = conn.execute(f"SELECT COUNT(*) AS c FROM tiktok_jobs {where}", params).fetchone()["c"] rows = conn.execute( diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index a4236fc..c76202d 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -506,6 +506,14 @@ class TikTokPipeline: # TikTok 素材最少录 1 分钟;多 CDN 线路按 DouyinLiveRecorder 方式试探 sec = max(60, int(cfg.get("tiktok_clip_sec") or 60)) + try: + room_pk = str(job.get("room_pk") or "") + room = db.get_room(room_pk) if room_pk else None + override = db.room_clip_seconds(room, default=0, platform="tiktok") if room else 0 + if override > 0: + sec = max(60, override) + except Exception: + pass outcome = await record_clip( job_id=f"tiktok_{jid[:8]}", stream_urls=candidates, diff --git a/backend/app/tiktok_schedule.py b/backend/app/tiktok_schedule.py index 4267ec5..77cfa3d 100644 --- a/backend/app/tiktok_schedule.py +++ b/backend/app/tiktok_schedule.py @@ -157,14 +157,20 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: **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"), } diff --git a/backend/app/upload_timeline.py b/backend/app/upload_timeline.py new file mode 100644 index 0000000..1c2955e --- /dev/null +++ b/backend/app/upload_timeline.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +"""Upload timeline helpers — hour buckets for Shorts / TikTok schedule boards.""" +from __future__ import annotations + +from typing import Any + +from .timeutil import beijing_from_ts + + +def build_timeline( + jobs: list[dict[str, Any]], + *, + now: float, + day_start: float, + day_end: float, +) -> dict[str, Any]: + """Build 24 Beijing-hour slots with job markers for the current push day.""" + hours: list[dict[str, Any]] = [] + for h in range(24): + hours.append( + { + "hour": h, + "label": f"{h:02d}:00", + "jobs": [], + "count": 0, + "is_past": False, + "is_current": False, + } + ) + now_h = beijing_from_ts(now).hour + for bucket in hours: + bucket["is_past"] = int(bucket["hour"]) < now_h + bucket["is_current"] = int(bucket["hour"]) == now_h + + for j in jobs: + ts = float(j.get("upload_at") or j.get("finished_at") or j.get("updated_at") or 0) + if ts <= 0: + continue + if ts < day_start - 60 or ts > day_end + 60: + continue + h = beijing_from_ts(ts).hour + item = { + "id": j.get("id"), + "upload_at": ts, + "status": j.get("status"), + "anchor_name": j.get("anchor_name") or "", + "channel_name": j.get("channel_name") or "", + "channel_pk": j.get("channel_pk") or "", + "clip_ready": bool(j.get("clip_ready")), + "can_upload_now": bool(j.get("can_upload_now")), + } + hours[h]["jobs"].append(item) + hours[h]["count"] = len(hours[h]["jobs"]) + + return { + "hours": hours, + "now_hour": now_h, + "total": sum(int(x["count"]) for x in hours), + } diff --git a/backend/app/watch_remind.py b/backend/app/watch_remind.py new file mode 100644 index 0000000..e65b738 --- /dev/null +++ b/backend/app/watch_remind.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +"""Anchor watch reminders — notify when high-confidence opens are overdue.""" +from __future__ import annotations + +import time +from typing import Any + +from . import db +from .notify import send_webhook + + +def _dedupe_key(room_id: str, day_bucket: int) -> str: + return f"watch_remind:{room_id}:{day_bucket}" + + +async def check_and_notify(*, now: float | None = None) -> dict[str, Any]: + """Scan upcoming opens; fire webhook once per room per ~3h window when overdue.""" + cfg = db.get_settings_map() + if not cfg.get("notify_on_watch_remind", True): + return {"sent": 0, "skipped": "disabled"} + now = float(now or time.time()) + window = max(300, int(cfg.get("watch_remind_window_sec") or 1800)) + items = db.list_upcoming_opens(limit=40, priority_only=False) + sent = 0 + checked = 0 + for it in items: + conf = float(it.get("confidence") or 0) + if conf < 0.65 and not it.get("priority"): + continue + eta = float(it.get("eta_ts") or 0) + if eta <= 0: + continue + # Only remind when ETA is due / slightly overdue (within window) + if eta > now + 120: + continue + if now - eta > window: + continue + checked += 1 + rid = str(it.get("room_id") or it.get("room_pk") or "") + if not rid: + continue + bucket = int(now // 10800) # 3h dedupe buckets + key = _dedupe_key(rid, bucket) + try: + prev = db.get_kv(key) + if prev: + continue + except Exception: + pass + name = str(it.get("anchor_name") or rid) + msg = ( + f"【盯梢】{name} 预计开播窗口已到" + + (f"(置信 {int(conf*100)}%)" if conf else "") + + (f" · {it.get('typical_open_hint')}" if it.get("typical_open_hint") else "") + ) + await send_webhook( + "watch_remind", + { + "message": msg, + "anchor_name": name, + "room_id": rid, + "room_pk": it.get("room_pk"), + "url": it.get("url"), + "eta_ts": eta, + "confidence": conf, + "priority": bool(it.get("priority")), + }, + ) + try: + db.set_kv(key, {"ts": now, "anchor": name}) + except Exception: + pass + sent += 1 + return {"sent": sent, "checked": checked, "candidates": len(items)} diff --git a/frontend/src/app/anchors/page.tsx b/frontend/src/app/anchors/page.tsx index be35bc9..50d7b45 100644 --- a/frontend/src/app/anchors/page.tsx +++ b/frontend/src/app/anchors/page.tsx @@ -69,6 +69,17 @@ export default function AnchorsPage() { const [error, setError] = useState(""); const [detail, setDetail] = useState(null); const [bootstrapped, setBootstrapped] = useState(false); + const [upcoming, setUpcoming] = useState< + Array<{ + anchor_name: string; + room_id?: string; + eta_ts?: number; + confidence?: number; + priority?: boolean; + typical_open_hint?: string; + next_open_hint?: { label?: string; based_on?: string }; + }> + >([]); useEffect(() => { if (typeof window === "undefined") return; @@ -85,9 +96,13 @@ export default function AnchorsPage() { setError(""); } try { - const data = await fetchJson("/api/anchors?limit=80"); + const [data, up] = await Promise.all([ + fetchJson("/api/anchors?limit=80"), + fetchJson("/api/anchors/upcoming?limit=8"), + ]); const list = (data.anchors || []) as AnchorRow[]; setAnchors(list); + setUpcoming(up.items || []); } catch (e) { if (!silent) setError((e as Error).message); } finally { @@ -179,6 +194,34 @@ export default function AnchorsPage() { {error ?
{error}
: null} + {upcoming.length > 0 ? ( +
+
+

盯梢:预计开播窗口

+ 高置信度会推 Webhook +
+
+ {upcoming.map((u) => ( + + ))} +
+
+ ) : null} + {!anchors.length && !loading ? ( ) : ( diff --git a/frontend/src/app/rooms/page.tsx b/frontend/src/app/rooms/page.tsx index 3dda3b8..c80458b 100644 --- a/frontend/src/app/rooms/page.tsx +++ b/frontend/src/app/rooms/page.tsx @@ -17,6 +17,7 @@ type Room = { room_id: string; note?: string; tags?: string[]; + clip_sec?: number; enabled: boolean; last_status: string; last_anchor?: string; @@ -27,6 +28,18 @@ type Room = { error_count?: number; }; +type RecommendRoom = { + room_id: string; + room_pk?: string; + anchor?: string; + success_rate: number; + total: number; + ok: number; + reason?: string; + suggest_tags?: string[]; + tags?: string[]; +}; + export default function RoomsPage() { const confirm = useConfirm(); const toast = useToast(); @@ -51,7 +64,9 @@ export default function RoomsPage() { const [editRoom, setEditRoom] = useState(null); const [editNote, setEditNote] = useState(""); const [editTags, setEditTags] = useState(""); + const [editClipSec, setEditClipSec] = useState("0"); const [editBusy, setEditBusy] = useState(false); + const [recommend, setRecommend] = useState([]); useEffect(() => { if (typeof window === "undefined") return; @@ -91,6 +106,7 @@ export default function RoomsPage() { setEditRoom(room); setEditNote(room.note || ""); setEditTags((room.tags || []).join(",")); + setEditClipSec(String(room.clip_sec || 0)); } async function saveEdit() { @@ -100,7 +116,11 @@ export default function RoomsPage() { try { await fetchJson(`/api/rooms/${editRoom.id}`, { method: "PATCH", - body: JSON.stringify({ note: editNote, tags: editTags }), + body: JSON.stringify({ + note: editNote, + tags: editTags, + clip_sec: Number(editClipSec) || 0, + }), }); setMsg(`已更新 ${editRoom.room_id}`); setEditRoom(null); @@ -151,13 +171,15 @@ export default function RoomsPage() { setError(""); } try { - const [data, tagsData] = await Promise.all([ + const [data, tagsData, rec] = await Promise.all([ fetchJson(`/api/rooms?${query}`), fetchJson("/api/rooms/tags"), + fetchJson("/api/rooms/recommend?limit=8"), ]); setRooms(data.rooms || []); setTotal(Number(data.total) || 0); setAllTags(tagsData.tags || []); + setRecommend(rec.rooms || []); if (!silent) setSelected(new Set()); } catch (e) { if (!silent) setError((e as Error).message); @@ -348,6 +370,53 @@ export default function RoomsPage() {

批量多行添加、标签分组、多选批量操作、一键拉黑。

+ {recommend.length > 0 ? ( +
+
+

高转化房推荐(近14天上传成功率)

+ 可打 tags: shorts / tiktok / shorts_only… +
+
+ {recommend.map((r) => ( +
+
{r.anchor || r.room_id}
+
+ 成功率 {Math.round((r.success_rate || 0) * 100)}% · {r.ok}/{r.total} +
+ {r.suggest_tags?.length ? ( +
+ {r.suggest_tags.map((t) => ( + + ))} +
+ ) : null} +
+ ))} +
+
+ ) : null} +
+
{["收藏", "重点", "竞品", "高优"].map((t) => { const cur = editTags.split(/[,,]/).map((x) => x.trim()).filter(Boolean); diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 5906396..2bfcb0c 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -28,6 +28,7 @@ import { useShortsUpload, type ShortsUploadTarget, } from "@/components/ShortsUploadUx"; +import { UploadTimeline } from "@/components/UploadTimeline"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; import { PageLoader, TableSkeleton } from "@/components/ui"; @@ -1076,6 +1077,17 @@ export default function ShortsPage() {
) : null} + {status?.board?.quota_forecast?.message ? ( +
+ 配额预演:{status.board.quota_forecast.message} +
+ ) : null} {loading && !status ? : null} @@ -1086,7 +1098,7 @@ export default function ShortsPage() {

频道配额({channels.length})

- 按 Client A/B/C/D 分组 · 北京日 {beijingWindow || "—"} · 每频道 9 条/日 + 按 Client A/B/C/D 分组 · 北京日 {beijingWindow || "—"} · 日配额按频道可配
@@ -1225,6 +1237,18 @@ export default function ShortsPage() {

北京 {status?.board?.beijing_hint || "—"} · 按 Client A/B/C/D 分组 · 点击「立即上传」确认后发布

+ {status?.board?.timeline?.hours ? ( +
+ { + const full = upcoming.find((u) => u.id === j.id); + if (full) uploadUx.openConfirm(toUploadTarget(full, channelName)); + }} + /> +
+ ) : null}
{upcoming.length === 0 ? (
diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index 8827028..7dd1d89 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -23,6 +23,7 @@ import { useTikTokUpload, type TikTokUploadTarget, } from "@/components/TikTokUploadUx"; +import { UploadTimeline } from "@/components/UploadTimeline"; import { fetchJson, fmtDuration, fmtTs, todayBeijingISO } from "@/lib/api"; type Channel = { @@ -1251,6 +1252,18 @@ export default function TikTokPage() { 素材 {upcoming.length}
+ {board?.timeline?.hours ? ( +
+ { + const full = upcoming.find((u) => u.id === j.id); + if (full) uploadUx.openConfirm(toUploadTarget(full)); + }} + /> +
+ ) : null}
{upcoming.length === 0 ? (
diff --git a/frontend/src/app/x/XOpsPanels.tsx b/frontend/src/app/x/XOpsPanels.tsx index 6ccb5fa..44355e5 100644 --- a/frontend/src/app/x/XOpsPanels.tsx +++ b/frontend/src/app/x/XOpsPanels.tsx @@ -55,6 +55,7 @@ export function WorkbenchPanel({ lastKind, rerun, likeN, + recentResults, }: Common & { extOnline: boolean; accountsN: number; @@ -63,6 +64,7 @@ export function WorkbenchPanel({ lastKind?: string; rerun: () => void; likeN: number; + recentResults?: Array<{ id: string; kind?: string; status?: string; summary: string }>; }) { return (
@@ -91,6 +93,46 @@ export function WorkbenchPanel({
) : null} + {recentResults && recentResults.length > 0 ? ( +
+
+
+

最近结果

+

完成/失败任务摘要,点进「任务」看详情

+
+ +
+
+ {recentResults.slice(0, 5).map((r) => ( + + ))} +
+
+ ) : null} +
diff --git a/frontend/src/app/x/page.tsx b/frontend/src/app/x/page.tsx index 65e1d24..32fd3a8 100644 --- a/frontend/src/app/x/page.tsx +++ b/frontend/src/app/x/page.tsx @@ -170,6 +170,20 @@ export default function XPage() { return [] as string[]; }, [jobs]); + const recentResults = useMemo( + () => + jobs + .filter((j) => j.status === "completed" || j.status === "failed" || j.status === "cancelled") + .slice(0, 5) + .map((j) => ({ + id: j.id, + kind: kindLabel(j.kind), + status: j.status, + summary: summarizeJob(j), + })), + [jobs], + ); + const active = jobs.find((j) => j.status === "running" || j.status === "queued"); const pct = active ? Math.min( @@ -327,6 +341,7 @@ export default function XPage() { onGo={(id) => setTab(id as TabId)} lastKind={lastJob?.kind} likeN={likeN} + recentResults={recentResults} rerun={() => { if (!lastJob) return toast.push("没有上次任务", "err"); void createJob(lastJob.kind, lastJob.params); diff --git a/frontend/src/components/SessionDetailModal.tsx b/frontend/src/components/SessionDetailModal.tsx index 2adf95e..f7d4386 100644 --- a/frontend/src/components/SessionDetailModal.tsx +++ b/frontend/src/components/SessionDetailModal.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import Link from "next/link"; import { ExternalLink, Loader2, RefreshCw, Square } from "lucide-react"; @@ -27,6 +27,19 @@ export type SessionDetail = { end_reason?: string; }; +type ClipJob = { + id: string; + status?: string; + clip_ready?: boolean; + clip_seconds?: number; + youtube_url?: string; + tiktok_publish_id?: string; + channel_name?: string; + error?: string; + error_class?: string; + upload_at?: number; +}; + type Props = { session: SessionDetail | null; onClose: () => void; @@ -41,10 +54,38 @@ export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: P const [err, setErr] = useState(""); const [local, setLocal] = useState(null); const [zoom, setZoom] = useState(false); + const [shortsJobs, setShortsJobs] = useState([]); + const [tiktokJobs, setTiktokJobs] = useState([]); const current = local && local.id === session?.id ? local : session; const cover = sessionCoverSrc(current || undefined); const isActive = Boolean(current && !current.ended_at); + useEffect(() => { + if (!session?.id) { + setShortsJobs([]); + setTiktokJobs([]); + return; + } + let cancelled = false; + void (async () => { + try { + const data = await fetchJson(`/api/sessions/${session.id}`); + if (cancelled) return; + setShortsJobs((data.shorts_jobs || []) as ClipJob[]); + setTiktokJobs((data.tiktok_jobs || []) as ClipJob[]); + if (data.session) setLocal(data.session as SessionDetail); + } catch { + if (!cancelled) { + setShortsJobs([]); + setTiktokJobs([]); + } + } + })(); + return () => { + cancelled = true; + }; + }, [session?.id]); + async function recapture() { if (!current?.id) return; setBusy("cover"); @@ -54,6 +95,8 @@ export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: P const data = await fetchJson(`/api/sessions/${current.id}`); const next = (data.session || data) as SessionDetail; setLocal(next); + setShortsJobs((data.shorts_jobs || []) as ClipJob[]); + setTiktokJobs((data.tiktok_jobs || []) as ClipJob[]); onUpdated?.(next); } catch (e) { setErr((e as Error).message); @@ -87,6 +130,53 @@ export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: P } } + function renderJobs(platform: "shorts" | "tiktok", jobs: ClipJob[]) { + if (!jobs.length) { + return

暂无成片

; + } + return ( +
    + {jobs.slice(0, 8).map((j) => ( +
  • +
    + {j.status || "—"} + {j.channel_name ? ` · ${j.channel_name}` : ""} + {j.clip_seconds ? ` · ${Math.round(Number(j.clip_seconds))}s` : ""} + {j.error_class ? ` · ${j.error_class}` : ""} +
    +
    + {j.clip_ready ? ( + + 成片 + + ) : null} + + 任务 + + {j.youtube_url ? ( + + YT + + ) : null} +
    +
  • + ))} +
+ ); + } + return ( <> 结束原因
{current.end_reason || "—"}
+
+
Shorts 成片
+
{renderJobs("shorts", shortsJobs)}
+
+
+
TikTok 成片
+
{renderJobs("tiktok", tiktokJobs)}
+
{current.anchor_name ? ( void; +}) { + const rows = hours || []; + if (!rows.length) { + return

暂无排程时间轴

; + } + const max = Math.max(1, ...rows.map((h) => h.count || 0)); + + return ( +
+
+ {rows.map((h) => { + const hgt = Math.max(4, Math.round(((h.count || 0) / max) * 48)); + return ( +
+
+
+
+
+ {h.hour} +
+
+ ); + })} +
+
+ {rows + .flatMap((h) => h.jobs || []) + .slice(0, 24) + .map((j) => ( +
+
+ {j.upload_at ? fmtTs(Number(j.upload_at)) : "—"} + {" · "} + {j.anchor_name || "素材"} + {j.channel_name ? ` · ${j.channel_name}` : ""} +
+ {j.can_upload_now && onUploadNow ? ( + + ) : ( + {j.status || ""} + )} +
+ ))} +
+
+ ); +}