# -*- coding: utf-8 -*- """YouTube relay assignment: channel + stream key → Douyin URL pool → featured list. Isolated from shorts_*/tiktok_*/x_* upload pipelines. Links optionally to shorts_channels for OAuth profile cards on /youtube. """ from __future__ import annotations import hashlib import random import re import sqlite3 import time import uuid from typing import Any, Optional from .db import _connect, _lock, _row_to_dict from .models import extract_room_id, normalize_room_url from .config import settings def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None: conn.execute( """ CREATE TABLE IF NOT EXISTS yt_assign_groups ( id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', channel_pk TEXT NOT NULL DEFAULT '', youtube_channel_id TEXT NOT NULL DEFAULT '', stream_key TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '', enabled INTEGER NOT NULL DEFAULT 1, sort_order INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, updated_at REAL NOT NULL ) """ ) conn.execute( """ CREATE TABLE IF NOT EXISTS yt_assign_pool_urls ( id TEXT PRIMARY KEY, group_id TEXT NOT NULL, url TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '', room_id TEXT NOT NULL DEFAULT '', cover_url TEXT NOT NULL DEFAULT '', sort_order INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL, updated_at REAL NOT NULL ) """ ) conn.execute( """ CREATE TABLE IF NOT EXISTS yt_assign_featured_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) ) """ ) 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 ''"), ("room_id", "TEXT NOT NULL DEFAULT ''"), ("cover_url", "TEXT NOT NULL DEFAULT ''"), ]: if col not in cols: conn.execute(f"ALTER TABLE yt_assign_pool_urls ADD COLUMN {col} {ddl}") conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_assign_pool_group ON yt_assign_pool_urls(group_id, sort_order)" ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_assign_feat_group ON yt_assign_featured_urls(group_id, sort_order)" ) conn.execute( "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_slot_group ON yt_assign_slot_urls(group_id, sort_order)" ) gcols = {str(r[1]) for r in conn.execute("PRAGMA table_info(yt_assign_groups)").fetchall()} for col, ddl in [ ("neko_instance_id", "INTEGER NOT NULL DEFAULT 0"), ("neko_enabled", "INTEGER NOT NULL DEFAULT 0"), # Remote ops-neko (physical tab) — additive; never replaces native douyinweb-neko-* ("ops_neko_open_url", "TEXT NOT NULL DEFAULT ''"), ("ops_neko_slot", "INTEGER NOT NULL DEFAULT 0"), ("ops_neko_edge_label", "TEXT NOT NULL DEFAULT ''"), ("ops_neko_bound_at", "REAL NOT NULL DEFAULT 0"), # Which desktop the assign「打开」button prefers: local (native) | remote (ops-neko tab) ("neko_open_prefer", "TEXT NOT NULL DEFAULT 'local'"), # Push category: normal (manual / featured) | time_slot (24/N schedule + live sources) ("category", "TEXT NOT NULL DEFAULT 'normal'"), # time_slot only: off ⇒ same as missing stream key (excluded from 24/N) ("time_slot_armed", "INTEGER NOT NULL DEFAULT 1"), ]: if col not in gcols: conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}") orphans = conn.execute( "SELECT id FROM yt_assign_groups WHERE COALESCE(neko_instance_id, 0) = 0 ORDER BY sort_order ASC, created_at ASC" ).fetchall() if orphans: max_row = conn.execute("SELECT COALESCE(MAX(neko_instance_id), 0) AS m FROM yt_assign_groups").fetchone() next_id = int(max_row["m"] if max_row else 0) for row in orphans: next_id += 1 conn.execute( "UPDATE yt_assign_groups SET neko_instance_id = ? WHERE id = ?", (next_id, str(row["id"])), ) def parse_pool_line(raw: str) -> dict[str, str]: """Parse paste lines like: https://live.douyin.com/343450949840,主播: 街角早安三明治,""" text = str(raw or "").strip().lstrip("\ufeff") if not text: return {} url = "" m = re.search(r"https?://[^\s,,]+", text) if m: url = m.group(0).rstrip(".,,/;") if not url: rid0 = extract_room_id(text) if rid0: url = normalize_room_url(rid0) if not url: return {} url = normalize_room_url(url) or url room_id = extract_room_id(url) title = "" m2 = re.search(r"主播\s*[::]\s*([^,\n,]+)", text) if m2: title = m2.group(1).strip().rstrip(".,,") else: rest = text if m: rest = (text[: m.start()] + text[m.end() :]).strip() for part in re.split(r"[,,]", rest): p = part.strip().rstrip(".,,") if not p or p.startswith("http"): continue p = re.sub(r"^主播\s*[::]\s*", "", p).strip() if p: title = p break return {"url": url[:500], "title": title[:120], "room_id": (room_id or "")[:64]} def _lookup_cover_and_anchor(conn: sqlite3.Connection, room_id: str) -> tuple[str, str]: rid = str(room_id or "").strip() if not rid: return "", "" cover = "" anchor = "" try: room = conn.execute( "SELECT last_anchor, note, avatar_url FROM rooms WHERE room_id = ? LIMIT 1", (rid,), ).fetchone() if room: anchor = str(room["last_anchor"] or "").strip() or str(room["note"] or "").strip() cover = str(room["avatar_url"] or "").strip() if not cover or not anchor: row = conn.execute( """ SELECT cover_path, anchor_name FROM sessions WHERE room_id = ? AND cover_path IS NOT NULL AND TRIM(cover_path) != '' ORDER BY started_at DESC LIMIT 1 """, (rid,), ).fetchone() if row: cover = cover or str(row["cover_path"] or "").strip() anchor = anchor or str(row["anchor_name"] or "").strip() if not cover or not anchor: row2 = conn.execute( """ SELECT cover_path, anchor_name FROM sessions WHERE room_id = ? ORDER BY started_at DESC LIMIT 1 """, (rid,), ).fetchone() if row2: cover = cover or str(row2["cover_path"] or "").strip() anchor = anchor or str(row2["anchor_name"] or "").strip() except Exception: pass if cover and not (cover.startswith("http") or cover.startswith("/api/") or cover.startswith("/covers/")): cover = "" return cover, anchor def _enrich_pool_row( conn: sqlite3.Connection, row: dict[str, Any], *, mutate: bool = True, ) -> dict[str, Any]: from .db import _is_blacklisted_conn out = dict(row) rid = str(out.get("room_id") or "").strip() or extract_room_id(str(out.get("url") or "")) if rid and not out.get("room_id"): out["room_id"] = rid cover = str(out.get("cover_url") or "").strip() title = str(out.get("title") or "").strip() if rid and (not cover or not title): found_cover, found_anchor = _lookup_cover_and_anchor(conn, rid) if not cover and found_cover: out["cover_url"] = found_cover if not title and found_anchor: out["title"] = found_anchor if mutate: # Persist so ordinary list stops showing「未命名主播」after refresh. pool_pk = str(out.get("pool_url_id") or "").strip() if not pool_pk: # Pure pool row uses id; featured/slot rows use pool_url_id. if "pool_url_id" not in row: pool_pk = str(out.get("id") or "").strip() try: if pool_pk: conn.execute( """ UPDATE yt_assign_pool_urls SET title = ?, updated_at = ? WHERE id = ? AND TRIM(COALESCE(title, '')) = '' """, (found_anchor[:120], time.time(), pool_pk), ) else: conn.execute( """ UPDATE yt_assign_pool_urls SET title = ?, updated_at = ? WHERE room_id = ? AND TRIM(COALESCE(title, '')) = '' """, (found_anchor[:120], time.time(), rid), ) except Exception: pass # Backfill: pool URL missing from rooms → push into live pool (overview). if mutate and rid and str(out.get("url") or "").strip(): try: exists = conn.execute( "SELECT 1 AS ok FROM rooms WHERE room_id = ? LIMIT 1", (rid,), ).fetchone() if not exists: from .douyin_ingest import ensure_in_live_pool_conn ensure_in_live_pool_conn( conn, str(out.get("url") or ""), note=str(out.get("title") or ""), title=str(out.get("title") or ""), enabled=True, ) except Exception: pass hit = _is_blacklisted_conn(conn, rid, str(out.get("url") or "")) out["blacklisted"] = bool(hit) out["blacklist_reason"] = str((hit or {}).get("reason") or (hit or {}).get("value") or "") if hit else "" out["blacklist_id"] = str((hit or {}).get("id") or "") if hit else "" return out def _dedupe_key(url: str, room_id: str = "") -> str: rid = (room_id or extract_room_id(url) or "").strip().lower() if rid: return f"rid:{rid}" return f"url:{_normalize_url(url).lower()}" def _normalize_url(url: str) -> str: return normalize_room_url(str(url or "").strip()) or str(url or "").strip() 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 _beijing_day_key(ts: float | None = None) -> str: from .timeutil import beijing_from_ts dt = beijing_from_ts(ts if ts is not None else time.time()) return dt.strftime("%Y-%m-%d") def _slot_active(now_h: float, start_h: float, end_h: float) -> bool: """True if now_h is in [start_h, end_h) on a 24h clock (supports wrap past midnight).""" now_h = float(now_h) % 24.0 start_h = float(start_h) % 24.0 end_h = float(end_h) % 24.0 if abs(end_h - start_h) < 1e-9: return True # full day if start_h < end_h: return start_h <= now_h < end_h # wraps midnight return now_h >= start_h or now_h < end_h def _daily_random_windows(n: int, *, seed: str) -> list[tuple[float, float, float]]: """Uneven random 24h partition for N channels. Stable for a given seed (Beijing day + channel set). Order of returned windows matches the already-shuffled channel list. Avoids equal 24/N splits that look bot-like to YouTube. """ if n <= 0: return [] rng = random.Random(seed) if n == 1: return [(0.0, 24.0, 24.0)] # Broken-stick spacings → uneven lengths; reject if any slice too short. min_h = min(0.75, max(0.35, 24.0 / (n * 4.0))) hours: list[float] = [] for _ in range(40): pts = [0.0] + sorted(rng.random() for _ in range(n - 1)) + [1.0] hours = [(pts[i + 1] - pts[i]) * 24.0 for i in range(n)] if min(hours) >= min_h - 1e-9: break else: # Fallback: soft-jitter equal split so we never stall base = 24.0 / n jitter = [rng.uniform(0.65, 1.35) for _ in range(n)] s = sum(jitter) hours = [base * j * n / s for j in jitter] # renormalize exact 24 s2 = sum(hours) hours = [h * 24.0 / s2 for h in hours] # Random day offset so boundaries don't always sit on the hour / midnight offset = rng.uniform(0.0, 24.0) out: list[tuple[float, float, float]] = [] t = offset for h in hours: start = t % 24.0 end = (t + h) % 24.0 out.append((start, end, h)) t += h return out ASSIGN_CATEGORIES = ("normal", "time_slot") ASSIGN_CATEGORY_LABELS = {"normal": "普通", "time_slot": "时间段"} def normalize_assign_category(value: Any) -> str: """Map UI/API values to stored category keys. Default / unknown → normal.""" raw = str(value or "").strip().lower() if raw in {"time_slot", "timeslot", "time-slot", "slot", "时间段"}: return "time_slot" if raw in {"normal", "普通", "manual", "手动"}: return "normal" return "normal" def group_is_time_slot(group: dict[str, Any] | None) -> bool: if not group: return False return normalize_assign_category(group.get("category")) == "time_slot" def group_time_slot_armed(group: dict[str, Any] | None) -> bool: """Whether a time_slot card participates in 24/N. Default True (legacy rows).""" if group is None: return False if "time_slot_armed" not in group: return True v = group.get("time_slot_armed") if v is None: return True if isinstance(v, str): return v.strip().lower() not in {"0", "false", "no", "off", ""} return bool(v) def group_eligible_for_time_slot(group: dict[str, Any] | None) -> bool: """时间段排班资格:分类=时间段 + 有 KEY + 右上角开关开。""" if not group or not group.get("enabled"): return False if not group_is_time_slot(group): return False if not _group_has_stream_key(group): return False return group_time_slot_armed(group) def _public_group( row: dict[str, Any], *, pool: list | None = None, featured: list | None = None, slots: list | None = None, include_secret: bool = True, ) -> dict[str, Any]: out = dict(row) out["enabled"] = bool(out.get("enabled")) out["neko_enabled"] = bool(out.get("neko_enabled")) out["category"] = normalize_assign_category(out.get("category")) out["category_label"] = ASSIGN_CATEGORY_LABELS.get(out["category"], "普通") out["time_slot_armed"] = group_time_slot_armed(out) neko_id = int(out.get("neko_instance_id") or 0) out["neko_instance_id"] = neko_id sk = str(out.get("stream_key") or "") out["has_stream_key"] = bool(sk.strip()) out["stream_key_masked"] = ("***" + sk[-4:]) if len(sk) > 6 else ("***" if sk else "") if include_secret: out["stream_key"] = sk else: out.pop("stream_key", None) if pool is not None: out["pool"] = pool if featured is not None: out["featured"] = featured if slots is not None: out["slots"] = slots local_studio = "" if neko_id > 0: try: from . import youtube_neko local_studio = youtube_neko.public_studio_url(neko_id) except Exception: local_studio = "" # Native assign Neko URL is always kept (VPS/physical local docker — default stopped). out["neko_studio_url"] = local_studio out["neko_local_studio_url"] = local_studio remote = str(out.get("ops_neko_open_url") or "").strip() if remote and not remote.endswith("/"): remote = f"{remote}/" out["ops_neko_open_url"] = remote out["ops_neko_bound"] = bool(remote) out["ops_neko_slot"] = int(out.get("ops_neko_slot") or 0) prefer = str(out.get("neko_open_prefer") or "local").strip().lower() if prefer not in {"local", "remote"}: prefer = "local" # Cannot prefer remote if unbound — fall back to local. if prefer == "remote" and not remote: prefer = "local" out["neko_open_prefer"] = prefer # Default click target for「打开工作室」— switchable; never deletes native URL. if prefer == "remote" and remote: out["neko_open_url"] = remote out["neko_open_source"] = "remote" else: out["neko_open_url"] = local_studio out["neko_open_source"] = "local" return out def set_ops_neko_bind( group_id: str, *, open_url: str, slot: int = 0, edge_label: str = "", ) -> dict[str, Any] | None: """Hub-side: attach physical ops-neko URL. Does NOT touch native neko_instance_id / neko_enabled.""" gid = str(group_id or "").strip() if not gid: return None url = str(open_url or "").strip() if url and not url.endswith("/"): url = f"{url}/" now = time.time() with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) conn.execute( """ UPDATE yt_assign_groups SET ops_neko_open_url = ?, ops_neko_slot = ?, ops_neko_edge_label = ?, ops_neko_bound_at = ?, updated_at = ? WHERE id = ? """, ( url, int(slot or 0), str(edge_label or "")[:120], now if url else 0, now, gid, ), ) conn.commit() finally: conn.close() return get_group(gid) def set_neko_open_prefer(group_id: str, prefer: str) -> dict[str, Any] | None: """local = native /neko/N/; remote = paired ops-neko tab URL. Native instance always retained.""" p = str(prefer or "local").strip().lower() if p not in {"local", "remote"}: raise ValueError("prefer must be local|remote") gid = str(group_id or "").strip() if not gid: return None with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) conn.execute( "UPDATE yt_assign_groups SET neko_open_prefer = ?, updated_at = ? WHERE id = ?", (p, time.time(), gid), ) conn.commit() finally: conn.close() return get_group(gid) 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, p.room_id AS room_id, p.cover_url AS cover_url FROM yt_assign_featured_urls f LEFT JOIN yt_assign_pool_urls p ON p.id = f.pool_url_id WHERE f.group_id = ? ORDER BY f.sort_order ASC, f.created_at ASC """ def list_groups( *, include_urls: bool = True, include_secret: bool = True, featured_only: bool = False, ) -> list[dict[str, Any]]: """List assign groups. featured_only=True: load featured URLs only (no pool/slots/enrich) — for relay status polls. include_secret=True by default so ops UI can show/copy live stream keys. """ with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) rows = conn.execute( "SELECT * FROM yt_assign_groups ORDER BY sort_order ASC, created_at ASC" ).fetchall() out: list[dict[str, Any]] = [] for r in rows: g = _row_to_dict(r) # type: ignore if not include_urls and not featured_only: out.append(_public_group(g, pool=[], featured=[], slots=[], include_secret=include_secret)) continue gid = str(g.get("id") or "") if featured_only: feat_rows = conn.execute(_feat_select_sql(), (gid,)).fetchall() featured = [] for x in feat_rows: d = _row_to_dict(x) or {} featured.append( { "url": str(d.get("url") or "").strip(), "room_id": str(d.get("room_id") or "").strip(), "title": str(d.get("title") or "").strip(), "blacklisted": False, } ) out.append( _public_group(g, pool=[], featured=featured, slots=[], include_secret=include_secret) ) continue pool_rows = conn.execute( "SELECT * FROM yt_assign_pool_urls WHERE group_id = ? ORDER BY sort_order ASC, created_at ASC", (gid,), ).fetchall() pool = [_enrich_pool_row(conn, _row_to_dict(x) or {}, mutate=False) for x in pool_rows] feat_rows = conn.execute(_feat_select_sql(), (gid,)).fetchall() featured = [_enrich_pool_row(conn, _row_to_dict(x) or {}, mutate=False) for x in feat_rows] slot_rows = conn.execute(_slot_select_sql(), (gid,)).fetchall() slots = [_enrich_pool_row(conn, _row_to_dict(x) or {}, mutate=False) for x in slot_rows] out.append( _public_group(g, pool=pool, featured=featured, slots=slots, include_secret=include_secret) ) # Read path: no commit needed (enrich is non-mutating). return out finally: conn.close() def get_group(group_id: str, *, include_secret: bool = True) -> dict[str, Any] | None: with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) row = conn.execute("SELECT * FROM yt_assign_groups WHERE id = ?", (group_id,)).fetchone() if not row: return None g = _row_to_dict(row) # type: ignore gid = str(g.get("id") or "") pool = [ _enrich_pool_row(conn, _row_to_dict(x) or {}) for x in conn.execute( "SELECT * FROM yt_assign_pool_urls WHERE group_id = ? ORDER BY sort_order ASC, created_at ASC", (gid,), ).fetchall() ] featured = [ _enrich_pool_row(conn, _row_to_dict(x) or {}) for x in conn.execute(_feat_select_sql(), (gid,)).fetchall() ] slots = [ _enrich_pool_row(conn, _row_to_dict(x) or {}) for x in conn.execute(_slot_select_sql(), (gid,)).fetchall() ] conn.commit() return _public_group(g, pool=pool, featured=featured, slots=slots, include_secret=include_secret) # type: ignore finally: conn.close() def _sanitize_stream_key(raw: str) -> str: """Reject browser-autofilled site login passwords mistaken for YouTube stream keys.""" sk = str(raw or "").strip() if not sk: return "" low = sk.lower() banned = { "hackrobot", "douyinweb", "xiao4669805@", "xiao4669805", str(getattr(settings, "admin_username", "") or "").strip().lower(), str(getattr(settings, "admin_password", "") or "").strip().lower(), str(getattr(settings, "neko_user_pass", "") or "").strip().lower(), str(getattr(settings, "neko_admin_pass", "") or "").strip().lower(), } banned = {x for x in banned if x} if low in banned: raise ValueError("直播推流 KEY 不能使用站点登录密码;请粘贴 YouTube Studio 的 Stream key(留空可后填)") return sk def create_group( *, name: str = "", channel_pk: str = "", youtube_channel_id: str = "", stream_key: str = "", note: str = "", enabled: bool = True, category: str = "normal", ) -> dict[str, Any]: from . import db now = time.time() gid = str(uuid.uuid4()) ch_pk = str(channel_pk or "").strip() yt_id = str(youtube_channel_id or "").strip() nm = str(name or "").strip() stream_key = _sanitize_stream_key(stream_key) cat = normalize_assign_category(category) if ch_pk: ch = db.get_shorts_channel(ch_pk) if ch: if not nm: nm = str(ch.get("name") or "").strip() if not yt_id: yt_id = str(ch.get("youtube_channel_id") or "").strip() if not nm: nm = yt_id or "未命名频道" with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) if ch_pk: hit = conn.execute( "SELECT id, name FROM yt_assign_groups WHERE channel_pk = ? LIMIT 1", (ch_pk,), ).fetchone() if hit: raise ValueError(f"该 Shorts 卡已分配给分组「{hit['name'] or hit['id']}」") if yt_id: hit = conn.execute( "SELECT id, name FROM yt_assign_groups WHERE youtube_channel_id = ? LIMIT 1", (yt_id,), ).fetchone() if hit: raise ValueError( f"YouTube 频道 {yt_id} 已分配给分组「{hit['name'] or hit['id']}」" ) max_ord = conn.execute("SELECT COALESCE(MAX(sort_order), 0) AS m FROM yt_assign_groups").fetchone() sort_order = int(max_ord["m"] if max_ord else 0) + 1 max_neko = conn.execute( "SELECT COALESCE(MAX(neko_instance_id), 0) AS m FROM yt_assign_groups" ).fetchone() from . import youtube_neko as _yn next_id = int(max_neko["m"] if max_neko else 0) + 1 cap = int(_yn._max_instances()) if next_id > cap: raise ValueError( f"Neko 实例已达上限 {cap}(DY_NEKO_MAX_INSTANCES / 边缘反代容量)。" "请删除闲置分组或提高上限并同步边缘 /neko 路由。" ) neko_instance_id = next_id conn.execute( """ INSERT INTO yt_assign_groups( id, name, channel_pk, youtube_channel_id, stream_key, note, enabled, sort_order, neko_instance_id, neko_enabled, category, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( gid, nm[:120], ch_pk, yt_id[:64], str(stream_key or "").strip(), str(note or "").strip()[:500], 1 if enabled else 0, sort_order, neko_instance_id, 0, cat, now, now, ), ) conn.commit() finally: conn.close() group = get_group(gid) or {"id": gid} neko_sync: dict[str, Any] = {"ok": True, "skipped": True} try: from . import youtube_neko # Never reconcile_running here — would stop exclusive-live Studio browsers. neko_sync = youtube_neko.sync_for_groups( list_groups(include_urls=False), reconcile_running=False, ) if not neko_sync.get("ok"): db.add_event( kind="ops", level="warn", message=f"Neko 容器创建失败:{neko_sync.get('error', 'unknown')[:160]}", meta={"group_id": gid, "neko_instance_id": neko_instance_id}, ) except Exception as exc: neko_sync = {"ok": False, "error": str(exc)[:300]} try: db.add_event( kind="ops", level="error", message=f"Neko sync 异常:{str(exc)[:160]}", meta={"group_id": gid}, ) except Exception: pass group["neko_sync"] = { "ok": bool(neko_sync.get("ok")), "neko_instance_id": neko_instance_id, "error": neko_sync.get("error") or "", "created": neko_sync.get("created"), } return group def update_group(group_id: str, **fields: Any) -> dict[str, Any]: from . import db allowed = { "name", "channel_pk", "youtube_channel_id", "stream_key", "note", "enabled", "sort_order", "neko_enabled", "category", "time_slot_armed", } patch: dict[str, Any] = {} for k, v in fields.items(): if k not in allowed or v is None: continue if k == "enabled": patch[k] = 1 if v else 0 elif k == "neko_enabled": patch[k] = 1 if v else 0 elif k == "time_slot_armed": patch[k] = 1 if v else 0 elif k == "category": patch[k] = normalize_assign_category(v) elif k == "sort_order": try: patch[k] = int(v) except Exception: continue elif k in {"name", "note", "stream_key", "youtube_channel_id", "channel_pk"}: patch[k] = str(v).strip() if k == "stream_key": patch[k] = _sanitize_stream_key(patch[k]) if k == "name": patch[k] = patch[k][:120] if k == "note": patch[k] = patch[k][:500] if k == "youtube_channel_id": patch[k] = patch[k][:64] else: patch[k] = v # Sync name/id from shorts channel when channel_pk changes if "channel_pk" in patch and patch["channel_pk"]: ch = db.get_shorts_channel(str(patch["channel_pk"])) if ch: yt_from_ch = str(ch.get("youtube_channel_id") or "").strip() if yt_from_ch: patch["youtube_channel_id"] = yt_from_ch[:64] if "name" not in patch or not patch.get("name"): patch["name"] = str(ch.get("name") or patch.get("name") or "")[:120] if not patch: g = get_group(group_id) if not g: raise ValueError("分组不存在") return g sets = [f"{k} = ?" for k in patch] params = list(patch.values()) sets.append("updated_at = ?") params.append(time.time()) params.append(group_id) with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) cur = conn.execute( f"UPDATE yt_assign_groups SET {', '.join(sets)} WHERE id = ?", params, ) if cur.rowcount == 0: raise ValueError("分组不存在") conn.commit() finally: conn.close() group = get_group(group_id) or {} if "neko_enabled" in patch: try: from . import youtube_neko # Never reconcile_running — exclusive-live / time-slot may leave # winner running with neko_enabled=0 and siblings flagged enabled. youtube_neko.sync_for_groups( list_groups(include_urls=False), reconcile_running=False, ) except Exception: pass return group def delete_group(group_id: str) -> dict[str, Any]: with _lock: conn = _connect() 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() result = {"ok": True, "deleted": int(n), "pool_deleted": int(n_pool)} finally: conn.close() try: from . import youtube_neko # Do not stop siblings — deleted group's container can linger until manual stop. youtube_neko.sync_for_groups(list_groups(include_urls=False), reconcile_running=False) except Exception: pass return result def add_pool_urls( group_id: str, urls: list[str] | None = None, *, note: str = "", text: str = "", items: list[dict[str, Any]] | None = None, ) -> dict[str, Any]: from .db import _is_blacklisted_conn parsed: list[dict[str, str]] = [] seen: set[str] = set() skipped_dup_in = 0 def _push(item: dict[str, str]) -> None: nonlocal skipped_dup_in u = str(item.get("url") or "").strip() if not u: return key = _dedupe_key(u, item.get("room_id") or "") if key in seen: skipped_dup_in += 1 return seen.add(key) parsed.append(item) for it in items or []: if not isinstance(it, dict): continue line = str(it.get("line") or "").strip() if line: p = parse_pool_line(line) if p: if it.get("title") and not p.get("title"): p["title"] = str(it.get("title") or "")[:120] _push(p) continue u = _normalize_url(str(it.get("url") or "")) if not u: continue _push( { "url": u[:500], "title": str(it.get("title") or "").strip()[:120], "room_id": str(it.get("room_id") or extract_room_id(u) or "")[:64], } ) blob = str(text or "").strip() if blob: for line in re.split(r"[\r\n]+", blob): p = parse_pool_line(line) if p: _push(p) for u in urls or []: p = parse_pool_line(str(u)) if p: _push(p) else: nu = _normalize_url(str(u)) if nu: _push({"url": nu[:500], "title": "", "room_id": extract_room_id(nu)[:64]}) if not parsed: raise ValueError("没有有效 URL") now = time.time() created: list[dict[str, Any]] = [] 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_pool_urls WHERE group_id = ?", (group_id,), ).fetchone() ord0 = int(max_ord["m"] if max_ord else 0) existing_keys: set[str] = set() for r in conn.execute( "SELECT url, room_id FROM yt_assign_pool_urls WHERE group_id = ?", (group_id,), ).fetchall(): existing_keys.add(_dedupe_key(str(r["url"] or ""), str(r["room_id"] or ""))) for item in parsed: url = item["url"] rid = item.get("room_id") or extract_room_id(url) key = _dedupe_key(url, rid) if key in existing_keys: skipped_dup += 1 continue hit = _is_blacklisted_conn(conn, rid, url) if hit: skipped_blacklist.append( { "url": url, "title": str(item.get("title") or ""), "reason": str(hit.get("reason") or hit.get("value") or "黑名单"), } ) continue title = str(item.get("title") or "").strip() cover, anchor = _lookup_cover_and_anchor(conn, rid) if not title and anchor: title = anchor uid = str(uuid.uuid4()) ord0 += 1 conn.execute( """ INSERT INTO yt_assign_pool_urls( id, group_id, url, note, title, room_id, cover_url, sort_order, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( uid, group_id, url[:500], str(note or "").strip()[:200], title[:120], (rid or "")[:64], (cover or "")[:800], ord0, now, now, ), ) # Unified live pool (rooms) — overview / monitor / live-map. try: from .douyin_ingest import ensure_in_live_pool_conn ensure_in_live_pool_conn( conn, url, note=title, title=title, enabled=True ) except Exception: pass created.append({"id": uid, "url": url, "title": title, "cover_url": cover}) existing_keys.add(key) conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (now, group_id)) conn.commit() finally: conn.close() return { "ok": True, "added": created, "skipped_dup": skipped_dup + skipped_dup_in, "skipped_blacklist": skipped_blacklist, "group": get_group(group_id), } def update_pool_url(pool_url_id: str, **fields: Any) -> dict[str, Any]: allowed = {"url", "note", "title", "cover_url", "room_id", "sort_order"} patch: dict[str, Any] = {} for k, v in fields.items(): if k not in allowed or v is None: continue if k == "url": patch[k] = _normalize_url(str(v))[:500] if not patch[k]: raise ValueError("URL 不能为空") patch["room_id"] = extract_room_id(patch[k])[:64] elif k in {"note", "title", "cover_url", "room_id"}: lim = 800 if k == "cover_url" else (120 if k == "title" else 200) patch[k] = str(v).strip()[:lim] elif k == "sort_order": patch[k] = int(v) if not patch: raise ValueError("无更新字段") sets = [f"{k} = ?" for k in patch] params = list(patch.values()) sets.append("updated_at = ?") params.append(time.time()) params.append(pool_url_id) with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) row = conn.execute("SELECT group_id FROM yt_assign_pool_urls WHERE id = ?", (pool_url_id,)).fetchone() if not row: raise ValueError("URL 不存在") gid = str(row["group_id"]) conn.execute(f"UPDATE yt_assign_pool_urls SET {', '.join(sets)} WHERE id = ?", params) 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 delete_pool_url(pool_url_id: str) -> dict[str, Any]: with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) row = conn.execute("SELECT group_id FROM yt_assign_pool_urls WHERE id = ?", (pool_url_id,)).fetchone() if not row: 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() finally: conn.close() return {"ok": True, "group": get_group(gid)} def add_featured(group_id: str, pool_url_ids: list[str]) -> dict[str, Any]: 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") # preserve order, unique 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_featured_urls WHERE group_id = ?", (group_id,), ).fetchone() ord0 = int(max_ord["m"] if max_ord else 0) # also dedupe by room_id already in featured feat_room_keys: set[str] = set() for r in conn.execute( """ SELECT p.url, p.room_id FROM yt_assign_featured_urls f JOIN yt_assign_pool_urls p ON p.id = f.pool_url_id WHERE f.group_id = ? """, (group_id,), ).fetchall(): feat_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_featured_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 feat_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_featured_urls(id, group_id, pool_url_id, sort_order, created_at) VALUES (?, ?, ?, ?, ?) """, (str(uuid.uuid4()), group_id, pid, ord0, now), ) feat_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 dedupe_group(group_id: str) -> dict[str, Any]: """Remove duplicate pool/featured entries by room_id (keep earliest).""" now = time.time() pool_removed = 0 feat_removed = 0 slot_removed = 0 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("分组不存在") rows = conn.execute( """ SELECT id, url, room_id FROM yt_assign_pool_urls WHERE group_id = ? ORDER BY sort_order ASC, created_at ASC """, (group_id,), ).fetchall() seen: set[str] = set() drop_pool: list[str] = [] for r in rows: key = _dedupe_key(str(r["url"] or ""), str(r["room_id"] or "")) if key in seen: drop_pool.append(str(r["id"])) else: 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) frows = conn.execute( """ SELECT f.id AS fid, p.url, p.room_id FROM yt_assign_featured_urls f JOIN yt_assign_pool_urls p ON p.id = f.pool_url_id WHERE f.group_id = ? ORDER BY f.sort_order ASC, f.created_at ASC """, (group_id,), ).fetchall() fseen: set[str] = set() for r in frows: key = _dedupe_key(str(r["url"] or ""), str(r["room_id"] or "")) if key in fseen: conn.execute("DELETE FROM yt_assign_featured_urls WHERE id = ?", (str(r["fid"]),)) 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: conn.close() return { "ok": True, "pool_removed": pool_removed, "featured_removed": feat_removed, "slot_removed": slot_removed, "group": get_group(group_id), } def purge_blacklisted(group_id: str, *, from_pool: bool = True, from_featured: bool = True) -> dict[str, Any]: """Remove blacklisted entries from pool and/or featured.""" from .db import _is_blacklisted_conn now = time.time() pool_removed = 0 feat_removed = 0 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("分组不存在") if from_featured: frows = conn.execute( """ SELECT f.id AS fid, p.url, p.room_id FROM yt_assign_featured_urls f JOIN yt_assign_pool_urls p ON p.id = f.pool_url_id WHERE f.group_id = ? """, (group_id,), ).fetchall() for r in frows: 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 = ?", (group_id,), ).fetchall() 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)) conn.commit() finally: conn.close() return { "ok": True, "pool_removed": pool_removed, "featured_removed": feat_removed, "slot_removed": slot_removed, "group": get_group(group_id), } def ban_pool_url(pool_url_id: str, *, reason: str = "分配页拉黑", remove_from_lists: bool = True) -> dict[str, Any]: """Add room to global blacklist; optionally remove from this group's pool/featured.""" from . import db with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) row = conn.execute("SELECT * FROM yt_assign_pool_urls WHERE id = ?", (pool_url_id,)).fetchone() if not row: raise ValueError("URL 不存在") gid = str(row["group_id"]) url = str(row["url"] or "") rid = str(row["room_id"] or "") or extract_room_id(url) title = str(row["title"] or "") finally: conn.close() value = rid or url existing = db.is_blacklisted(rid, url) if existing: bl = existing else: try: bl = db.add_blacklist(value, reason=reason or f"分配页拉黑 {title}".strip()) except Exception as exc: # UNIQUE value race / already exists bl = db.is_blacklisted(rid, url) or {"value": value, "error": str(exc)} removed = {"pool_removed": 0, "featured_removed": 0} if remove_from_lists: removed = purge_blacklisted(gid, from_pool=True, from_featured=True) return {"ok": True, "blacklist": bl, **removed, "group": get_group(gid)} def remove_featured(featured_id: str) -> dict[str, Any]: with _lock: conn = _connect() try: ensure_yt_assign_tables(conn) row = conn.execute( "SELECT group_id FROM yt_assign_featured_urls WHERE id = ?", (featured_id,), ).fetchone() if not row: raise ValueError("精选项不存在") gid = str(row["group_id"]) conn.execute("DELETE FROM yt_assign_featured_urls WHERE id = ?", (featured_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_featured_order(group_id: str, pool_url_ids: list[str]) -> dict[str, Any]: """Replace featured list order with given pool_url_ids (must belong to pool).""" from .db import _is_blacklisted_conn ids = [str(x).strip() for x in pool_url_ids if str(x).strip()] # unique preserve order + room dedupe 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_featured_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_featured_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 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 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 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)) except Exception: pass finally: conn.close() ranked.sort(key=lambda x: float(x.get("score") or 0), reverse=True) return ranked[: max(1, limit)] def _group_has_stream_key(g: dict[str, Any]) -> bool: if g.get("has_stream_key"): return True return bool(str(g.get("stream_key") or "").strip()) def _group_yt_channel_key(g: dict[str, Any]) -> str: """Stable YouTube channel identity for time-slot dedupe (not per stream key / assign group).""" meta = _group_yt_channel_meta(g) if meta.get("youtube_channel_id"): return f"yt:{meta['youtube_channel_id']}" pk = str(g.get("channel_pk") or "").strip() if pk: return f"pk:{pk}" return f"gid:{str(g.get('id') or '').strip()}" def _group_yt_channel_meta(g: dict[str, Any]) -> dict[str, str]: """Resolve YouTube channel id + display name from linked Shorts channel (source of truth).""" pk = str(g.get("channel_pk") or "").strip() yt = "" name = str(g.get("name") or "").strip() if pk: try: from . import db as _db ch = _db.get_shorts_channel(pk) if ch: yt = str(ch.get("youtube_channel_id") or "").strip() name = str(ch.get("name") or name).strip() except Exception: pass if not yt: yt = str(g.get("youtube_channel_id") or "").strip() return {"youtube_channel_id": yt, "display_name": name or str(g.get("name") or "")} def same_yt_channel(a: dict[str, Any], b: dict[str, Any]) -> bool: ka = _group_yt_channel_key(a) kb = _group_yt_channel_key(b) return bool(ka and kb and ka == kb) def _pick_canonical_group(groups: list[dict[str, Any]]) -> dict[str, Any]: """When multiple assign rows share one YouTube channel, pick one schedule row.""" return min( groups, key=lambda g: ( int(g.get("sort_order") or 0), 0 if g.get("neko_enabled") else 1, str(g.get("id") or ""), ), ) def _dedupe_groups_by_yt_channel(groups: list[dict[str, Any]]) -> list[tuple[dict[str, Any], list[str]]]: buckets: dict[str, list[dict[str, Any]]] = {} order: list[str] = [] for g in groups: key = _group_yt_channel_key(g) if key not in buckets: buckets[key] = [] order.append(key) buckets[key].append(g) out: list[tuple[dict[str, Any], list[str]]] = [] for key in order: gs = buckets[key] canonical = _pick_canonical_group(gs) cid = str(canonical.get("id") or "") aliases = [str(g.get("id") or "") for g in gs if str(g.get("id") or "") and str(g.get("id") or "") != cid] out.append((canonical, aliases)) out.sort(key=lambda pair: (int(pair[0].get("sort_order") or 0), str(pair[0].get("name") or ""))) return out def group_in_rotation_slot(group_id: str, *, keyed_only: bool | None = None) -> bool: """True when this assign group's YouTube channel is in the active 24/N window.""" gid = str(group_id or "").strip() if not gid: return False g = get_group(gid) if not g or not g.get("enabled"): return False if keyed_only is None: try: from . import db as _db keyed_only = bool(_db.get_settings_map().get("youtube_relay_time_slot_mode")) except Exception: keyed_only = False if keyed_only and not group_eligible_for_time_slot(g): return False ch_key = _group_yt_channel_key(g) sched = build_rotation_schedule(include_urls=False, keyed_only=keyed_only) for c in sched.get("channels") or []: if str(c.get("group_id") or "") == gid or gid in [str(x) for x in (c.get("alias_group_ids") or [])]: return bool(c.get("active")) slot_key = _group_yt_channel_key( { "youtube_channel_id": c.get("youtube_channel_id"), "channel_pk": c.get("channel_pk"), "id": c.get("group_id"), } ) if slot_key == ch_key: return bool(c.get("active")) return False if keyed_only else True def build_rotation_schedule( *, include_urls: bool = True, groups: list[dict[str, Any]] | None = None, keyed_only: bool | None = None, ) -> dict[str, Any]: """24h Beijing rotation with daily-stable random order & uneven lengths. Anti-bot: NOT equal 24/N splits and NOT fixed channel order. Seeded by Beijing calendar day + channel id set so the board stays stable within a day (and while relay polls) but reshuffles overnight. keyed_only=True (时间段模式): enabled groups with a stream key, deduped by YouTube channel (same channel + different keys still counts as one slot; keys may be wrong/backups). """ if groups is None: raw = list_groups(include_urls=include_urls) else: raw = groups if keyed_only is None: try: from . import db as _db # Prefer per-group 时间段 rows; fall back to legacy global toggle. has_slot = any(group_is_time_slot(g) for g in raw if g.get("enabled")) keyed_only = has_slot or bool(_db.get_settings_map().get("youtube_relay_time_slot_mode")) except Exception: keyed_only = False enabled = [g for g in raw if g.get("enabled")] if keyed_only: # 时间段排班:时间段分类 + 有 KEY + 开关开(关=等同无 KEY) keyed = [g for g in enabled if group_eligible_for_time_slot(g)] rotation_rows = _dedupe_groups_by_yt_channel(keyed) else: rotation_rows = [(g, []) for g in enabled] n = len(rotation_rows) now_h = _beijing_hour_fraction() day_key = _beijing_day_key() if n == 0: return { "ok": True, "channel_count": 0, "slot_hours": 0, "slot_hours_min": 0, "slot_hours_max": 0, "now_hour": round(now_h, 3), "now_label": _fmt_hour(now_h), "keyed_only": bool(keyed_only), "time_slot_mode": bool(keyed_only), "randomized": True, "schedule_day": day_key, "channels": [], } # Daily-stable shuffle (do not use sort_order as wall-clock order) id_key = ",".join( sorted(str((g.get("id") or "")) for g, _aliases in rotation_rows) ) seed = hashlib.sha256(f"yt-slot-v2|{day_key}|{id_key}".encode("utf-8")).hexdigest() rng = random.Random(seed) shuffled = list(rotation_rows) rng.shuffle(shuffled) windows = _daily_random_windows(n, seed=seed + "|win") channels: list[dict[str, Any]] = [] hour_vals: list[float] = [] for i, (g, alias_ids) in enumerate(shuffled): start_h, end_h, slot_h = windows[i] hour_vals.append(slot_h) active = _slot_active(now_h, start_h, end_h) 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]] = [] # Sub-windows follow the channel arc (may wrap); keep relative fractions for j, s in enumerate(slots_raw): u_start = (start_h + j * sub_h) % 24.0 u_end = (start_h + (j + 1) * sub_h) % 24.0 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), } ) meta = _group_yt_channel_meta(g) channels.append( { "group_id": g.get("id"), "name": meta.get("display_name") or g.get("name"), "channel_pk": g.get("channel_pk"), "youtube_channel_id": meta.get("youtube_channel_id") or g.get("youtube_channel_id"), "yt_channel_key": _group_yt_channel_key(g), "has_stream_key": _group_has_stream_key(g), "alias_group_ids": alias_ids, "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, } ) avg_h = (sum(hour_vals) / n) if n else 0.0 return { "ok": True, "channel_count": n, "slot_hours": round(avg_h, 2), "slot_hours_min": round(min(hour_vals), 2) if hour_vals else 0, "slot_hours_max": round(max(hour_vals), 2) if hour_vals else 0, "now_hour": round(now_h, 3), "now_label": _fmt_hour(now_h), "keyed_only": bool(keyed_only), "time_slot_mode": bool(keyed_only), "randomized": True, "schedule_day": day_key, "channels": channels, } def overlay_timeslot_test_schedule( schedule: dict[str, Any] | None, *, test_on: bool, test_group_id: str = "", ) -> dict[str, Any]: """Mark forced test winner as active for UI; keep real clock in schedule_active.""" out = dict(schedule or {}) want = str(test_group_id or "").strip() out["test_mode"] = bool(test_on) out["test_group_id"] = want if test_on else "" channels: list[dict[str, Any]] = [] for raw in out.get("channels") or []: if not isinstance(raw, dict): continue c = dict(raw) c["schedule_active"] = bool(c.get("active")) if test_on and want: gid = str(c.get("group_id") or "") aliases = [str(x) for x in (c.get("alias_group_ids") or []) if x] forced = gid == want or want in aliases c["active"] = forced c["test_force"] = forced else: c["test_force"] = False channels.append(c) out["channels"] = channels return out 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))) try: blocked = timeslot_exclude_room_ids(include_manual_featured=True) except Exception: blocked = set() if blocked: ranked = [r for r in ranked if str(r.get("room_id") or "").strip() not in blocked] if not ranked: 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: 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]] = [] 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, "filled": len(results), "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) TIMESLOT_EXCLUDE_SETTING_KEY = "youtube_relay_timeslot_exclude_urls" def parse_timeslot_exclude_text(text: str) -> dict[str, Any]: """Parse pasted Douyin live URLs / room ids into a deduped exclude list. Accepts multiline / comma-separated / pool-line formats. Not a blacklist — only blocks time_slot auto sources so they don't collide with manual lives. """ items: list[dict[str, str]] = [] seen: set[str] = set() skipped_dup = 0 skipped_invalid = 0 blob = str(text or "").strip().lstrip("\ufeff") if not blob: return { "ok": True, "items": [], "count": 0, "skipped_dup": 0, "skipped_invalid": 0, "text": "", } chunks: list[str] = [] for line in re.split(r"[\r\n]+", blob): line = line.strip() if not line: continue # Split comma-separated URLs on one line (keep 「主播: …」 with preceding url via parse_pool_line) if re.search(r"https?://", line) and ("," in line or "," in line): # Prefer whole-line parse first (url + 主播) p0 = parse_pool_line(line) if p0.get("url"): chunks.append(line) continue for part in re.split(r"[,,\s]+", line): part = part.strip() if part: chunks.append(part) else: chunks.append(line) for raw in chunks: p = parse_pool_line(raw) url = str(p.get("url") or "").strip() rid = str(p.get("room_id") or extract_room_id(raw) or "").strip() if not url and rid: url = normalize_room_url(rid) or f"https://live.douyin.com/{rid}" if not url and not rid: skipped_invalid += 1 continue if not rid: rid = extract_room_id(url) key = _dedupe_key(url, rid) if key in seen: skipped_dup += 1 continue seen.add(key) items.append( { "url": (normalize_room_url(url) or url)[:500], "room_id": rid[:64], "title": str(p.get("title") or "")[:120], } ) text_out = "\n".join( f"{it['url']}" + (f",主播: {it['title']}," if it.get("title") else "") for it in items ) return { "ok": True, "items": items, "count": len(items), "skipped_dup": skipped_dup, "skipped_invalid": skipped_invalid, "text": text_out, } def get_timeslot_exclude_items() -> list[dict[str, str]]: from . import db raw = db.get_settings_map().get(TIMESLOT_EXCLUDE_SETTING_KEY) items: list[dict[str, str]] = [] if isinstance(raw, list): for it in raw: if isinstance(it, str): p = parse_pool_line(it) if p.get("url") or p.get("room_id"): items.append( { "url": str(p.get("url") or "")[:500], "room_id": str(p.get("room_id") or "")[:64], "title": str(p.get("title") or "")[:120], } ) elif isinstance(it, dict): url = str(it.get("url") or "").strip() rid = str(it.get("room_id") or extract_room_id(url) or "").strip() if not url and rid: url = normalize_room_url(rid) or f"https://live.douyin.com/{rid}" if not url and not rid: continue items.append( { "url": (normalize_room_url(url) or url)[:500], "room_id": rid[:64], "title": str(it.get("title") or "")[:120], } ) elif isinstance(raw, str) and raw.strip(): items = list(parse_timeslot_exclude_text(raw).get("items") or []) # Final dedupe out: list[dict[str, str]] = [] seen: set[str] = set() for it in items: key = _dedupe_key(it.get("url") or "", it.get("room_id") or "") if key in seen: continue seen.add(key) out.append(it) return out def set_timeslot_exclude_text(text: str) -> dict[str, Any]: from . import db parsed = parse_timeslot_exclude_text(text) items = list(parsed.get("items") or []) db.update_settings_map({TIMESLOT_EXCLUDE_SETTING_KEY: items}) return { "ok": True, "items": items, "count": len(items), "skipped_dup": int(parsed.get("skipped_dup") or 0), "skipped_invalid": int(parsed.get("skipped_invalid") or 0), "text": str(parsed.get("text") or ""), } def import_timeslot_exclude_from_manual(*, merge: bool = True) -> dict[str, Any]: """Seed exclude list from 普通(manual) groups' featured Douyin URLs.""" existing = get_timeslot_exclude_items() if merge else [] seen = {_dedupe_key(it.get("url") or "", it.get("room_id") or "") for it in existing} added = 0 for g in list_groups(include_urls=True): if group_is_time_slot(g): continue for f in g.get("featured") or []: if f.get("blacklisted"): continue url = str(f.get("url") or "").strip() rid = str(f.get("room_id") or extract_room_id(url) or "").strip() if not url and not rid: continue if not url and rid: url = normalize_room_url(rid) or f"https://live.douyin.com/{rid}" key = _dedupe_key(url, rid) if key in seen: continue seen.add(key) existing.append( { "url": (normalize_room_url(url) or url)[:500], "room_id": rid[:64], "title": str(f.get("title") or f.get("pool_note") or "")[:120], } ) added += 1 from . import db db.update_settings_map({TIMESLOT_EXCLUDE_SETTING_KEY: existing}) text = "\n".join( f"{it['url']}" + (f",主播: {it['title']}," if it.get("title") else "") for it in existing ) return {"ok": True, "items": existing, "count": len(existing), "added": added, "text": text} def timeslot_exclude_room_ids(*, include_manual_featured: bool = True) -> set[str]: """Room ids time_slot relay / auto-fill must not use.""" out: set[str] = set() for it in get_timeslot_exclude_items(): rid = str(it.get("room_id") or extract_room_id(it.get("url") or "") or "").strip() if rid: out.add(rid) if include_manual_featured: for g in list_groups(include_urls=True): if group_is_time_slot(g): continue for f in g.get("featured") or []: if f.get("blacklisted"): continue rid = str(f.get("room_id") or extract_room_id(str(f.get("url") or "")) or "").strip() if rid: out.add(rid) return out def timeslot_exclude_status() -> dict[str, Any]: items = get_timeslot_exclude_items() manual_ids = timeslot_exclude_room_ids(include_manual_featured=True) stored_ids = timeslot_exclude_room_ids(include_manual_featured=False) text = "\n".join( f"{it['url']}" + (f",主播: {it['title']}," if it.get("title") else "") for it in items ) return { "ok": True, "items": items, "count": len(items), "text": text, "effective_room_count": len(manual_ids), "stored_room_count": len(stored_ids), "manual_featured_extra": max(0, len(manual_ids) - len(stored_ids)), }