Fix assign auto-fill SQL error and auto-populate slot lists on load.
Remove invalid sessions.platform filter, ensure defaults from Douyin live data when groups load, and make manual fill force-refresh without 500s. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
999ce60ea1
commit
1bd2d299c1
@ -2521,9 +2521,22 @@ async def youtube_manage_playlists(channel_pk: str) -> dict[str, Any]:
|
|||||||
|
|
||||||
@app.get("/api/youtube/assign/groups")
|
@app.get("/api/youtube/assign/groups")
|
||||||
async def yt_assign_list_groups() -> dict[str, Any]:
|
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)}
|
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")
|
@app.post("/api/youtube/assign/groups")
|
||||||
async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]:
|
async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]:
|
||||||
try:
|
try:
|
||||||
@ -2654,11 +2667,6 @@ async def yt_assign_remove_featured(featured_id: str) -> dict[str, Any]:
|
|||||||
raise HTTPException(400, str(exc)) from exc
|
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")
|
@app.post("/api/youtube/assign/groups/{group_id}/slots")
|
||||||
async def yt_assign_add_slots(group_id: str, body: YtAssignSlotAdd) -> dict[str, Any]:
|
async def yt_assign_add_slots(group_id: str, body: YtAssignSlotAdd) -> dict[str, Any]:
|
||||||
ids = list(body.pool_url_ids or [])
|
ids = list(body.pool_url_ids or [])
|
||||||
@ -2697,6 +2705,7 @@ async def yt_assign_auto_fill_group(
|
|||||||
group_id=group_id,
|
group_id=group_id,
|
||||||
limit=int(raw.limit or 24),
|
limit=int(raw.limit or 24),
|
||||||
all_groups=False,
|
all_groups=False,
|
||||||
|
force=bool(raw.force),
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(400, str(exc)) from 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="",
|
group_id="",
|
||||||
limit=int(raw.limit or 24),
|
limit=int(raw.limit or 24),
|
||||||
all_groups=True,
|
all_groups=True,
|
||||||
|
force=bool(raw.force),
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(400, str(exc)) from exc
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|||||||
@ -392,6 +392,7 @@ class YtAssignSlotSet(BaseModel):
|
|||||||
class YtAssignAutoFillBody(BaseModel):
|
class YtAssignAutoFillBody(BaseModel):
|
||||||
limit: int = 24
|
limit: int = 24
|
||||||
all_groups: bool = False
|
all_groups: bool = False
|
||||||
|
force: bool = False
|
||||||
|
|
||||||
|
|
||||||
class YouTubeVideoUpdate(BaseModel):
|
class YouTubeVideoUpdate(BaseModel):
|
||||||
|
|||||||
@ -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,
|
SUM(CASE WHEN ended_at IS NULL THEN (? - started_at) ELSE duration_seconds END) AS dur,
|
||||||
MAX(started_at) AS last_start
|
MAX(started_at) AS last_start
|
||||||
FROM sessions
|
FROM sessions
|
||||||
WHERE platform = 'douyin'
|
WHERE room_id != ''
|
||||||
AND room_id != ''
|
|
||||||
AND room_id NOT LIKE 'yt:%'
|
AND room_id NOT LIKE 'yt:%'
|
||||||
|
AND room_id NOT LIKE 'shorts:%'
|
||||||
AND started_at >= ?
|
AND started_at >= ?
|
||||||
GROUP BY room_id
|
GROUP BY room_id
|
||||||
ORDER BY dur DESC, last_start DESC
|
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
|
live = rid in live_ids
|
||||||
dur = float(row["dur"] or 0)
|
dur = float(row["dur"] or 0)
|
||||||
_push(rid, str(row["anchor_name"] or ""), live=live, score=dur + (1e6 if live else 0))
|
_push(rid, str(row["anchor_name"] or ""), live=live, score=dur + (1e6 if live else 0))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
@ -1309,27 +1311,57 @@ 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."""
|
"""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)))
|
ranked = _rank_douyin_rooms_for_relay(limit=max(8, min(int(limit), 80)))
|
||||||
if not ranked:
|
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)
|
schedule = build_rotation_schedule(include_urls=False)
|
||||||
targets = [c for c in schedule.get("channels") or [] if c.get("group_id")]
|
targets = [c for c in schedule.get("channels") or [] if c.get("group_id")]
|
||||||
if group_id.strip() and not all_groups:
|
if group_id.strip() and not all_groups:
|
||||||
targets = [c for c in targets if str(c.get("group_id") or "") == group_id.strip()]
|
targets = [c for c in targets if str(c.get("group_id") or "") == group_id.strip()]
|
||||||
if not targets:
|
if not targets:
|
||||||
raise ValueError("没有启用的分配分组")
|
return {"ok": True, "filled": 0, "skipped": "no_groups", "schedule": build_rotation_schedule(include_urls=True)}
|
||||||
|
|
||||||
|
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]] = []
|
results: list[dict[str, Any]] = []
|
||||||
gi = 0
|
for gi, tgt in enumerate(targets):
|
||||||
for room in ranked:
|
|
||||||
tgt = targets[gi % len(targets)]
|
|
||||||
gid = str(tgt.get("group_id") or "")
|
gid = str(tgt.get("group_id") or "")
|
||||||
gi += 1
|
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 ''},"
|
line = f"{room['url']},主播: {room.get('title') or room.get('room_id') or ''},"
|
||||||
|
try:
|
||||||
pool_r = add_pool_urls(gid, text=line)
|
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 {}
|
g = pool_r.get("group") or get_group(gid) or {}
|
||||||
pool = g.get("pool") or []
|
pool = g.get("pool") or []
|
||||||
pid = ""
|
pid = ""
|
||||||
@ -1340,8 +1372,12 @@ def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups
|
|||||||
break
|
break
|
||||||
slot_added = 0
|
slot_added = 0
|
||||||
if pid:
|
if pid:
|
||||||
|
try:
|
||||||
sr = add_slot(gid, [pid])
|
sr = add_slot(gid, [pid])
|
||||||
slot_added = int(sr.get("added") or 0)
|
slot_added = int(sr.get("added") or 0)
|
||||||
|
except ValueError:
|
||||||
|
slot_added = 0
|
||||||
|
if slot_added or pool_r.get("added"):
|
||||||
results.append(
|
results.append(
|
||||||
{
|
{
|
||||||
"group_id": gid,
|
"group_id": gid,
|
||||||
@ -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),
|
"schedule": build_rotation_schedule(include_urls=True),
|
||||||
"details": results,
|
"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)
|
||||||
|
|||||||
@ -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;
|
if (!selected && !allGroups) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
const r = allGroups
|
const r = allGroups
|
||||||
? await fetchJson("/api/youtube/assign/schedule/auto-fill", {
|
? await fetchJson("/api/youtube/assign/schedule/auto-fill", {
|
||||||
method: "POST",
|
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`, {
|
: await fetchJson(`/api/youtube/assign/groups/${selected!.id}/slots/auto-fill`, {
|
||||||
method: "POST",
|
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();
|
await loadGroups();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.push((e as Error).message, "err");
|
toast.push((e as Error).message, "err");
|
||||||
@ -732,7 +735,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={() => void autoFillSlots(true)}
|
onClick={() => void autoFillSlots(true, true)}
|
||||||
className="inline-flex items-center gap-1 rounded-lg bg-violet-500/20 px-2.5 py-1 text-[11px] text-violet-100"
|
className="inline-flex items-center gap-1 rounded-lg bg-violet-500/20 px-2.5 py-1 text-[11px] text-violet-100"
|
||||||
>
|
>
|
||||||
<RefreshCw className="h-3 w-3" />
|
<RefreshCw className="h-3 w-3" />
|
||||||
@ -1154,7 +1157,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={() => void autoFillSlots(false)}
|
onClick={() => void autoFillSlots(false, true)}
|
||||||
className="inline-flex items-center gap-1 rounded-lg bg-violet-500/20 px-2 py-1 text-[11px] text-violet-100"
|
className="inline-flex items-center gap-1 rounded-lg bg-violet-500/20 px-2 py-1 text-[11px] text-violet-100"
|
||||||
>
|
>
|
||||||
<RefreshCw className="h-3 w-3" />
|
<RefreshCw className="h-3 w-3" />
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user