feat(test1): 时间轴/场次深链/按房时长/盯梢推荐/配额预演/X结果

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 04:59:15 -05:00
parent e08db6aa74
commit b59c39d4b8
21 changed files with 852 additions and 13 deletions

View File

@ -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(

View File

@ -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")

View File

@ -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

View File

@ -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)]

View File

@ -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 = {

View File

@ -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))]}

View File

@ -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"):

View File

@ -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"),
}

View File

@ -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(

View File

@ -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,

View File

@ -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"),
}

View File

@ -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),
}

View File

@ -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)}

View File

@ -69,6 +69,17 @@ export default function AnchorsPage() {
const [error, setError] = useState("");
const [detail, setDetail] = useState<SessionDetail | null>(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 ? <div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div> : null}
{upcoming.length > 0 ? (
<div className="mb-4 rounded-xl border border-amber-500/20 bg-amber-500/5 p-3">
<div className="mb-2 flex items-center justify-between">
<h3 className="text-sm font-medium text-amber-100">盯梢:预计开播窗口</h3>
<span className="text-[11px] text-slate-500">高置信度会推 Webhook</span>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
{upcoming.map((u) => (
<button
key={`${u.anchor_name}-${u.room_id || ""}`}
type="button"
onClick={() => setSelected(u.anchor_name)}
className="rounded-lg border border-white/10 bg-black/25 px-2.5 py-2 text-left text-[11px] hover:border-amber-400/40"
>
<div className="truncate font-medium text-slate-100">
{u.priority ? "★ " : ""}
{u.anchor_name}
</div>
<div className="mt-0.5 text-slate-400">
{u.next_open_hint?.label || fmtTs(u.eta_ts)}
{typeof u.confidence === "number" ? ` · 置信 ${Math.round(u.confidence * 100)}%` : ""}
</div>
</button>
))}
</div>
</div>
) : null}
{!anchors.length && !loading ? (
<EmptyState emoji="🎤" title="还没有主播数据" desc="有开播场次后,这里会自动生成主播排行与画像。" />
) : (

View File

@ -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<Room | null>(null);
const [editNote, setEditNote] = useState("");
const [editTags, setEditTags] = useState("");
const [editClipSec, setEditClipSec] = useState("0");
const [editBusy, setEditBusy] = useState(false);
const [recommend, setRecommend] = useState<RecommendRoom[]>([]);
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() {
<p className="text-sm text-slate-400">批量多行添加、标签分组、多选批量操作、一键拉黑。</p>
</div>
{recommend.length > 0 ? (
<div className="mb-4 rounded-xl border border-teal-500/20 bg-teal-500/5 p-3">
<div className="mb-2 flex items-center justify-between gap-2">
<h3 className="text-sm font-medium text-teal-100">高转化房推荐(近14天上传成功率)</h3>
<span className="text-[11px] text-slate-500">可打 tags: shorts / tiktok / shorts_only…</span>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
{recommend.map((r) => (
<div key={r.room_id} className="rounded-lg border border-white/10 bg-black/25 px-2.5 py-2 text-[11px]">
<div className="truncate font-medium text-slate-100">{r.anchor || r.room_id}</div>
<div className="mt-0.5 text-slate-400">
成功率 {Math.round((r.success_rate || 0) * 100)}% · {r.ok}/{r.total}
</div>
{r.suggest_tags?.length ? (
<div className="mt-1 flex flex-wrap gap-1">
{r.suggest_tags.map((t) => (
<button
key={t}
type="button"
className="rounded border border-teal-500/30 bg-teal-500/10 px-1.5 py-0.5 text-teal-100"
onClick={async () => {
if (!r.room_pk) return;
try {
const cur = (r.tags || []).join(",");
const next = [...new Set([...(r.tags || []), t])].join(",");
await fetchJson(`/api/rooms/${r.room_pk}`, {
method: "PATCH",
body: JSON.stringify({ tags: next || cur }),
});
toast.push(`已加标签 ${t}`, "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "err");
}
}}
>
+{t}
</button>
))}
</div>
) : null}
</div>
))}
</div>
</div>
) : null}
<div className="mb-4 space-y-3 rounded-xl border border-white/10 bg-black/30 p-4">
<label className="block text-xs text-slate-400">
直播间 URL / 房间号(每行一个)
@ -595,6 +664,17 @@ export default function RoomsPage() {
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
成片时长覆盖(秒,0=用全局默认;TikTok 最少 60)
<input
type="number"
min={0}
max={120}
value={editClipSec}
onChange={(e) => setEditClipSec(e.target.value)}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<div className="flex flex-wrap gap-2">
{["收藏", "重点", "竞品", "高优"].map((t) => {
const cur = editTags.split(/[,,]/).map((x) => x.trim()).filter(Boolean);

View File

@ -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() {
</div>
</div>
) : null}
{status?.board?.quota_forecast?.message ? (
<div
className={`mb-3 rounded-xl border px-3 py-2.5 text-xs ${
status.board.quota_forecast.warn
? "border-amber-500/30 bg-amber-500/10 text-amber-50"
: "border-white/10 bg-white/5 text-slate-300"
}`}
>
配额预演:{status.board.quota_forecast.message}
</div>
) : null}
{loading && !status ? <PageLoader label="加载 Shorts 分发台…" /> : null}
@ -1086,7 +1098,7 @@ export default function ShortsPage() {
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="text-sm font-medium text-slate-100">频道配额({channels.length})</h3>
<span className="text-[11px] text-slate-500">
按 Client A/B/C/D 分组 · 北京日 {beijingWindow || "—"} · 每频道 9 条/日
按 Client A/B/C/D 分组 · 北京日 {beijingWindow || "—"} · 日配额按频道可配
</span>
</div>
<div className="space-y-4">
@ -1225,6 +1237,18 @@ export default function ShortsPage() {
<p className="mb-3 shrink-0 text-[11px] text-slate-500">
北京 {status?.board?.beijing_hint || "—"} · 按 Client A/B/C/D 分组 · 点击「立即上传」确认后发布
</p>
{status?.board?.timeline?.hours ? (
<div className="mb-3 shrink-0 rounded-xl border border-white/5 bg-black/20 p-2.5">
<UploadTimeline
hours={status.board.timeline.hours}
nowHour={status.board.timeline.now_hour}
onUploadNow={(j) => {
const full = upcoming.find((u) => u.id === j.id);
if (full) uploadUx.openConfirm(toUploadTarget(full, channelName));
}}
/>
</div>
) : null}
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto pr-1">
{upcoming.length === 0 ? (
<div className="rounded-xl border border-dashed border-white/10 px-3 py-8 text-center text-sm text-slate-500">

View File

@ -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}
</span>
</div>
{board?.timeline?.hours ? (
<div className="mb-3 shrink-0 rounded-xl border border-white/5 bg-black/20 p-2.5">
<UploadTimeline
hours={board.timeline.hours}
nowHour={board.timeline.now_hour}
onUploadNow={(j) => {
const full = upcoming.find((u) => u.id === j.id);
if (full) uploadUx.openConfirm(toUploadTarget(full));
}}
/>
</div>
) : null}
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto pr-1">
{upcoming.length === 0 ? (
<div className="rounded-xl border border-dashed border-white/10 py-8 text-center text-sm text-slate-500">

View File

@ -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 (
<div className="space-y-4">
@ -91,6 +93,46 @@ export function WorkbenchPanel({
</div>
) : null}
{recentResults && recentResults.length > 0 ? (
<div className={panel}>
<div className="mb-2 flex items-center justify-between">
<div>
<h3 className={title}>最近结果</h3>
<p className={sub}>完成/失败任务摘要,点进「任务」看详情</p>
</div>
<button type="button" className={ghost} onClick={() => onGo("jobs")}>
全部任务
</button>
</div>
<div className="space-y-2">
{recentResults.slice(0, 5).map((r) => (
<button
key={r.id}
type="button"
className="w-full rounded-xl border border-white/10 bg-black/35 px-3 py-2 text-left hover:border-orange-400/30"
onClick={() => onGo("jobs")}
>
<div className="flex items-center justify-between gap-2 text-[11px]">
<span className="font-medium text-slate-100">{r.kind || "任务"}</span>
<span
className={
r.status === "completed"
? "text-emerald-300"
: r.status === "failed"
? "text-rose-300"
: "text-slate-400"
}
>
{r.status || ""}
</span>
</div>
<div className="mt-1 line-clamp-2 text-[11px] text-slate-400">{r.summary}</div>
</button>
))}
</div>
</div>
) : null}
<div className={panel}>
<div className="mb-3 flex items-start justify-between gap-2">
<div>

View File

@ -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);

View File

@ -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<SessionDetail | null>(null);
const [zoom, setZoom] = useState(false);
const [shortsJobs, setShortsJobs] = useState<ClipJob[]>([]);
const [tiktokJobs, setTiktokJobs] = useState<ClipJob[]>([]);
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 <p className="text-xs text-slate-600">暂无成片</p>;
}
return (
<ul className="space-y-1.5">
{jobs.slice(0, 8).map((j) => (
<li
key={j.id}
className="flex items-center justify-between gap-2 rounded-lg border border-white/5 bg-black/25 px-2 py-1.5 text-[11px]"
>
<div className="min-w-0 truncate text-slate-300">
<span className="text-slate-500">{j.status || "—"}</span>
{j.channel_name ? ` · ${j.channel_name}` : ""}
{j.clip_seconds ? ` · ${Math.round(Number(j.clip_seconds))}s` : ""}
{j.error_class ? ` · ${j.error_class}` : ""}
</div>
<div className="flex shrink-0 gap-1">
{j.clip_ready ? (
<a
href={`/api/${platform}/jobs/${j.id}/clip`}
target="_blank"
rel="noreferrer"
className="rounded bg-white/5 px-1.5 py-0.5 text-teal-200 hover:bg-white/10"
>
成片
</a>
) : null}
<Link
href={platform === "shorts" ? `/shorts?job=${j.id}` : `/tiktok?job=${j.id}`}
className="rounded bg-white/5 px-1.5 py-0.5 text-sky-200 hover:bg-white/10"
onClick={onClose}
>
任务
</Link>
{j.youtube_url ? (
<a href={j.youtube_url} target="_blank" rel="noreferrer" className="rounded bg-white/5 px-1.5 py-0.5 text-rose-200">
YT
</a>
) : null}
</div>
</li>
))}
</ul>
);
}
return (
<>
<Modal
@ -211,6 +301,14 @@ export function SessionDetailModal({ session, onClose, onUpdated, extraRows }: P
<dt className="text-slate-500">结束原因</dt>
<dd>{current.end_reason || "—"}</dd>
</div>
<div>
<dt className="mb-1 text-slate-500">Shorts 成片</dt>
<dd>{renderJobs("shorts", shortsJobs)}</dd>
</div>
<div>
<dt className="mb-1 text-slate-500">TikTok 成片</dt>
<dd>{renderJobs("tiktok", tiktokJobs)}</dd>
</div>
<div className="flex flex-wrap gap-2 pt-1">
{current.anchor_name ? (
<Link

View File

@ -0,0 +1,92 @@
"use client";
import { fmtTs } from "@/lib/api";
export type TimelineJob = {
id: string;
upload_at?: number;
status?: string;
anchor_name?: string;
channel_name?: string;
clip_ready?: boolean;
can_upload_now?: boolean;
};
export type TimelineHour = {
hour: number;
label: string;
count: number;
is_past?: boolean;
is_current?: boolean;
jobs: TimelineJob[];
};
export function UploadTimeline({
hours,
nowHour,
onUploadNow,
}: {
hours?: TimelineHour[];
nowHour?: number;
onUploadNow?: (job: TimelineJob) => void;
}) {
const rows = hours || [];
if (!rows.length) {
return <p className="text-xs text-slate-500">暂无排程时间轴</p>;
}
const max = Math.max(1, ...rows.map((h) => h.count || 0));
return (
<div className="space-y-2">
<div className="flex gap-0.5 overflow-x-auto pb-1">
{rows.map((h) => {
const hgt = Math.max(4, Math.round(((h.count || 0) / max) * 48));
return (
<div key={h.hour} className="flex w-5 shrink-0 flex-col items-center gap-1" title={`${h.label} · ${h.count} 条`}>
<div className="flex h-12 w-full items-end justify-center">
<div
className={`w-2 rounded-sm ${
h.is_current ? "bg-pink-400" : h.is_past ? "bg-white/20" : "bg-teal-400/70"
}`}
style={{ height: `${hgt}px` }}
/>
</div>
<div className={`text-[9px] ${(nowHour ?? -1) === h.hour ? "text-pink-300" : "text-slate-600"}`}>
{h.hour}
</div>
</div>
);
})}
</div>
<div className="max-h-40 space-y-1 overflow-y-auto">
{rows
.flatMap((h) => h.jobs || [])
.slice(0, 24)
.map((j) => (
<div
key={j.id}
className="flex items-center justify-between gap-2 rounded-lg border border-white/5 bg-black/20 px-2 py-1.5 text-[11px]"
>
<div className="min-w-0 truncate text-slate-300">
<span className="text-slate-500">{j.upload_at ? fmtTs(Number(j.upload_at)) : "—"}</span>
{" · "}
{j.anchor_name || "素材"}
{j.channel_name ? ` · ${j.channel_name}` : ""}
</div>
{j.can_upload_now && onUploadNow ? (
<button
type="button"
onClick={() => onUploadNow(j)}
className="shrink-0 rounded bg-pink-500/20 px-2 py-0.5 text-[10px] text-pink-200"
>
立即
</button>
) : (
<span className="shrink-0 text-slate-600">{j.status || ""}</span>
)}
</div>
))}
</div>
</div>
);
}