Add YouTube assign time-slot rotation and fix channel card layout.
24h Beijing channel rotation with slot list, live-data auto-fill, and compact sidebar cards for /youtube assign. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
a9c0af5f36
commit
999ce60ea1
@ -57,6 +57,9 @@ from .models import (
|
||||
YouTubeVideoUpdate,
|
||||
YtAssignFeaturedAdd,
|
||||
YtAssignFeaturedSet,
|
||||
YtAssignSlotAdd,
|
||||
YtAssignSlotSet,
|
||||
YtAssignAutoFillBody,
|
||||
YtAssignGroupCreate,
|
||||
YtAssignGroupUpdate,
|
||||
YtAssignPoolAdd,
|
||||
@ -2651,6 +2654,67 @@ 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 [])
|
||||
if body.pool_url_id and str(body.pool_url_id).strip():
|
||||
ids.append(str(body.pool_url_id).strip())
|
||||
try:
|
||||
return yt_assign_db.add_slot(group_id, ids)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.put("/api/youtube/assign/groups/{group_id}/slots")
|
||||
async def yt_assign_set_slots(group_id: str, body: YtAssignSlotSet) -> dict[str, Any]:
|
||||
try:
|
||||
return yt_assign_db.set_slot_order(group_id, body.pool_url_ids or [])
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.delete("/api/youtube/assign/slots/{slot_id}")
|
||||
async def yt_assign_remove_slot(slot_id: str) -> dict[str, Any]:
|
||||
try:
|
||||
return yt_assign_db.remove_slot(slot_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.post("/api/youtube/assign/groups/{group_id}/slots/auto-fill")
|
||||
async def yt_assign_auto_fill_group(
|
||||
group_id: str,
|
||||
body: YtAssignAutoFillBody | None = None,
|
||||
) -> dict[str, Any]:
|
||||
raw = body or YtAssignAutoFillBody()
|
||||
try:
|
||||
return yt_assign_db.auto_fill_slots_from_live(
|
||||
group_id=group_id,
|
||||
limit=int(raw.limit or 24),
|
||||
all_groups=False,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.post("/api/youtube/assign/schedule/auto-fill")
|
||||
async def yt_assign_auto_fill_all(body: YtAssignAutoFillBody | None = None) -> dict[str, Any]:
|
||||
raw = body or YtAssignAutoFillBody()
|
||||
try:
|
||||
return yt_assign_db.auto_fill_slots_from_live(
|
||||
group_id="",
|
||||
limit=int(raw.limit or 24),
|
||||
all_groups=True,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/youtube/resolve")
|
||||
async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]:
|
||||
try:
|
||||
|
||||
@ -380,6 +380,20 @@ class YtAssignFeaturedSet(BaseModel):
|
||||
pool_url_ids: list[str] = []
|
||||
|
||||
|
||||
class YtAssignSlotAdd(BaseModel):
|
||||
pool_url_ids: list[str] = []
|
||||
pool_url_id: str = ""
|
||||
|
||||
|
||||
class YtAssignSlotSet(BaseModel):
|
||||
pool_url_ids: list[str] = []
|
||||
|
||||
|
||||
class YtAssignAutoFillBody(BaseModel):
|
||||
limit: int = 24
|
||||
all_groups: bool = False
|
||||
|
||||
|
||||
class YouTubeVideoUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
@ -61,6 +61,18 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None:
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS yt_assign_slot_urls (
|
||||
id TEXT PRIMARY KEY,
|
||||
group_id TEXT NOT NULL,
|
||||
pool_url_id TEXT NOT NULL,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at REAL NOT NULL,
|
||||
UNIQUE(group_id, pool_url_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
cols = {str(r[1]) for r in conn.execute("PRAGMA table_info(yt_assign_pool_urls)").fetchall()}
|
||||
for col, ddl in [
|
||||
("title", "TEXT NOT NULL DEFAULT ''"),
|
||||
@ -79,7 +91,7 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None:
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_assign_groups_channel ON yt_assign_groups(channel_pk)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_assign_pool_room ON yt_assign_pool_urls(room_id)"
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_assign_slot_group ON yt_assign_slot_urls(group_id, sort_order)"
|
||||
)
|
||||
|
||||
|
||||
@ -195,7 +207,24 @@ def _normalize_url(url: str) -> str:
|
||||
return normalize_room_url(str(url or "").strip()) or str(url or "").strip()
|
||||
|
||||
|
||||
def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: list | None = None) -> dict[str, Any]:
|
||||
def _fmt_hour(h: float) -> str:
|
||||
h = float(h) % 24.0
|
||||
hh = int(h)
|
||||
mm = int(round((h - hh) * 60))
|
||||
if mm >= 60:
|
||||
hh = (hh + 1) % 24
|
||||
mm = 0
|
||||
return f"{hh:02d}:{mm:02d}"
|
||||
|
||||
|
||||
def _beijing_hour_fraction(ts: float | None = None) -> float:
|
||||
from .timeutil import beijing_from_ts
|
||||
|
||||
dt = beijing_from_ts(ts if ts is not None else time.time())
|
||||
return dt.hour + dt.minute / 60.0 + dt.second / 3600.0
|
||||
|
||||
|
||||
def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: list | None = None, slots: list | None = None) -> dict[str, Any]:
|
||||
out = dict(row)
|
||||
out["enabled"] = bool(out.get("enabled"))
|
||||
sk = str(out.get("stream_key") or "")
|
||||
@ -205,9 +234,22 @@ def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: li
|
||||
out["pool"] = pool
|
||||
if featured is not None:
|
||||
out["featured"] = featured
|
||||
if slots is not None:
|
||||
out["slots"] = slots
|
||||
return out
|
||||
|
||||
|
||||
def _slot_select_sql() -> str:
|
||||
return """
|
||||
SELECT s.*, p.url AS url, p.note AS pool_note, p.title AS title,
|
||||
p.room_id AS room_id, p.cover_url AS cover_url
|
||||
FROM yt_assign_slot_urls s
|
||||
LEFT JOIN yt_assign_pool_urls p ON p.id = s.pool_url_id
|
||||
WHERE s.group_id = ?
|
||||
ORDER BY s.sort_order ASC, s.created_at ASC
|
||||
"""
|
||||
|
||||
|
||||
def _feat_select_sql() -> str:
|
||||
return """
|
||||
SELECT f.*, p.url AS url, p.note AS pool_note, p.title AS title,
|
||||
@ -231,7 +273,7 @@ def list_groups(*, include_urls: bool = True) -> list[dict[str, Any]]:
|
||||
for r in rows:
|
||||
g = _row_to_dict(r) # type: ignore
|
||||
if not include_urls:
|
||||
out.append(_public_group(g, pool=[], featured=[]))
|
||||
out.append(_public_group(g, pool=[], featured=[], slots=[]))
|
||||
continue
|
||||
gid = str(g.get("id") or "")
|
||||
pool_rows = conn.execute(
|
||||
@ -241,7 +283,9 @@ def list_groups(*, include_urls: bool = True) -> list[dict[str, Any]]:
|
||||
pool = [_enrich_pool_row(conn, _row_to_dict(x) or {}) for x in pool_rows]
|
||||
feat_rows = conn.execute(_feat_select_sql(), (gid,)).fetchall()
|
||||
featured = [_enrich_pool_row(conn, _row_to_dict(x) or {}) for x in feat_rows]
|
||||
out.append(_public_group(g, pool=pool, featured=featured))
|
||||
slot_rows = conn.execute(_slot_select_sql(), (gid,)).fetchall()
|
||||
slots = [_enrich_pool_row(conn, _row_to_dict(x) or {}) for x in slot_rows]
|
||||
out.append(_public_group(g, pool=pool, featured=featured, slots=slots))
|
||||
return out
|
||||
finally:
|
||||
conn.close()
|
||||
@ -268,7 +312,11 @@ def get_group(group_id: str) -> dict[str, Any] | None:
|
||||
_enrich_pool_row(conn, _row_to_dict(x) or {})
|
||||
for x in conn.execute(_feat_select_sql(), (gid,)).fetchall()
|
||||
]
|
||||
return _public_group(g, pool=pool, featured=featured) # type: ignore
|
||||
slots = [
|
||||
_enrich_pool_row(conn, _row_to_dict(x) or {})
|
||||
for x in conn.execute(_slot_select_sql(), (gid,)).fetchall()
|
||||
]
|
||||
return _public_group(g, pool=pool, featured=featured, slots=slots) # type: ignore
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@ -406,6 +454,7 @@ def delete_group(group_id: str) -> dict[str, Any]:
|
||||
try:
|
||||
ensure_yt_assign_tables(conn)
|
||||
conn.execute("DELETE FROM yt_assign_featured_urls WHERE group_id = ?", (group_id,))
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE group_id = ?", (group_id,))
|
||||
n_pool = conn.execute("DELETE FROM yt_assign_pool_urls WHERE group_id = ?", (group_id,)).rowcount
|
||||
n = conn.execute("DELETE FROM yt_assign_groups WHERE id = ?", (group_id,)).rowcount
|
||||
conn.commit()
|
||||
@ -610,6 +659,7 @@ def delete_pool_url(pool_url_id: str) -> dict[str, Any]:
|
||||
raise ValueError("URL 不存在")
|
||||
gid = str(row["group_id"])
|
||||
conn.execute("DELETE FROM yt_assign_featured_urls WHERE pool_url_id = ?", (pool_url_id,))
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE pool_url_id = ?", (pool_url_id,))
|
||||
conn.execute("DELETE FROM yt_assign_pool_urls WHERE id = ?", (pool_url_id,))
|
||||
conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (time.time(), gid))
|
||||
conn.commit()
|
||||
@ -715,6 +765,7 @@ def dedupe_group(group_id: str) -> dict[str, Any]:
|
||||
now = time.time()
|
||||
pool_removed = 0
|
||||
feat_removed = 0
|
||||
slot_removed = 0
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
@ -740,6 +791,7 @@ def dedupe_group(group_id: str) -> dict[str, Any]:
|
||||
seen.add(key)
|
||||
for pid in drop_pool:
|
||||
conn.execute("DELETE FROM yt_assign_featured_urls WHERE pool_url_id = ?", (pid,))
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE pool_url_id = ?", (pid,))
|
||||
conn.execute("DELETE FROM yt_assign_pool_urls WHERE id = ?", (pid,))
|
||||
pool_removed += 1
|
||||
# featured room_id dedupe (keep earliest featured)
|
||||
@ -761,6 +813,26 @@ def dedupe_group(group_id: str) -> dict[str, Any]:
|
||||
feat_removed += 1
|
||||
else:
|
||||
fseen.add(key)
|
||||
# slot room_id dedupe
|
||||
slot_removed = 0
|
||||
srows = conn.execute(
|
||||
"""
|
||||
SELECT s.id AS sid, p.url, p.room_id
|
||||
FROM yt_assign_slot_urls s
|
||||
JOIN yt_assign_pool_urls p ON p.id = s.pool_url_id
|
||||
WHERE s.group_id = ?
|
||||
ORDER BY s.sort_order ASC, s.created_at ASC
|
||||
""",
|
||||
(group_id,),
|
||||
).fetchall()
|
||||
sseen: set[str] = set()
|
||||
for r in srows:
|
||||
key = _dedupe_key(str(r["url"] or ""), str(r["room_id"] or ""))
|
||||
if key in sseen:
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE id = ?", (str(r["sid"]),))
|
||||
slot_removed += 1
|
||||
else:
|
||||
sseen.add(key)
|
||||
conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (now, group_id))
|
||||
conn.commit()
|
||||
finally:
|
||||
@ -769,6 +841,7 @@ def dedupe_group(group_id: str) -> dict[str, Any]:
|
||||
"ok": True,
|
||||
"pool_removed": pool_removed,
|
||||
"featured_removed": feat_removed,
|
||||
"slot_removed": slot_removed,
|
||||
"group": get_group(group_id),
|
||||
}
|
||||
|
||||
@ -801,6 +874,20 @@ def purge_blacklisted(group_id: str, *, from_pool: bool = True, from_featured: b
|
||||
if _is_blacklisted_conn(conn, str(r["room_id"] or ""), str(r["url"] or "")):
|
||||
conn.execute("DELETE FROM yt_assign_featured_urls WHERE id = ?", (str(r["fid"]),))
|
||||
feat_removed += 1
|
||||
slot_removed = 0
|
||||
srows = conn.execute(
|
||||
"""
|
||||
SELECT s.id AS sid, p.url, p.room_id
|
||||
FROM yt_assign_slot_urls s
|
||||
JOIN yt_assign_pool_urls p ON p.id = s.pool_url_id
|
||||
WHERE s.group_id = ?
|
||||
""",
|
||||
(group_id,),
|
||||
).fetchall()
|
||||
for r in srows:
|
||||
if _is_blacklisted_conn(conn, str(r["room_id"] or ""), str(r["url"] or "")):
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE id = ?", (str(r["sid"]),))
|
||||
slot_removed += 1
|
||||
if from_pool:
|
||||
prows = conn.execute(
|
||||
"SELECT id, url, room_id FROM yt_assign_pool_urls WHERE group_id = ?",
|
||||
@ -809,6 +896,7 @@ def purge_blacklisted(group_id: str, *, from_pool: bool = True, from_featured: b
|
||||
for r in prows:
|
||||
if _is_blacklisted_conn(conn, str(r["room_id"] or ""), str(r["url"] or "")):
|
||||
conn.execute("DELETE FROM yt_assign_featured_urls WHERE pool_url_id = ?", (str(r["id"]),))
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE pool_url_id = ?", (str(r["id"]),))
|
||||
conn.execute("DELETE FROM yt_assign_pool_urls WHERE id = ?", (str(r["id"]),))
|
||||
pool_removed += 1
|
||||
conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (now, group_id))
|
||||
@ -819,6 +907,7 @@ def purge_blacklisted(group_id: str, *, from_pool: bool = True, from_featured: b
|
||||
"ok": True,
|
||||
"pool_removed": pool_removed,
|
||||
"featured_removed": feat_removed,
|
||||
"slot_removed": slot_removed,
|
||||
"group": get_group(group_id),
|
||||
}
|
||||
|
||||
@ -926,3 +1015,348 @@ def set_featured_order(group_id: str, pool_url_ids: list[str]) -> dict[str, Any]
|
||||
finally:
|
||||
conn.close()
|
||||
return {"ok": True, "group": get_group(group_id)}
|
||||
|
||||
|
||||
def add_slot(group_id: str, pool_url_ids: list[str]) -> dict[str, Any]:
|
||||
"""Add pool URLs to time-slot rotation list (must be in pool)."""
|
||||
from .db import _is_blacklisted_conn
|
||||
|
||||
ids = [str(x).strip() for x in pool_url_ids if str(x).strip()]
|
||||
if not ids:
|
||||
raise ValueError("未选择普通列表 URL")
|
||||
seen_ids: set[str] = set()
|
||||
uniq_ids: list[str] = []
|
||||
for pid in ids:
|
||||
if pid in seen_ids:
|
||||
continue
|
||||
seen_ids.add(pid)
|
||||
uniq_ids.append(pid)
|
||||
now = time.time()
|
||||
added = 0
|
||||
skipped_dup = 0
|
||||
skipped_blacklist: list[dict[str, str]] = []
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_assign_tables(conn)
|
||||
g = conn.execute("SELECT id FROM yt_assign_groups WHERE id = ?", (group_id,)).fetchone()
|
||||
if not g:
|
||||
raise ValueError("分组不存在")
|
||||
max_ord = conn.execute(
|
||||
"SELECT COALESCE(MAX(sort_order), 0) AS m FROM yt_assign_slot_urls WHERE group_id = ?",
|
||||
(group_id,),
|
||||
).fetchone()
|
||||
ord0 = int(max_ord["m"] if max_ord else 0)
|
||||
slot_room_keys: set[str] = set()
|
||||
for r in conn.execute(
|
||||
"""
|
||||
SELECT p.url, p.room_id FROM yt_assign_slot_urls s
|
||||
JOIN yt_assign_pool_urls p ON p.id = s.pool_url_id
|
||||
WHERE s.group_id = ?
|
||||
""",
|
||||
(group_id,),
|
||||
).fetchall():
|
||||
slot_room_keys.add(_dedupe_key(str(r["url"] or ""), str(r["room_id"] or "")))
|
||||
for pid in uniq_ids:
|
||||
pool = conn.execute(
|
||||
"SELECT * FROM yt_assign_pool_urls WHERE id = ? AND group_id = ?",
|
||||
(pid, group_id),
|
||||
).fetchone()
|
||||
if not pool:
|
||||
continue
|
||||
exists = conn.execute(
|
||||
"SELECT 1 FROM yt_assign_slot_urls WHERE group_id = ? AND pool_url_id = ?",
|
||||
(group_id, pid),
|
||||
).fetchone()
|
||||
if exists:
|
||||
skipped_dup += 1
|
||||
continue
|
||||
key = _dedupe_key(str(pool["url"] or ""), str(pool["room_id"] or ""))
|
||||
if key in slot_room_keys:
|
||||
skipped_dup += 1
|
||||
continue
|
||||
hit = _is_blacklisted_conn(conn, str(pool["room_id"] or ""), str(pool["url"] or ""))
|
||||
if hit:
|
||||
skipped_blacklist.append(
|
||||
{
|
||||
"url": str(pool["url"] or ""),
|
||||
"title": str(pool["title"] or ""),
|
||||
"reason": str(hit.get("reason") or hit.get("value") or "黑名单"),
|
||||
}
|
||||
)
|
||||
continue
|
||||
ord0 += 1
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO yt_assign_slot_urls(id, group_id, pool_url_id, sort_order, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(str(uuid.uuid4()), group_id, pid, ord0, now),
|
||||
)
|
||||
slot_room_keys.add(key)
|
||||
added += 1
|
||||
conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (now, group_id))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"ok": True,
|
||||
"added": added,
|
||||
"skipped_dup": skipped_dup,
|
||||
"skipped_blacklist": skipped_blacklist,
|
||||
"group": get_group(group_id),
|
||||
}
|
||||
|
||||
|
||||
def remove_slot(slot_id: str) -> dict[str, Any]:
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_assign_tables(conn)
|
||||
row = conn.execute(
|
||||
"SELECT group_id FROM yt_assign_slot_urls WHERE id = ?",
|
||||
(slot_id,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise ValueError("时间段项不存在")
|
||||
gid = str(row["group_id"])
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE id = ?", (slot_id,))
|
||||
conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (time.time(), gid))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {"ok": True, "group": get_group(gid)}
|
||||
|
||||
|
||||
def set_slot_order(group_id: str, pool_url_ids: list[str]) -> dict[str, Any]:
|
||||
"""Replace slot list order with given pool_url_ids."""
|
||||
from .db import _is_blacklisted_conn
|
||||
|
||||
ids = [str(x).strip() for x in pool_url_ids if str(x).strip()]
|
||||
seen_ids: set[str] = set()
|
||||
uniq: list[str] = []
|
||||
for pid in ids:
|
||||
if pid in seen_ids:
|
||||
continue
|
||||
seen_ids.add(pid)
|
||||
uniq.append(pid)
|
||||
now = time.time()
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_assign_tables(conn)
|
||||
g = conn.execute("SELECT id FROM yt_assign_groups WHERE id = ?", (group_id,)).fetchone()
|
||||
if not g:
|
||||
raise ValueError("分组不存在")
|
||||
conn.execute("DELETE FROM yt_assign_slot_urls WHERE group_id = ?", (group_id,))
|
||||
room_seen: set[str] = set()
|
||||
ord_i = 0
|
||||
for pid in uniq:
|
||||
pool = conn.execute(
|
||||
"SELECT * FROM yt_assign_pool_urls WHERE id = ? AND group_id = ?",
|
||||
(pid, group_id),
|
||||
).fetchone()
|
||||
if not pool:
|
||||
continue
|
||||
key = _dedupe_key(str(pool["url"] or ""), str(pool["room_id"] or ""))
|
||||
if key in room_seen:
|
||||
continue
|
||||
if _is_blacklisted_conn(conn, str(pool["room_id"] or ""), str(pool["url"] or "")):
|
||||
continue
|
||||
room_seen.add(key)
|
||||
ord_i += 1
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO yt_assign_slot_urls(id, group_id, pool_url_id, sort_order, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(str(uuid.uuid4()), group_id, pid, ord_i, now),
|
||||
)
|
||||
conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (now, group_id))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {"ok": True, "group": get_group(group_id)}
|
||||
|
||||
|
||||
def _rank_douyin_rooms_for_relay(*, limit: int = 40) -> list[dict[str, Any]]:
|
||||
"""Rank Douyin rooms: live first, then by recent 24h session duration."""
|
||||
from . import db
|
||||
from .timeutil import beijing_day_bounds
|
||||
|
||||
live_rows = db.list_live_douyin_rooms_for_shorts(limit=limit)
|
||||
live_ids = {str(r.get("room_id") or "").strip() for r in live_rows if r.get("room_id")}
|
||||
day_start, _ = beijing_day_bounds()
|
||||
ranked: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def _push(room_id: str, anchor: str, *, live: bool, score: float) -> None:
|
||||
rid = str(room_id or "").strip()
|
||||
if not rid or rid in seen or rid.startswith("yt:"):
|
||||
return
|
||||
seen.add(rid)
|
||||
url = normalize_room_url(rid) or f"https://live.douyin.com/{rid}"
|
||||
ranked.append(
|
||||
{
|
||||
"room_id": rid,
|
||||
"url": url,
|
||||
"title": str(anchor or "").strip(),
|
||||
"live": live,
|
||||
"score": score,
|
||||
}
|
||||
)
|
||||
|
||||
for r in live_rows:
|
||||
_push(
|
||||
str(r.get("room_id") or ""),
|
||||
str(r.get("last_anchor") or r.get("last_title") or ""),
|
||||
live=True,
|
||||
score=1e9 + float(r.get("last_checked_at") or 0),
|
||||
)
|
||||
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT room_id,
|
||||
MAX(anchor_name) AS anchor_name,
|
||||
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 != ''
|
||||
AND room_id NOT LIKE 'yt:%'
|
||||
AND started_at >= ?
|
||||
GROUP BY room_id
|
||||
ORDER BY dur DESC, last_start DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(time.time(), day_start, max(limit * 3, limit)),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
rid = str(row["room_id"] or "")
|
||||
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))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
ranked.sort(key=lambda x: float(x.get("score") or 0), reverse=True)
|
||||
return ranked[: max(1, limit)]
|
||||
|
||||
|
||||
def build_rotation_schedule(*, include_urls: bool = True) -> dict[str, Any]:
|
||||
"""24h Beijing rotation: N channels → 24/N hours each, no overlap."""
|
||||
groups = [g for g in list_groups(include_urls=include_urls) if g.get("enabled")]
|
||||
n = len(groups)
|
||||
now_h = _beijing_hour_fraction()
|
||||
if n == 0:
|
||||
return {
|
||||
"ok": True,
|
||||
"channel_count": 0,
|
||||
"slot_hours": 0,
|
||||
"now_hour": round(now_h, 3),
|
||||
"now_label": _fmt_hour(now_h),
|
||||
"channels": [],
|
||||
}
|
||||
slot_h = 24.0 / n
|
||||
channels: list[dict[str, Any]] = []
|
||||
for i, g in enumerate(groups):
|
||||
start_h = i * slot_h
|
||||
end_h = (i + 1) * slot_h
|
||||
active = start_h <= now_h < end_h if end_h <= 24 else (now_h >= start_h or now_h < (end_h % 24))
|
||||
slots_raw = list(g.get("slots") or [])
|
||||
m = len(slots_raw)
|
||||
sub_h = slot_h / m if m else 0.0
|
||||
slot_items: list[dict[str, Any]] = []
|
||||
for j, s in enumerate(slots_raw):
|
||||
u_start = start_h + j * sub_h
|
||||
u_end = start_h + (j + 1) * sub_h
|
||||
slot_items.append(
|
||||
{
|
||||
**s,
|
||||
"window_start_hour": round(u_start, 3),
|
||||
"window_end_hour": round(u_end, 3),
|
||||
"window_start_label": _fmt_hour(u_start),
|
||||
"window_end_label": _fmt_hour(u_end),
|
||||
"window_hours": round(sub_h, 2),
|
||||
}
|
||||
)
|
||||
channels.append(
|
||||
{
|
||||
"group_id": g.get("id"),
|
||||
"name": g.get("name"),
|
||||
"channel_pk": g.get("channel_pk"),
|
||||
"youtube_channel_id": g.get("youtube_channel_id"),
|
||||
"start_hour": round(start_h, 3),
|
||||
"end_hour": round(end_h, 3),
|
||||
"start_label": _fmt_hour(start_h),
|
||||
"end_label": _fmt_hour(end_h),
|
||||
"slot_hours": round(slot_h, 2),
|
||||
"active": active,
|
||||
"slot_count": m,
|
||||
"slots": slot_items,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"channel_count": n,
|
||||
"slot_hours": round(slot_h, 2),
|
||||
"now_hour": round(now_h, 3),
|
||||
"now_label": _fmt_hour(now_h),
|
||||
"channels": channels,
|
||||
}
|
||||
|
||||
|
||||
def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups: 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("暂无可用抖音直播数据")
|
||||
|
||||
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("没有启用的分配分组")
|
||||
|
||||
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,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"filled": len(results),
|
||||
"schedule": build_rotation_schedule(include_urls=True),
|
||||
"details": results,
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Ban,
|
||||
Clock,
|
||||
Copy,
|
||||
Download,
|
||||
Eye,
|
||||
@ -63,6 +64,12 @@ type FeaturedUrl = {
|
||||
blacklist_reason?: string;
|
||||
};
|
||||
|
||||
type SlotUrl = FeaturedUrl & {
|
||||
window_start_label?: string;
|
||||
window_end_label?: string;
|
||||
window_hours?: number;
|
||||
};
|
||||
|
||||
type AssignGroup = {
|
||||
id: string;
|
||||
name?: string;
|
||||
@ -75,6 +82,25 @@ type AssignGroup = {
|
||||
enabled?: boolean;
|
||||
pool?: PoolUrl[];
|
||||
featured?: FeaturedUrl[];
|
||||
slots?: SlotUrl[];
|
||||
};
|
||||
|
||||
type ScheduleChannel = {
|
||||
group_id: string;
|
||||
name?: string;
|
||||
start_label?: string;
|
||||
end_label?: string;
|
||||
slot_hours?: number;
|
||||
active?: boolean;
|
||||
slot_count?: number;
|
||||
slots?: SlotUrl[];
|
||||
};
|
||||
|
||||
type RotationSchedule = {
|
||||
channel_count?: number;
|
||||
slot_hours?: number;
|
||||
now_label?: string;
|
||||
channels?: ScheduleChannel[];
|
||||
};
|
||||
|
||||
function formatExportLine(url: string, title?: string): string {
|
||||
@ -175,6 +201,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
const confirm = useConfirm();
|
||||
const toast = useToast();
|
||||
const [groups, setGroups] = useState<AssignGroup[]>([]);
|
||||
const [schedule, setSchedule] = useState<RotationSchedule | null>(null);
|
||||
const [groupId, setGroupId] = useState("");
|
||||
const [profiles, setProfiles] = useState<Record<string, YtProfileSnippet>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
@ -193,6 +220,14 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
() => new Set((selected?.featured || []).map((f) => String(f.pool_url_id))),
|
||||
[selected]
|
||||
);
|
||||
const slotIds = useMemo(
|
||||
() => new Set((selected?.slots || []).map((s) => String(s.pool_url_id))),
|
||||
[selected]
|
||||
);
|
||||
const selectedSchedule = useMemo(
|
||||
() => (schedule?.channels || []).find((c) => c.group_id === groupId) || null,
|
||||
[schedule, groupId]
|
||||
);
|
||||
const channelById = useMemo(() => {
|
||||
const m: Record<string, ManagedChannel> = {};
|
||||
for (const c of channels) m[c.id] = c;
|
||||
@ -214,10 +249,22 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const loadSchedule = useCallback(async () => {
|
||||
try {
|
||||
const data = await fetchJson("/api/youtube/assign/schedule");
|
||||
setSchedule(data as RotationSchedule);
|
||||
} catch {
|
||||
setSchedule(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadGroups = useCallback(async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const data = await fetchJson("/api/youtube/assign/groups");
|
||||
const [data] = await Promise.all([
|
||||
fetchJson("/api/youtube/assign/groups"),
|
||||
loadSchedule(),
|
||||
]);
|
||||
const list: AssignGroup[] = data.groups || [];
|
||||
setGroups(list);
|
||||
setGroupId((prev) => {
|
||||
@ -229,7 +276,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [toast]);
|
||||
}, [toast, loadSchedule]);
|
||||
|
||||
const loadAllProfiles = useCallback(async () => {
|
||||
try {
|
||||
@ -501,33 +548,91 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function copyList(kind: "pool" | "featured") {
|
||||
async function addSlot(poolUrlId: string) {
|
||||
if (!selected) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson(`/api/youtube/assign/groups/${selected.id}/slots`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ pool_url_id: poolUrlId }),
|
||||
});
|
||||
const bl = Array.isArray(r?.skipped_blacklist) ? r.skipped_blacklist.length : 0;
|
||||
if (bl) toast.push("该房间在黑名单中,未加入时间段", "err");
|
||||
else if (Number(r?.skipped_dup || 0) > 0 && !r?.added) toast.push("时间段已存在(已去重)", "ok");
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeSlot(slotId: string) {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/assign/slots/${slotId}`, { method: "DELETE" });
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function autoFillSlots(allGroups = 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 }),
|
||||
})
|
||||
: await fetchJson(`/api/youtube/assign/groups/${selected!.id}/slots/auto-fill`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ limit: 16, all_groups: false }),
|
||||
});
|
||||
toast.push(`已从直播数据填充 ${Number(r?.filled ?? 0)} 条`, "ok");
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function copyList(kind: "pool" | "featured" | "slots") {
|
||||
if (!selected) return;
|
||||
const rows =
|
||||
kind === "pool"
|
||||
? selected.pool || []
|
||||
: (selected.featured || []).map((f) => ({ url: f.url, title: f.title }));
|
||||
: kind === "featured"
|
||||
? (selected.featured || []).map((f) => ({ url: f.url, title: f.title }))
|
||||
: (selected.slots || []).map((s) => ({ url: s.url, title: s.title }));
|
||||
const label = kind === "pool" ? "普通" : kind === "featured" ? "精选" : "时间段";
|
||||
const text = exportText(rows);
|
||||
if (!text) {
|
||||
toast.push("列表为空", "err");
|
||||
return;
|
||||
}
|
||||
const ok = await copyText(text);
|
||||
toast.push(ok ? `已复制${kind === "pool" ? "普通" : "精选"}列表 ${rows.length} 条` : "复制失败", ok ? "ok" : "err");
|
||||
toast.push(ok ? `已复制${label}列表 ${rows.length} 条` : "复制失败", ok ? "ok" : "err");
|
||||
}
|
||||
|
||||
function exportList(kind: "pool" | "featured") {
|
||||
function exportList(kind: "pool" | "featured" | "slots") {
|
||||
if (!selected) return;
|
||||
const rows =
|
||||
kind === "pool"
|
||||
? selected.pool || []
|
||||
: (selected.featured || []).map((f) => ({ url: f.url, title: f.title }));
|
||||
: kind === "featured"
|
||||
? (selected.featured || []).map((f) => ({ url: f.url, title: f.title }))
|
||||
: (selected.slots || []).map((s) => ({ url: s.url, title: s.title }));
|
||||
const text = exportText(rows);
|
||||
if (!text) {
|
||||
toast.push("列表为空", "err");
|
||||
return;
|
||||
}
|
||||
const tag = kind === "pool" ? "pool" : "featured";
|
||||
const tag = kind === "pool" ? "pool" : kind === "featured" ? "featured" : "slots";
|
||||
const name = String(selected.name || "assign").replace(/[\\/:*?"<>|]+/g, "_").slice(0, 40);
|
||||
downloadText(`${name}-${tag}.txt`, text);
|
||||
toast.push(`已导出 ${rows.length} 条`, "ok");
|
||||
@ -614,18 +719,70 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
暂无分配分组。上方选择频道并新建。
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 xl:grid-cols-[240px_1fr]">
|
||||
<aside className="space-y-2">
|
||||
<>
|
||||
{schedule && (schedule.channels || []).length > 0 ? (
|
||||
<section className="rounded-2xl border border-violet-500/25 bg-violet-500/5 p-4">
|
||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-violet-100">24 小时频道轮播(北京时间)</h4>
|
||||
<p className="text-[11px] text-violet-200/70">
|
||||
{schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前 {schedule.now_label}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void autoFillSlots(true)}
|
||||
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" />
|
||||
全频道填充直播数据
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex gap-1 overflow-x-auto pb-1">
|
||||
{(schedule.channels || []).map((ch) => {
|
||||
const active = Boolean(ch.active);
|
||||
const selectedNow = ch.group_id === groupId;
|
||||
return (
|
||||
<button
|
||||
key={ch.group_id}
|
||||
type="button"
|
||||
onClick={() => setGroupId(ch.group_id)}
|
||||
className={`min-w-[7.5rem] shrink-0 rounded-lg border px-2 py-1.5 text-left transition ${
|
||||
active
|
||||
? "border-teal-400/50 bg-teal-500/15"
|
||||
: selectedNow
|
||||
? "border-violet-400/40 bg-violet-500/15"
|
||||
: "border-white/10 bg-black/30 hover:bg-white/5"
|
||||
}`}
|
||||
>
|
||||
<div className="truncate text-[11px] font-medium text-slate-100">{ch.name || "频道"}</div>
|
||||
<div className="text-[10px] text-slate-400">
|
||||
{ch.start_label}–{ch.end_label}
|
||||
</div>
|
||||
{active ? (
|
||||
<div className="mt-0.5 text-[10px] text-teal-300">● 当前时段</div>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-[minmax(280px,300px)_minmax(0,1fr)]">
|
||||
<aside className="space-y-2 xl:sticky xl:top-4 xl:self-start">
|
||||
{groups.map((g) => {
|
||||
const pk = String(g.channel_pk || "");
|
||||
const ch = channelById[pk];
|
||||
const active = g.id === groupId;
|
||||
const sch = (schedule?.channels || []).find((c) => c.group_id === g.id);
|
||||
return (
|
||||
<button
|
||||
key={g.id}
|
||||
type="button"
|
||||
onClick={() => setGroupId(g.id)}
|
||||
className={`w-full rounded-xl border p-3 text-left transition ${
|
||||
className={`w-full min-w-0 overflow-hidden rounded-xl border p-2.5 text-left transition ${
|
||||
active
|
||||
? "border-rose-400/40 bg-rose-500/10"
|
||||
: "border-white/10 bg-black/30 hover:bg-white/5"
|
||||
@ -636,11 +793,18 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
fallbackName={g.name}
|
||||
fallbackChannelId={g.youtube_channel_id}
|
||||
liveChannelPk={pk || undefined}
|
||||
compact
|
||||
meta={ch ? buildChannelMeta(ch) : undefined}
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap gap-2 text-[10px] text-slate-500">
|
||||
<div className="mt-2 flex flex-wrap gap-x-2 gap-y-1 text-[10px] text-slate-500">
|
||||
<span>池 {(g.pool || []).length}</span>
|
||||
<span>精选 {(g.featured || []).length}</span>
|
||||
<span>时段 {(g.slots || []).length}</span>
|
||||
{sch ? (
|
||||
<span className={sch.active ? "text-teal-300" : "text-violet-300/80"}>
|
||||
{sch.start_label}–{sch.end_label}
|
||||
</span>
|
||||
) : null}
|
||||
<span>{g.has_stream_key ? "KEY✓" : "无 KEY"}</span>
|
||||
</div>
|
||||
</button>
|
||||
@ -658,6 +822,19 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
channel={channelById[String(selected.channel_pk || "")] || null}
|
||||
/>
|
||||
|
||||
{selectedSchedule ? (
|
||||
<div className="rounded-xl border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-xs text-violet-100">
|
||||
本频道时段{" "}
|
||||
<span className="font-medium">
|
||||
{selectedSchedule.start_label}–{selectedSchedule.end_label}
|
||||
</span>
|
||||
(约 {selectedSchedule.slot_hours} 小时)
|
||||
{selectedSchedule.active ? (
|
||||
<span className="ml-2 text-teal-300">● 当前正在轮播</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium text-slate-100">直播 KEY / 备注</h4>
|
||||
@ -727,7 +904,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
|
||||
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium text-slate-100">
|
||||
@ -779,6 +956,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
) : (
|
||||
(selected.pool || []).map((u) => {
|
||||
const inFeat = featuredIds.has(u.id);
|
||||
const inSlot = slotIds.has(u.id);
|
||||
const banned = Boolean(u.blacklisted);
|
||||
return (
|
||||
<div
|
||||
@ -818,6 +996,19 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || inSlot || banned}
|
||||
title={banned ? "已在黑名单" : inSlot ? "已在时间段" : "加入时间段轮播"}
|
||||
onClick={() => void addSlot(u.id)}
|
||||
className={`rounded-lg px-2 py-1 text-[11px] ${
|
||||
inSlot || banned
|
||||
? "bg-violet-500/20 text-violet-100 opacity-50"
|
||||
: "bg-white/5 text-slate-300 hover:bg-violet-500/15"
|
||||
}`}
|
||||
>
|
||||
<Clock className="h-3 w-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || inFeat || banned}
|
||||
@ -953,10 +1144,132 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-violet-500/25 bg-violet-500/5 p-4 xl:col-span-1">
|
||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium text-violet-50">
|
||||
时间段列表(轮播)· {(selected.slots || []).length}
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void autoFillSlots(false)}
|
||||
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" />
|
||||
填充直播
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copyList("slots")}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-violet-50"
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
复制
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => exportList("slots")}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-violet-50"
|
||||
>
|
||||
<Download className="h-3 w-3" />
|
||||
导出
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mb-3 text-[11px] text-violet-100/70">
|
||||
本频道 {selectedSchedule?.start_label || "—"}–{selectedSchedule?.end_label || "—"} 内按序轮播抖音源;多频道错开时段,避免同时推流。
|
||||
</p>
|
||||
<div className="max-h-[28rem] space-y-2 overflow-y-auto">
|
||||
{(selected.slots || []).length === 0 ? (
|
||||
<div className="py-10 text-center text-xs text-violet-100/50">
|
||||
从普通列表点时钟图标加入,或点「填充直播」
|
||||
</div>
|
||||
) : (
|
||||
(selected.slots || []).map((s, i) => {
|
||||
const banned = Boolean(s.blacklisted);
|
||||
const schSlot = (schedule?.channels || [])
|
||||
.find((c) => c.group_id === selected.id)
|
||||
?.slots?.[i] as SlotUrl | undefined;
|
||||
const timeLabel =
|
||||
schSlot?.window_start_label && schSlot?.window_end_label
|
||||
? `${schSlot.window_start_label}–${schSlot.window_end_label}`
|
||||
: null;
|
||||
return (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`flex items-center gap-2 rounded-xl border p-2 ${
|
||||
banned
|
||||
? "border-fuchsia-500/35 bg-fuchsia-500/10"
|
||||
: "border-violet-500/25 bg-black/40"
|
||||
}`}
|
||||
>
|
||||
<span className="shrink-0 rounded bg-violet-500/20 px-1.5 text-[10px] text-violet-100">
|
||||
#{i + 1}
|
||||
</span>
|
||||
<CoverThumb
|
||||
cover={s.cover_url}
|
||||
title={s.title}
|
||||
onOpen={(src) =>
|
||||
setLightbox({ src, title: s.title || "封面", subtitle: s.url })
|
||||
}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="truncate text-sm text-violet-50">{s.title || "未命名主播"}</div>
|
||||
{timeLabel ? (
|
||||
<span className="rounded bg-violet-500/25 px-1.5 text-[10px] text-violet-100">
|
||||
{timeLabel}
|
||||
</span>
|
||||
) : null}
|
||||
{banned ? (
|
||||
<span className="rounded bg-fuchsia-500/25 px-1.5 text-[10px] text-fuchsia-100">
|
||||
黑名单
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<a
|
||||
href={s.url || "#"}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="block truncate text-[11px] text-sky-300 hover:underline"
|
||||
>
|
||||
{s.url || s.pool_url_id}
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-1">
|
||||
{s.pool_url_id ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
title="加入黑名单"
|
||||
onClick={() => void banPool(s.pool_url_id, s.title || s.url || "")}
|
||||
className="rounded-lg bg-fuchsia-500/15 px-2 py-1 text-fuchsia-100"
|
||||
>
|
||||
<Ban className="h-3 w-3" />
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void removeSlot(s.id)}
|
||||
className="rounded-lg bg-rose-500/10 px-2 py-1 text-rose-200"
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{lightbox ? (
|
||||
|
||||
@ -78,6 +78,7 @@ export function YtChannelProfileSnippet({
|
||||
trailing,
|
||||
meta,
|
||||
metaLayout = "column",
|
||||
compact = false,
|
||||
className = "",
|
||||
}: {
|
||||
profile?: YtProfileSnippet | null;
|
||||
@ -87,6 +88,7 @@ export function YtChannelProfileSnippet({
|
||||
trailing?: ReactNode;
|
||||
meta?: YtChannelMeta | null;
|
||||
metaLayout?: "column" | "row";
|
||||
compact?: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
const ytName = String(profile?.title || "").trim();
|
||||
@ -99,39 +101,46 @@ export function YtChannelProfileSnippet({
|
||||
const showPhoto = Boolean(thumb) && !imgBroken;
|
||||
const alias = localName && ytName && localName.toLowerCase() !== ytName.toLowerCase() ? localName : "";
|
||||
|
||||
const avatarCls = compact ? "h-10 w-10" : "h-12 w-12";
|
||||
const titleCls = compact ? "text-sm" : "";
|
||||
|
||||
return (
|
||||
<div className={`flex min-w-0 gap-3 ${className}`}>
|
||||
<div className={`flex min-w-0 w-full gap-2.5 ${className}`}>
|
||||
{showPhoto ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={thumb}
|
||||
alt={title}
|
||||
className="h-12 w-12 shrink-0 rounded-full object-cover ring-1 ring-white/10"
|
||||
className={`${avatarCls} shrink-0 rounded-full object-cover ring-1 ring-white/10`}
|
||||
onError={() => setImgBroken(true)}
|
||||
/>
|
||||
) : (
|
||||
<LetterAvatar name={title} />
|
||||
<div className={compact ? "scale-90 origin-top-left" : ""}>
|
||||
<LetterAvatar name={title} />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="truncate font-medium text-slate-100" title="YouTube 频道昵称(授权页同名)">
|
||||
<div className={`truncate font-medium text-slate-100 ${titleCls}`} title="YouTube 频道昵称(授权页同名)">
|
||||
{title}
|
||||
</div>
|
||||
{liveChannelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(liveChannelPk)} compact showOffline /> : null}
|
||||
{trailing}
|
||||
</div>
|
||||
{handle ? <div className="truncate text-xs text-slate-400">{handle}</div> : null}
|
||||
{alias ? <div className="truncate text-[11px] text-slate-500">内部备注 {alias}</div> : null}
|
||||
<div className="mt-0.5 text-[11px] text-slate-500">
|
||||
订阅 {stats?.subscriberCount ?? "—"} · 视频 {stats?.videoCount ?? "—"} · 播放 {stats?.viewCount ?? "—"}
|
||||
</div>
|
||||
{meta && metaLayout === "row" ? (
|
||||
<div className="mt-1.5">
|
||||
{alias && !compact ? <div className="truncate text-[11px] text-slate-500">内部备注 {alias}</div> : null}
|
||||
{!compact ? (
|
||||
<div className="mt-0.5 text-[11px] text-slate-500">
|
||||
订阅 {stats?.subscriberCount ?? "—"} · 视频 {stats?.videoCount ?? "—"} · 播放 {stats?.viewCount ?? "—"}
|
||||
</div>
|
||||
) : null}
|
||||
{meta && (compact || metaLayout === "row") ? (
|
||||
<div className="mt-1">
|
||||
<YtChannelMetaBadges meta={meta} layout="row" />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{meta && metaLayout === "column" ? <YtChannelMetaBadges meta={meta} layout="column" /> : null}
|
||||
{meta && !compact && metaLayout === "column" ? <YtChannelMetaBadges meta={meta} layout="column" /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user