diff --git a/backend/app/main.py b/backend/app/main.py index 65a0919..13c462d 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2521,9 +2521,22 @@ async def youtube_manage_playlists(channel_pk: str) -> dict[str, Any]: @app.get("/api/youtube/assign/groups") async def yt_assign_list_groups() -> dict[str, Any]: + try: + yt_assign_db.ensure_default_assign_data() + except Exception: + pass return {"groups": yt_assign_db.list_groups(include_urls=True)} +@app.get("/api/youtube/assign/schedule") +async def yt_assign_schedule() -> dict[str, Any]: + try: + yt_assign_db.ensure_default_assign_data() + except Exception: + pass + return yt_assign_db.build_rotation_schedule(include_urls=True) + + @app.post("/api/youtube/assign/groups") async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]: try: @@ -2654,11 +2667,6 @@ async def yt_assign_remove_featured(featured_id: str) -> dict[str, Any]: raise HTTPException(400, str(exc)) from exc -@app.get("/api/youtube/assign/schedule") -async def yt_assign_schedule() -> dict[str, Any]: - return yt_assign_db.build_rotation_schedule(include_urls=True) - - @app.post("/api/youtube/assign/groups/{group_id}/slots") async def yt_assign_add_slots(group_id: str, body: YtAssignSlotAdd) -> dict[str, Any]: ids = list(body.pool_url_ids or []) @@ -2697,6 +2705,7 @@ async def yt_assign_auto_fill_group( group_id=group_id, limit=int(raw.limit or 24), all_groups=False, + force=bool(raw.force), ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc @@ -2710,6 +2719,7 @@ async def yt_assign_auto_fill_all(body: YtAssignAutoFillBody | None = None) -> d group_id="", limit=int(raw.limit or 24), all_groups=True, + force=bool(raw.force), ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc diff --git a/backend/app/models.py b/backend/app/models.py index 5c49e34..6d031f6 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -392,6 +392,7 @@ class YtAssignSlotSet(BaseModel): class YtAssignAutoFillBody(BaseModel): limit: int = 24 all_groups: bool = False + force: bool = False class YouTubeVideoUpdate(BaseModel): diff --git a/backend/app/yt_assign_db.py b/backend/app/yt_assign_db.py index 3ac6832..27e8b83 100644 --- a/backend/app/yt_assign_db.py +++ b/backend/app/yt_assign_db.py @@ -1224,9 +1224,9 @@ def _rank_douyin_rooms_for_relay(*, limit: int = 40) -> list[dict[str, Any]]: SUM(CASE WHEN ended_at IS NULL THEN (? - started_at) ELSE duration_seconds END) AS dur, MAX(started_at) AS last_start FROM sessions - WHERE platform = 'douyin' - AND room_id != '' + WHERE room_id != '' AND room_id NOT LIKE 'yt:%' + AND room_id NOT LIKE 'shorts:%' AND started_at >= ? GROUP BY room_id ORDER BY dur DESC, last_start DESC @@ -1239,6 +1239,8 @@ def _rank_douyin_rooms_for_relay(*, limit: int = 40) -> list[dict[str, Any]]: live = rid in live_ids dur = float(row["dur"] or 0) _push(rid, str(row["anchor_name"] or ""), live=live, score=dur + (1e6 if live else 0)) + except Exception: + pass finally: conn.close() @@ -1309,50 +1311,84 @@ def build_rotation_schedule(*, include_urls: bool = True) -> dict[str, Any]: } -def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups: bool = False) -> dict[str, Any]: +def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups: bool = False, force: bool = False) -> dict[str, Any]: """Fill slot lists from Douyin live + 24h session stats; round-robin across groups.""" ranked = _rank_douyin_rooms_for_relay(limit=max(8, min(int(limit), 80))) if not ranked: - raise ValueError("暂无可用抖音直播数据") + return {"ok": True, "filled": 0, "skipped": "no_live_data", "schedule": build_rotation_schedule(include_urls=True)} schedule = build_rotation_schedule(include_urls=False) targets = [c for c in schedule.get("channels") or [] if c.get("group_id")] if group_id.strip() and not all_groups: targets = [c for c in targets if str(c.get("group_id") or "") == group_id.strip()] if not targets: - raise ValueError("没有启用的分配分组") + return {"ok": True, "filled": 0, "skipped": "no_groups", "schedule": build_rotation_schedule(include_urls=True)} - results: list[dict[str, Any]] = [] - gi = 0 - for room in ranked: - tgt = targets[gi % len(targets)] - gid = str(tgt.get("group_id") or "") - gi += 1 - line = f"{room['url']},主播: {room.get('title') or room.get('room_id') or ''}," - pool_r = add_pool_urls(gid, text=line) - g = pool_r.get("group") or get_group(gid) or {} - pool = g.get("pool") or [] - pid = "" - key = _dedupe_key(str(room.get("url") or ""), str(room.get("room_id") or "")) - for p in reversed(pool): - if _dedupe_key(str(p.get("url") or ""), str(p.get("room_id") or "")) == key: - pid = str(p.get("id") or "") - break - slot_added = 0 - if pid: - sr = add_slot(gid, [pid]) - slot_added = int(sr.get("added") or 0) - results.append( - { - "group_id": gid, - "group_name": tgt.get("name"), - "room_id": room.get("room_id"), - "title": room.get("title"), - "live": room.get("live"), - "pool_added": len(pool_r.get("added") or []), - "slot_added": slot_added, + if not force: + full_groups = list_groups(include_urls=True) + by_id = {str(g.get("id") or ""): g for g in full_groups} + if group_id.strip() and not all_groups: + g0 = by_id.get(group_id.strip()) + if g0 and (g0.get("slots") or []): + return { + "ok": True, + "filled": 0, + "skipped": "already_has_slots", + "schedule": build_rotation_schedule(include_urls=True), + } + elif all_groups and all((by_id.get(str(t.get("group_id") or "")) or {}).get("slots") for t in targets): + return { + "ok": True, + "filled": 0, + "skipped": "already_has_slots", + "schedule": build_rotation_schedule(include_urls=True), } - ) + else: + by_id = {} + + n_tgt = len(targets) + per = max(1, (len(ranked) + n_tgt - 1) // n_tgt) + results: list[dict[str, Any]] = [] + for gi, tgt in enumerate(targets): + gid = str(tgt.get("group_id") or "") + if not force and by_id.get(gid, {}).get("slots"): + continue + slice_rooms = ranked[gi * per : (gi + 1) * per] + if not slice_rooms and ranked: + slice_rooms = [ranked[gi % len(ranked)]] + for room in slice_rooms: + line = f"{room['url']},主播: {room.get('title') or room.get('room_id') or ''}," + try: + pool_r = add_pool_urls(gid, text=line) + except ValueError: + pool_r = {"group": get_group(gid), "added": []} + g = pool_r.get("group") or get_group(gid) or {} + pool = g.get("pool") or [] + pid = "" + key = _dedupe_key(str(room.get("url") or ""), str(room.get("room_id") or "")) + for p in reversed(pool): + if _dedupe_key(str(p.get("url") or ""), str(p.get("room_id") or "")) == key: + pid = str(p.get("id") or "") + break + slot_added = 0 + if pid: + try: + sr = add_slot(gid, [pid]) + slot_added = int(sr.get("added") or 0) + except ValueError: + slot_added = 0 + if slot_added or pool_r.get("added"): + results.append( + { + "group_id": gid, + "group_name": tgt.get("name"), + "room_id": room.get("room_id"), + "title": room.get("title"), + "live": room.get("live"), + "pool_added": len(pool_r.get("added") or []), + "slot_added": slot_added, + } + ) return { "ok": True, @@ -1360,3 +1396,15 @@ def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups "schedule": build_rotation_schedule(include_urls=True), "details": results, } + + +def ensure_default_assign_data(*, force: bool = False) -> dict[str, Any]: + """Auto-populate empty slot lists from monitor live + session stats (no manual action).""" + groups = [g for g in list_groups(include_urls=True) if g.get("enabled")] + if not groups: + return {"ok": True, "skipped": "no_groups"} + if not force and all((g.get("slots") or []) for g in groups): + return {"ok": True, "skipped": "already_has_slots"} + n = len(groups) + limit = max(12, min(48, n * 6)) + return auto_fill_slots_from_live(all_groups=True, limit=limit, force=force) diff --git a/frontend/src/components/YtAssignPanel.tsx b/frontend/src/components/YtAssignPanel.tsx index ef2b25d..9a1dfae 100644 --- a/frontend/src/components/YtAssignPanel.tsx +++ b/frontend/src/components/YtAssignPanel.tsx @@ -579,20 +579,23 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { } } - async function autoFillSlots(allGroups = false) { + async function autoFillSlots(allGroups = false, force = false) { if (!selected && !allGroups) return; setBusy(true); try { const r = allGroups ? await fetchJson("/api/youtube/assign/schedule/auto-fill", { method: "POST", - body: JSON.stringify({ limit: 24, all_groups: true }), + body: JSON.stringify({ limit: 24, all_groups: true, force }), }) : await fetchJson(`/api/youtube/assign/groups/${selected!.id}/slots/auto-fill`, { method: "POST", - body: JSON.stringify({ limit: 16, all_groups: false }), + body: JSON.stringify({ limit: 16, all_groups: false, force }), }); - toast.push(`已从直播数据填充 ${Number(r?.filled ?? 0)} 条`, "ok"); + const n = Number(r?.filled ?? 0); + const skipped = String(r?.skipped || ""); + if (force && n > 0) toast.push(`已填充 ${n} 条直播源`, "ok"); + else if (force && skipped) toast.push(skipped === "no_live_data" ? "暂无抖音直播数据" : "列表已有数据", "warn"); await loadGroups(); } catch (e) { toast.push((e as Error).message, "err"); @@ -732,7 +735,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {