677 lines
24 KiB
Python
677 lines
24 KiB
Python
# -*- 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 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:
|
||
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)
|
||
)
|
||
"""
|
||
)
|
||
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_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 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]:
|
||
out = dict(row)
|
||
out["enabled"] = bool(out.get("enabled"))
|
||
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 pool is not None:
|
||
out["pool"] = pool
|
||
if featured is not None:
|
||
out["featured"] = featured
|
||
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()
|
||
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:
|
||
out.append(_public_group(g, pool=[], featured=[]))
|
||
continue
|
||
gid = str(g.get("id") or "")
|
||
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 {}) 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:
|
||
conn.close()
|
||
|
||
|
||
def get_group(group_id: str) -> 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()
|
||
]
|
||
return _public_group(g, pool=pool, featured=featured) # type: ignore
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def create_group(
|
||
*,
|
||
name: str = "",
|
||
channel_pk: str = "",
|
||
youtube_channel_id: str = "",
|
||
stream_key: str = "",
|
||
note: str = "",
|
||
enabled: bool = True,
|
||
) -> 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()
|
||
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)
|
||
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
|
||
conn.execute(
|
||
"""
|
||
INSERT INTO yt_assign_groups(
|
||
id, name, channel_pk, youtube_channel_id, stream_key, note,
|
||
enabled, sort_order, 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,
|
||
now,
|
||
now,
|
||
),
|
||
)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
return get_group(gid) or {"id": gid}
|
||
|
||
|
||
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",
|
||
}
|
||
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 == "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 == "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:
|
||
if "name" not in patch or not patch.get("name"):
|
||
patch["name"] = str(ch.get("name") or patch.get("name") or "")[:120]
|
||
if "youtube_channel_id" not in patch or not patch.get("youtube_channel_id"):
|
||
patch["youtube_channel_id"] = str(ch.get("youtube_channel_id") or "")[:64]
|
||
|
||
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()
|
||
return get_group(group_id) or {}
|
||
|
||
|
||
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,))
|
||
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()
|
||
return {"ok": True, "deleted": int(n), "pool_deleted": int(n_pool)}
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
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:
|
||
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 = {
|
||
str(r["url"])
|
||
for r in conn.execute(
|
||
"SELECT url FROM yt_assign_pool_urls WHERE group_id = ?",
|
||
(group_id,),
|
||
).fetchall()
|
||
}
|
||
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, 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,
|
||
),
|
||
)
|
||
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:
|
||
conn.close()
|
||
return {"ok": True, "added": created, "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_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]:
|
||
ids = [str(x).strip() for x in pool_url_ids if str(x).strip()]
|
||
if not ids:
|
||
raise ValueError("未选择普通列表 URL")
|
||
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("分组不存在")
|
||
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)
|
||
for pid in ids:
|
||
pool = conn.execute(
|
||
"SELECT id 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:
|
||
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),
|
||
)
|
||
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 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)."""
|
||
ids = [str(x).strip() for x in pool_url_ids if str(x).strip()]
|
||
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,))
|
||
for i, pid in enumerate(ids):
|
||
pool = conn.execute(
|
||
"SELECT id FROM yt_assign_pool_urls WHERE id = ? AND group_id = ?",
|
||
(pid, group_id),
|
||
).fetchone()
|
||
if not pool:
|
||
continue
|
||
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, i + 1, 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)}
|