diff --git a/backend/app/main.py b/backend/app/main.py index f7fdf11..9834128 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2536,7 +2536,13 @@ async def yt_assign_add_pool(group_id: str, body: YtAssignPoolAdd) -> dict[str, if body.url and str(body.url).strip(): urls.append(str(body.url).strip()) try: - return yt_assign_db.add_pool_urls(group_id, urls, note=body.note) + return yt_assign_db.add_pool_urls( + group_id, + urls, + note=body.note, + text=body.text, + items=list(body.items or []), + ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc diff --git a/backend/app/models.py b/backend/app/models.py index e4f1750..a79f94b 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -358,11 +358,16 @@ class YtAssignPoolAdd(BaseModel): urls: list[str] = [] url: str = "" note: str = "" + text: str = "" + items: list[dict[str, Any]] = Field(default_factory=list) class YtAssignPoolUpdate(BaseModel): url: Optional[str] = None note: Optional[str] = None + title: Optional[str] = None + cover_url: Optional[str] = None + room_id: Optional[str] = None sort_order: Optional[int] = None diff --git a/backend/app/yt_assign_db.py b/backend/app/yt_assign_db.py index 99d5cbf..19239c5 100644 --- a/backend/app/yt_assign_db.py +++ b/backend/app/yt_assign_db.py @@ -6,12 +6,14 @@ shorts_channels for OAuth profile cards on /youtube. """ from __future__ import annotations +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 def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None: @@ -38,6 +40,9 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None: 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 @@ -56,6 +61,14 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None: ) """ ) + 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)" ) @@ -65,10 +78,108 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None: 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_pool_room ON yt_assign_pool_urls(room_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: + 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 = str(row["cover_path"] or "").strip() + anchor = 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() + room = conn.execute( + "SELECT last_anchor FROM rooms WHERE room_id = ? LIMIT 1", + (rid,), + ).fetchone() + if room: + anchor = anchor or str(room["last_anchor"] 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]) -> dict[str, Any]: + 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 + return out def _normalize_url(url: str) -> str: - return str(url or "").strip() + 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]: @@ -77,7 +188,6 @@ def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: li 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 "") - # Keep full key for authenticated admin UI; frontend can mask with Eye toggle if pool is not None: out["pool"] = pool if featured is not None: @@ -85,6 +195,17 @@ def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: li return out +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) -> list[dict[str, Any]]: with _lock: conn = _connect() @@ -104,18 +225,9 @@ def list_groups(*, include_urls: bool = True) -> list[dict[str, Any]]: "SELECT * FROM yt_assign_pool_urls WHERE group_id = ? ORDER BY sort_order ASC, created_at ASC", (gid,), ).fetchall() - pool = [_row_to_dict(x) for x in pool_rows] # type: ignore - feat_rows = conn.execute( - """ - SELECT f.*, p.url AS url, p.note AS pool_note - 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 - """, - (gid,), - ).fetchall() - featured = [_row_to_dict(x) for x in feat_rows] # type: ignore + 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)) return out finally: @@ -133,24 +245,15 @@ def get_group(group_id: str) -> dict[str, Any] | None: g = _row_to_dict(row) # type: ignore gid = str(g.get("id") or "") pool = [ - _row_to_dict(x) + _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 = [ - _row_to_dict(x) - for x in conn.execute( - """ - SELECT f.*, p.url AS url, p.note AS pool_note - 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 - """, - (gid,), - ).fetchall() + _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 finally: @@ -298,14 +401,65 @@ def delete_group(group_id: str) -> dict[str, Any]: conn.close() -def add_pool_urls(group_id: str, urls: list[str], *, note: str = "") -> dict[str, Any]: - clean = [] - for u in urls: - s = _normalize_url(u) - if s and s not in clean: - clean.append(s) - if not clean: +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]: + parsed: list[dict[str, str]] = [] + seen: set[str] = set() + + def _push(item: dict[str, str]) -> None: + u = str(item.get("url") or "").strip() + if not u or u in seen: + return + seen.add(u) + 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]] = [] with _lock: @@ -327,19 +481,39 @@ def add_pool_urls(group_id: str, urls: list[str], *, note: str = "") -> dict[str (group_id,), ).fetchall() } - for i, url in enumerate(clean): + for item in parsed: + url = item["url"] if url in existing: continue + rid = item.get("room_id") or extract_room_id(url) + 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, sort_order, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?) + 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], ord0, now, now), + ( + uid, + group_id, + url[:500], + str(note or "").strip()[:200], + title[:120], + (rid or "")[:64], + (cover or "")[:800], + ord0, + now, + now, + ), ) - created.append({"id": uid, "url": url}) + created.append({"id": uid, "url": url, "title": title, "cover_url": cover}) + existing.add(url) conn.execute("UPDATE yt_assign_groups SET updated_at = ? WHERE id = ?", (now, group_id)) conn.commit() finally: @@ -348,7 +522,7 @@ def add_pool_urls(group_id: str, urls: list[str], *, note: str = "") -> dict[str def update_pool_url(pool_url_id: str, **fields: Any) -> dict[str, Any]: - allowed = {"url", "note", "sort_order"} + 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: @@ -357,8 +531,10 @@ def update_pool_url(pool_url_id: str, **fields: Any) -> dict[str, Any]: patch[k] = _normalize_url(str(v))[:500] if not patch[k]: raise ValueError("URL 不能为空") - elif k == "note": - patch[k] = str(v).strip()[:200] + 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: diff --git a/frontend/src/components/YtAssignPanel.tsx b/frontend/src/components/YtAssignPanel.tsx index b32105c..9d9eaf9 100644 --- a/frontend/src/components/YtAssignPanel.tsx +++ b/frontend/src/components/YtAssignPanel.tsx @@ -2,9 +2,20 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import Link from "next/link"; -import { Eye, EyeOff, Loader2, Plus, RefreshCw, Star, Trash2 } from "lucide-react"; +import { + Copy, + Download, + Eye, + EyeOff, + Loader2, + Plus, + RefreshCw, + Star, + Trash2, +} from "lucide-react"; import { useConfirm } from "@/components/ConfirmDialog"; +import { ImageLightbox } from "@/components/ImageLightbox"; import { useToast } from "@/components/Toast"; import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; @@ -22,6 +33,9 @@ type PoolUrl = { id: string; url: string; note?: string; + title?: string; + room_id?: string; + cover_url?: string; }; type FeaturedUrl = { @@ -29,6 +43,9 @@ type FeaturedUrl = { pool_url_id: string; url?: string; pool_note?: string; + title?: string; + room_id?: string; + cover_url?: string; }; type AssignGroup = { @@ -45,6 +62,48 @@ type AssignGroup = { featured?: FeaturedUrl[]; }; +function formatExportLine(url: string, title?: string): string { + const u = String(url || "").trim(); + const t = String(title || "").trim(); + if (!u) return ""; + return t ? `${u},主播: ${t},` : `${u},`; +} + +function exportText(rows: Array<{ url?: string; title?: string }>): string { + return rows + .map((r) => formatExportLine(String(r.url || ""), r.title)) + .filter(Boolean) + .join("\n"); +} + +async function copyText(text: string): Promise { + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + try { + const ta = document.createElement("textarea"); + ta.value = text; + document.body.appendChild(ta); + ta.select(); + document.execCommand("copy"); + document.body.removeChild(ta); + return true; + } catch { + return false; + } + } +} + +function downloadText(filename: string, text: string) { + const blob = new Blob([text], { type: "text/plain;charset=utf-8" }); + const a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = filename; + a.click(); + URL.revokeObjectURL(a.href); +} + function ManageStyleProfileCard({ profile, channelPk, @@ -90,6 +149,32 @@ function ManageStyleProfileCard({ ); } +function CoverThumb({ + cover, + title, + onOpen, +}: { + cover?: string; + title?: string; + onOpen: (src: string) => void; +}) { + const src = String(cover || "").trim(); + if (!src) { + return
; + } + return ( + + ); +} + export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { const confirm = useConfirm(); const toast = useToast(); @@ -97,12 +182,15 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { const [groupId, setGroupId] = useState(""); const [profiles, setProfiles] = useState>({}); const [busy, setBusy] = useState(false); - const [showKey, setShowKey] = useState(false); + const [showKey, setShowKey] = useState(true); const [streamKeyDraft, setStreamKeyDraft] = useState(""); const [noteDraft, setNoteDraft] = useState(""); const [poolDraft, setPoolDraft] = useState(""); const [newChannelPk, setNewChannelPk] = useState(""); const [newStreamKey, setNewStreamKey] = useState(""); + const [lightbox, setLightbox] = useState<{ src: string; title?: string; subtitle?: string } | null>( + null + ); const selected = useMemo(() => groups.find((g) => g.id === groupId) || null, [groups, groupId]); const featuredIds = useMemo( @@ -138,7 +226,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { const live = await fetchJson(`/api/youtube/manage/${channelPk}/profile`); setProfiles((p) => ({ ...p, [channelPk]: live })); } catch { - // keep fallback name on card + // keep fallback } }, []); @@ -154,7 +242,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { } setStreamKeyDraft(String(selected.stream_key || "")); setNoteDraft(String(selected.note || "")); - setShowKey(false); + setShowKey(true); if (selected.channel_pk) void loadProfile(selected.channel_pk); }, [selected, loadProfile]); @@ -228,22 +316,20 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { async function addPoolUrls() { if (!selected) return; - const urls = poolDraft - .split(/[\n,]+/) - .map((s) => s.trim()) - .filter(Boolean); - if (!urls.length) { - toast.push("请粘贴抖音直播间 URL", "err"); + const text = poolDraft.trim(); + if (!text) { + toast.push("请粘贴抖音直播间(支持 URL,主播: 名称,)", "err"); return; } setBusy(true); try { - await fetchJson(`/api/youtube/assign/groups/${selected.id}/pool`, { + const r = await fetchJson(`/api/youtube/assign/groups/${selected.id}/pool`, { method: "POST", - body: JSON.stringify({ urls }), + body: JSON.stringify({ text }), }); setPoolDraft(""); - toast.push(`已加入普通列表 ${urls.length} 条`, "ok"); + const n = Array.isArray(r?.added) ? r.added.length : 0; + toast.push(`已加入普通列表 ${n} 条`, "ok"); await loadGroups(); } catch (e) { toast.push((e as Error).message, "err"); @@ -299,6 +385,38 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { } } + async function copyList(kind: "pool" | "featured") { + if (!selected) return; + const rows = + kind === "pool" + ? selected.pool || [] + : (selected.featured || []).map((f) => ({ url: f.url, title: f.title })); + 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"); + } + + function exportList(kind: "pool" | "featured") { + if (!selected) return; + const rows = + kind === "pool" + ? selected.pool || [] + : (selected.featured || []).map((f) => ({ url: f.url, title: f.title })); + const text = exportText(rows); + if (!text) { + toast.push("列表为空", "err"); + return; + } + const tag = kind === "pool" ? "pool" : "featured"; + const name = String(selected.name || "assign").replace(/[\\/:*?"<>|]+/g, "_").slice(0, 40); + downloadText(`${name}-${tag}.txt`, text); + toast.push(`已导出 ${rows.length} 条`, "ok"); + } + const usedChannelPks = useMemo(() => new Set(groups.map((g) => String(g.channel_pk || ""))), [groups]); const availableChannels = channels.filter((c) => !usedChannelPks.has(c.id)); @@ -309,7 +427,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {

转播分配

- 频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播用)。频道资料复用 OAuth 管理卡片。 + 频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。

@@ -455,15 +574,39 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
-

- 普通列表(URL 池)· {(selected.pool || []).length} -

-

分配给该频道的抖音直播间 URL,可增删。

+
+

+ 普通列表(URL 池)· {(selected.pool || []).length} +

+
+ + +
+
+

+ 支持:https://live.douyin.com/房间号,主播: 名称, +