feat: show OAuth channel profile on Shorts/yt-long quota cards
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
1febe0869e
commit
c9e29cc6e6
@ -322,10 +322,12 @@ def init_db() -> None:
|
|||||||
from . import x2_db as _x2_db
|
from . import x2_db as _x2_db
|
||||||
from . import x_clips_db as _x_clips_db
|
from . import x_clips_db as _x_clips_db
|
||||||
from . import yt_long_db as _yt_long_db
|
from . import yt_long_db as _yt_long_db
|
||||||
|
from . import yt_assign_db as _yt_assign_db
|
||||||
|
|
||||||
_x2_db.ensure_x2_tables(conn)
|
_x2_db.ensure_x2_tables(conn)
|
||||||
_x_clips_db.ensure_x_clips_tables(conn)
|
_x_clips_db.ensure_x_clips_tables(conn)
|
||||||
_yt_long_db.ensure_yt_long_tables(conn)
|
_yt_long_db.ensure_yt_long_tables(conn)
|
||||||
|
_yt_assign_db.ensure_yt_assign_tables(conn)
|
||||||
_caption_pool.ensure_caption_pool_table(conn)
|
_caption_pool.ensure_caption_pool_table(conn)
|
||||||
_caption_pool.seed_caption_pool(conn)
|
_caption_pool.seed_caption_pool(conn)
|
||||||
sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()}
|
sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()}
|
||||||
@ -340,6 +342,8 @@ def init_db() -> None:
|
|||||||
("last_live_video_id", "TEXT NOT NULL DEFAULT ''"),
|
("last_live_video_id", "TEXT NOT NULL DEFAULT ''"),
|
||||||
("active_session_id", "TEXT NOT NULL DEFAULT ''"),
|
("active_session_id", "TEXT NOT NULL DEFAULT ''"),
|
||||||
("oauth_profile_id", "TEXT NOT NULL DEFAULT ''"),
|
("oauth_profile_id", "TEXT NOT NULL DEFAULT ''"),
|
||||||
|
("yt_profile_json", "TEXT NOT NULL DEFAULT ''"),
|
||||||
|
("yt_profile_at", "REAL NOT NULL DEFAULT 0"),
|
||||||
]:
|
]:
|
||||||
if col not in sc_cols:
|
if col not in sc_cols:
|
||||||
conn.execute(f"ALTER TABLE shorts_channels ADD COLUMN {col} {ddl}")
|
conn.execute(f"ALTER TABLE shorts_channels ADD COLUMN {col} {ddl}")
|
||||||
@ -2970,6 +2974,8 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]:
|
|||||||
"oauth_ok",
|
"oauth_ok",
|
||||||
"oauth_checked_at",
|
"oauth_checked_at",
|
||||||
"oauth_error",
|
"oauth_error",
|
||||||
|
"yt_profile_json",
|
||||||
|
"yt_profile_at",
|
||||||
}
|
}
|
||||||
with _lock:
|
with _lock:
|
||||||
conn = _connect()
|
conn = _connect()
|
||||||
|
|||||||
@ -26,6 +26,7 @@ from fastapi.staticfiles import StaticFiles
|
|||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from . import cookie_loader, db, pb_sync, shorts_oauth, tiktok_db, youtube_client, youtube_manage
|
from . import cookie_loader, db, pb_sync, shorts_oauth, tiktok_db, youtube_client, youtube_manage
|
||||||
|
from . import yt_assign_db
|
||||||
from .config import settings
|
from .config import settings
|
||||||
from .cover import cover_path_for, ensure_session_cover
|
from .cover import cover_path_for, ensure_session_cover
|
||||||
from .douyin import check_room
|
from .douyin import check_room
|
||||||
@ -54,6 +55,12 @@ from .models import (
|
|||||||
TikTokUploadNowBody,
|
TikTokUploadNowBody,
|
||||||
X2IngestBody,
|
X2IngestBody,
|
||||||
YouTubeVideoUpdate,
|
YouTubeVideoUpdate,
|
||||||
|
YtAssignFeaturedAdd,
|
||||||
|
YtAssignFeaturedSet,
|
||||||
|
YtAssignGroupCreate,
|
||||||
|
YtAssignGroupUpdate,
|
||||||
|
YtAssignPoolAdd,
|
||||||
|
YtAssignPoolUpdate,
|
||||||
)
|
)
|
||||||
from .monitor import monitor
|
from .monitor import monitor
|
||||||
from .stats import summarize_anchor_schedule, summarize_sessions
|
from .stats import summarize_anchor_schedule, summarize_sessions
|
||||||
@ -511,6 +518,11 @@ async def shorts_status() -> dict[str, Any]:
|
|||||||
cfg = await _db(db.get_settings_map)
|
cfg = await _db(db.get_settings_map)
|
||||||
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
|
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
|
||||||
st["oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True)
|
st["oauth_profiles"] = shorts_oauth.list_oauth_profiles(cfg, public=True)
|
||||||
|
# Soft-refresh a few stale OAuth channel profile cards (non-blocking)
|
||||||
|
try:
|
||||||
|
asyncio.create_task(youtube_manage.refresh_stale_yt_profiles(limit=3))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
return st
|
return st
|
||||||
|
|
||||||
|
|
||||||
@ -1182,6 +1194,10 @@ async def x_clips_job_retry(job_id: str) -> dict[str, Any]:
|
|||||||
|
|
||||||
@app.get("/api/yt-long/status")
|
@app.get("/api/yt-long/status")
|
||||||
async def yt_long_status() -> dict[str, Any]:
|
async def yt_long_status() -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
asyncio.create_task(youtube_manage.refresh_stale_yt_profiles(limit=3))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
return await asyncio.to_thread(yt_long_pipeline.status)
|
return await asyncio.to_thread(yt_long_pipeline.status)
|
||||||
|
|
||||||
|
|
||||||
@ -2382,6 +2398,19 @@ async def youtube_manage_channels() -> dict[str, Any]:
|
|||||||
return {"channels": youtube_manage.list_managed_channels()}
|
return {"channels": youtube_manage.list_managed_channels()}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/manage/profiles")
|
||||||
|
async def youtube_manage_profiles() -> dict[str, Any]:
|
||||||
|
return {"profiles": youtube_manage.list_yt_profile_caches()}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/manage/profiles/refresh")
|
||||||
|
async def youtube_manage_profiles_refresh(
|
||||||
|
max_age_sec: float = Query(3600, ge=0, le=86400 * 7),
|
||||||
|
limit: int = Query(8, ge=1, le=30),
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return await youtube_manage.refresh_stale_yt_profiles(max_age_sec=max_age_sec, limit=limit)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/youtube/manage/{channel_pk}/profile")
|
@app.get("/api/youtube/manage/{channel_pk}/profile")
|
||||||
async def youtube_manage_profile(channel_pk: str) -> dict[str, Any]:
|
async def youtube_manage_profile(channel_pk: str) -> dict[str, Any]:
|
||||||
try:
|
try:
|
||||||
@ -2452,6 +2481,109 @@ async def youtube_manage_playlists(channel_pk: str) -> dict[str, Any]:
|
|||||||
raise HTTPException(400, str(exc)) from exc
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
# ── YouTube assign: channel + stream key → pool → featured ──────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/assign/groups")
|
||||||
|
async def yt_assign_list_groups() -> dict[str, Any]:
|
||||||
|
return {"groups": yt_assign_db.list_groups(include_urls=True)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/assign/groups")
|
||||||
|
async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
g = yt_assign_db.create_group(
|
||||||
|
name=body.name,
|
||||||
|
channel_pk=body.channel_pk,
|
||||||
|
youtube_channel_id=body.youtube_channel_id,
|
||||||
|
stream_key=body.stream_key,
|
||||||
|
note=body.note,
|
||||||
|
enabled=body.enabled,
|
||||||
|
)
|
||||||
|
return {"ok": True, "group": g}
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/assign/groups/{group_id}")
|
||||||
|
async def yt_assign_get_group(group_id: str) -> dict[str, Any]:
|
||||||
|
g = yt_assign_db.get_group(group_id)
|
||||||
|
if not g:
|
||||||
|
raise HTTPException(404, "分组不存在")
|
||||||
|
return {"group": g}
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/youtube/assign/groups/{group_id}")
|
||||||
|
async def yt_assign_update_group(group_id: str, body: YtAssignGroupUpdate) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
g = yt_assign_db.update_group(
|
||||||
|
group_id,
|
||||||
|
**body.model_dump(exclude_unset=True),
|
||||||
|
)
|
||||||
|
return {"ok": True, "group": g}
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/youtube/assign/groups/{group_id}")
|
||||||
|
async def yt_assign_delete_group(group_id: str) -> dict[str, Any]:
|
||||||
|
return yt_assign_db.delete_group(group_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/assign/groups/{group_id}/pool")
|
||||||
|
async def yt_assign_add_pool(group_id: str, body: YtAssignPoolAdd) -> dict[str, Any]:
|
||||||
|
urls = list(body.urls or [])
|
||||||
|
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)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/youtube/assign/pool/{pool_url_id}")
|
||||||
|
async def yt_assign_update_pool(pool_url_id: str, body: YtAssignPoolUpdate) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return yt_assign_db.update_pool_url(pool_url_id, **body.model_dump(exclude_unset=True))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/youtube/assign/pool/{pool_url_id}")
|
||||||
|
async def yt_assign_delete_pool(pool_url_id: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return yt_assign_db.delete_pool_url(pool_url_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/assign/groups/{group_id}/featured")
|
||||||
|
async def yt_assign_add_featured(group_id: str, body: YtAssignFeaturedAdd) -> dict[str, Any]:
|
||||||
|
ids = list(body.pool_url_ids or [])
|
||||||
|
if body.pool_url_id and str(body.pool_url_id).strip():
|
||||||
|
ids.append(str(body.pool_url_id).strip())
|
||||||
|
try:
|
||||||
|
return yt_assign_db.add_featured(group_id, ids)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.put("/api/youtube/assign/groups/{group_id}/featured")
|
||||||
|
async def yt_assign_set_featured(group_id: str, body: YtAssignFeaturedSet) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return yt_assign_db.set_featured_order(group_id, body.pool_url_ids or [])
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/youtube/assign/featured/{featured_id}")
|
||||||
|
async def yt_assign_remove_featured(featured_id: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return yt_assign_db.remove_featured(featured_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/youtube/resolve")
|
@app.get("/api/youtube/resolve")
|
||||||
async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]:
|
async def youtube_resolve(url: str = Query(..., min_length=1)) -> dict[str, Any]:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -335,6 +335,46 @@ class X2IngestBody(BaseModel):
|
|||||||
ts: str = ""
|
ts: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class YtAssignGroupCreate(BaseModel):
|
||||||
|
name: str = ""
|
||||||
|
channel_pk: str = ""
|
||||||
|
youtube_channel_id: str = ""
|
||||||
|
stream_key: str = ""
|
||||||
|
note: str = ""
|
||||||
|
enabled: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
class YtAssignGroupUpdate(BaseModel):
|
||||||
|
name: Optional[str] = None
|
||||||
|
channel_pk: Optional[str] = None
|
||||||
|
youtube_channel_id: Optional[str] = None
|
||||||
|
stream_key: Optional[str] = None
|
||||||
|
note: Optional[str] = None
|
||||||
|
enabled: Optional[bool] = None
|
||||||
|
sort_order: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class YtAssignPoolAdd(BaseModel):
|
||||||
|
urls: list[str] = []
|
||||||
|
url: str = ""
|
||||||
|
note: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class YtAssignPoolUpdate(BaseModel):
|
||||||
|
url: Optional[str] = None
|
||||||
|
note: Optional[str] = None
|
||||||
|
sort_order: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class YtAssignFeaturedAdd(BaseModel):
|
||||||
|
pool_url_ids: list[str] = []
|
||||||
|
pool_url_id: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class YtAssignFeaturedSet(BaseModel):
|
||||||
|
pool_url_ids: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
class YouTubeVideoUpdate(BaseModel):
|
class YouTubeVideoUpdate(BaseModel):
|
||||||
title: Optional[str] = None
|
title: Optional[str] = None
|
||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
|
|||||||
@ -9,6 +9,7 @@ from typing import Any
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from . import db
|
from . import db
|
||||||
|
from . import youtube_manage
|
||||||
from .timeutil import beijing_day_bounds, beijing_from_ts, beijing_now, push_date_from_ts
|
from .timeutil import beijing_day_bounds, beijing_from_ts, beijing_now, push_date_from_ts
|
||||||
|
|
||||||
|
|
||||||
@ -241,6 +242,7 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
|
|||||||
"min_met": min_met,
|
"min_met": min_met,
|
||||||
"max_met": used >= daily_max,
|
"max_met": used >= daily_max,
|
||||||
"behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min),
|
"behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min),
|
||||||
|
"yt_profile": youtube_manage._snippet_from_channel_row(c),
|
||||||
**stats,
|
**stats,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|||||||
@ -13,6 +13,18 @@ from .shorts_upload import refresh_access_token
|
|||||||
|
|
||||||
API = "https://www.googleapis.com/youtube/v3"
|
API = "https://www.googleapis.com/youtube/v3"
|
||||||
|
|
||||||
|
_refresh_profiles_lock: Optional[Any] = None
|
||||||
|
_refresh_profiles_running = False
|
||||||
|
|
||||||
|
|
||||||
|
def _get_refresh_lock():
|
||||||
|
global _refresh_profiles_lock
|
||||||
|
if _refresh_profiles_lock is None:
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
_refresh_profiles_lock = asyncio.Lock()
|
||||||
|
return _refresh_profiles_lock
|
||||||
|
|
||||||
|
|
||||||
async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]:
|
async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]:
|
||||||
ch = db.get_shorts_channel(channel_pk)
|
ch = db.get_shorts_channel(channel_pk)
|
||||||
@ -126,14 +138,22 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
|
|||||||
uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads") or ""
|
uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads") or ""
|
||||||
sn = item.get("snippet") or {}
|
sn = item.get("snippet") or {}
|
||||||
st = item.get("statistics") or {}
|
st = item.get("statistics") or {}
|
||||||
return {
|
thumbs = sn.get("thumbnails") or {}
|
||||||
|
thumb_url = (
|
||||||
|
((thumbs.get("medium") or {}).get("url"))
|
||||||
|
or ((thumbs.get("default") or {}).get("url"))
|
||||||
|
or ((thumbs.get("high") or {}).get("url"))
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
profile = {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"channel_pk": channel_pk,
|
"channel_pk": channel_pk,
|
||||||
"youtube_channel_id": yt_id,
|
"youtube_channel_id": yt_id,
|
||||||
"title": sn.get("title"),
|
"title": sn.get("title"),
|
||||||
"description": sn.get("description"),
|
"description": sn.get("description"),
|
||||||
"custom_url": sn.get("customUrl"),
|
"custom_url": sn.get("customUrl"),
|
||||||
"thumbnails": sn.get("thumbnails"),
|
"thumbnails": thumbs,
|
||||||
|
"thumb_url": thumb_url,
|
||||||
"uploads_playlist_id": uploads,
|
"uploads_playlist_id": uploads,
|
||||||
"statistics": {
|
"statistics": {
|
||||||
"viewCount": st.get("viewCount"),
|
"viewCount": st.get("viewCount"),
|
||||||
@ -143,6 +163,140 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
|
|||||||
},
|
},
|
||||||
"raw": item,
|
"raw": item,
|
||||||
}
|
}
|
||||||
|
try:
|
||||||
|
save_yt_profile_cache(channel_pk, profile)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return profile
|
||||||
|
|
||||||
|
|
||||||
|
def profile_snippet(profile: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||||
|
if not profile:
|
||||||
|
return None
|
||||||
|
stats = profile.get("statistics") if isinstance(profile.get("statistics"), dict) else {}
|
||||||
|
thumbs = profile.get("thumbnails") if isinstance(profile.get("thumbnails"), dict) else {}
|
||||||
|
thumb_url = str(profile.get("thumb_url") or "").strip() or (
|
||||||
|
((thumbs.get("medium") or {}).get("url"))
|
||||||
|
or ((thumbs.get("default") or {}).get("url"))
|
||||||
|
or ((thumbs.get("high") or {}).get("url"))
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"title": profile.get("title") or "",
|
||||||
|
"custom_url": profile.get("custom_url") or "",
|
||||||
|
"youtube_channel_id": profile.get("youtube_channel_id") or "",
|
||||||
|
"thumb_url": thumb_url,
|
||||||
|
"thumbnails": {
|
||||||
|
"default": {"url": ((thumbs.get("default") or {}).get("url")) or thumb_url},
|
||||||
|
"medium": {"url": ((thumbs.get("medium") or {}).get("url")) or thumb_url},
|
||||||
|
},
|
||||||
|
"statistics": {
|
||||||
|
"subscriberCount": stats.get("subscriberCount"),
|
||||||
|
"videoCount": stats.get("videoCount"),
|
||||||
|
"viewCount": stats.get("viewCount"),
|
||||||
|
},
|
||||||
|
"fetched_at": profile.get("fetched_at") or 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def save_yt_profile_cache(channel_pk: str, profile: dict[str, Any]) -> None:
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
snippet = profile_snippet(profile) or {}
|
||||||
|
snippet["fetched_at"] = time.time()
|
||||||
|
# Drop heavy raw if present
|
||||||
|
payload = {
|
||||||
|
"title": snippet.get("title"),
|
||||||
|
"custom_url": snippet.get("custom_url"),
|
||||||
|
"youtube_channel_id": snippet.get("youtube_channel_id"),
|
||||||
|
"thumb_url": snippet.get("thumb_url"),
|
||||||
|
"thumbnails": snippet.get("thumbnails"),
|
||||||
|
"statistics": snippet.get("statistics"),
|
||||||
|
"fetched_at": snippet.get("fetched_at"),
|
||||||
|
}
|
||||||
|
db.update_shorts_channel(
|
||||||
|
channel_pk,
|
||||||
|
yt_profile_json=json.dumps(payload, ensure_ascii=False),
|
||||||
|
yt_profile_at=float(snippet["fetched_at"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_yt_profile_cache(channel_pk: str) -> dict[str, Any] | None:
|
||||||
|
import json
|
||||||
|
|
||||||
|
ch = db.get_shorts_channel(channel_pk)
|
||||||
|
if not ch:
|
||||||
|
return None
|
||||||
|
return _snippet_from_channel_row(ch)
|
||||||
|
|
||||||
|
|
||||||
|
def _snippet_from_channel_row(ch: dict[str, Any]) -> dict[str, Any] | None:
|
||||||
|
import json
|
||||||
|
|
||||||
|
raw = str(ch.get("yt_profile_json") or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return None
|
||||||
|
data["fetched_at"] = float(ch.get("yt_profile_at") or data.get("fetched_at") or 0)
|
||||||
|
return profile_snippet(data)
|
||||||
|
|
||||||
|
|
||||||
|
def list_yt_profile_caches() -> dict[str, dict[str, Any]]:
|
||||||
|
out: dict[str, dict[str, Any]] = {}
|
||||||
|
for ch in db.list_shorts_channels(enabled=None):
|
||||||
|
pk = str(ch.get("id") or "")
|
||||||
|
if not pk:
|
||||||
|
continue
|
||||||
|
sn = _snippet_from_channel_row(ch)
|
||||||
|
if sn:
|
||||||
|
out[pk] = sn
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def refresh_stale_yt_profiles(*, max_age_sec: float = 6 * 3600, limit: int = 4) -> dict[str, Any]:
|
||||||
|
"""Refresh a few authorized channels whose cached profile is missing/stale."""
|
||||||
|
import time
|
||||||
|
|
||||||
|
global _refresh_profiles_running
|
||||||
|
if _refresh_profiles_running:
|
||||||
|
return {"ok": True, "refreshed": [], "skipped": "busy"}
|
||||||
|
lock = _get_refresh_lock()
|
||||||
|
async with lock:
|
||||||
|
if _refresh_profiles_running:
|
||||||
|
return {"ok": True, "refreshed": [], "skipped": "busy"}
|
||||||
|
_refresh_profiles_running = True
|
||||||
|
try:
|
||||||
|
now = time.time()
|
||||||
|
refreshed: list[str] = []
|
||||||
|
errors: list[str] = []
|
||||||
|
candidates: list[tuple[float, str]] = []
|
||||||
|
for ch in db.list_shorts_channels(enabled=None):
|
||||||
|
if not str(ch.get("refresh_token") or "").strip():
|
||||||
|
continue
|
||||||
|
pk = str(ch.get("id") or "")
|
||||||
|
if not pk:
|
||||||
|
continue
|
||||||
|
age_at = float(ch.get("yt_profile_at") or 0)
|
||||||
|
has = bool(str(ch.get("yt_profile_json") or "").strip())
|
||||||
|
if has and age_at and (now - age_at) < max_age_sec:
|
||||||
|
continue
|
||||||
|
candidates.append((age_at, pk))
|
||||||
|
candidates.sort(key=lambda x: x[0]) # oldest / empty first
|
||||||
|
for _age, pk in candidates[: max(0, int(limit))]:
|
||||||
|
try:
|
||||||
|
await fetch_channel_profile(pk)
|
||||||
|
refreshed.append(pk)
|
||||||
|
except Exception as exc:
|
||||||
|
errors.append(f"{pk[:8]}:{exc}")
|
||||||
|
return {"ok": True, "refreshed": refreshed, "errors": errors[:8]}
|
||||||
|
finally:
|
||||||
|
_refresh_profiles_running = False
|
||||||
|
|
||||||
|
|
||||||
async def list_my_videos(channel_pk: str, *, max_results: int = 25, page_token: str = "") -> dict[str, Any]:
|
async def list_my_videos(channel_pk: str, *, max_results: int = 25, page_token: str = "") -> dict[str, Any]:
|
||||||
|
|||||||
500
backend/app/yt_assign_db.py
Normal file
500
backend/app/yt_assign_db.py
Normal file
@ -0,0 +1,500 @@
|
|||||||
|
# -*- 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 sqlite3
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from .db import _connect, _lock, _row_to_dict
|
||||||
|
|
||||||
|
|
||||||
|
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 '',
|
||||||
|
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 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)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_url(url: str) -> str:
|
||||||
|
return 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 "")
|
||||||
|
# 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:
|
||||||
|
out["featured"] = featured
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
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 = [_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
|
||||||
|
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 = [
|
||||||
|
_row_to_dict(x)
|
||||||
|
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()
|
||||||
|
]
|
||||||
|
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], *, 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:
|
||||||
|
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 i, url in enumerate(clean):
|
||||||
|
if url in existing:
|
||||||
|
continue
|
||||||
|
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 (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(uid, group_id, url[:500], str(note or "").strip()[:200], ord0, now, now),
|
||||||
|
)
|
||||||
|
created.append({"id": uid, "url": 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", "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 不能为空")
|
||||||
|
elif k == "note":
|
||||||
|
patch[k] = str(v).strip()[:200]
|
||||||
|
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)}
|
||||||
@ -905,6 +905,18 @@ def channel_board(push_date: str = "") -> dict[str, Any]:
|
|||||||
channels = list_yt_long_channels(enabled=None)
|
channels = list_yt_long_channels(enabled=None)
|
||||||
board: list[dict[str, Any]] = []
|
board: list[dict[str, Any]] = []
|
||||||
total_gap = 0
|
total_gap = 0
|
||||||
|
from . import db as _db
|
||||||
|
from . import youtube_manage
|
||||||
|
|
||||||
|
shorts_profile_by_pk = youtube_manage.list_yt_profile_caches()
|
||||||
|
shorts_by_yt_id: dict[str, dict[str, Any]] = {}
|
||||||
|
for sch in _db.list_shorts_channels(enabled=None):
|
||||||
|
yid = str(sch.get("youtube_channel_id") or "").strip()
|
||||||
|
if not yid:
|
||||||
|
continue
|
||||||
|
sn = youtube_manage._snippet_from_channel_row(sch)
|
||||||
|
if sn:
|
||||||
|
shorts_by_yt_id[yid] = sn
|
||||||
with _lock:
|
with _lock:
|
||||||
conn = _connect()
|
conn = _connect()
|
||||||
try:
|
try:
|
||||||
@ -937,12 +949,20 @@ def channel_board(push_date: str = "") -> dict[str, Any]:
|
|||||||
ypp_ok = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1)
|
ypp_ok = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1)
|
||||||
except Exception:
|
except Exception:
|
||||||
ypp_ok = -1
|
ypp_ok = -1
|
||||||
|
src_pk = str(ch.get("source_shorts_channel_pk") or "").strip()
|
||||||
|
yid = str(ch.get("youtube_channel_id") or "").strip()
|
||||||
|
yt_profile = None
|
||||||
|
if src_pk and src_pk in shorts_profile_by_pk:
|
||||||
|
yt_profile = shorts_profile_by_pk[src_pk]
|
||||||
|
elif yid and yid in shorts_by_yt_id:
|
||||||
|
yt_profile = shorts_by_yt_id[yid]
|
||||||
board.append(
|
board.append(
|
||||||
{
|
{
|
||||||
"id": cid,
|
"id": cid,
|
||||||
"name": ch.get("name"),
|
"name": ch.get("name"),
|
||||||
"youtube_channel_id": ch.get("youtube_channel_id"),
|
"youtube_channel_id": ch.get("youtube_channel_id"),
|
||||||
"oauth_profile_id": ch.get("oauth_profile_id"),
|
"oauth_profile_id": ch.get("oauth_profile_id"),
|
||||||
|
"source_shorts_channel_pk": src_pk,
|
||||||
"enabled": bool(ch.get("enabled")),
|
"enabled": bool(ch.get("enabled")),
|
||||||
"authorized": bool(str(ch.get("refresh_token") or "").strip()),
|
"authorized": bool(str(ch.get("refresh_token") or "").strip()),
|
||||||
"daily_max": dmax,
|
"daily_max": dmax,
|
||||||
@ -956,6 +976,7 @@ def channel_board(push_date: str = "") -> dict[str, Any]:
|
|||||||
"oauth_error": ch.get("oauth_error") or "",
|
"oauth_error": ch.get("oauth_error") or "",
|
||||||
"ypp_ok": ypp_ok,
|
"ypp_ok": ypp_ok,
|
||||||
"monetize_default": bool(int(ch.get("monetize_default") if ch.get("monetize_default") is not None else 1)),
|
"monetize_default": bool(int(ch.get("monetize_default") if ch.get("monetize_default") is not None else 1)),
|
||||||
|
"yt_profile": yt_profile,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@ -30,6 +30,7 @@ import {
|
|||||||
} from "@/components/ShortsUploadUx";
|
} from "@/components/ShortsUploadUx";
|
||||||
import { UploadTimeline } from "@/components/UploadTimeline";
|
import { UploadTimeline } from "@/components/UploadTimeline";
|
||||||
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||||||
|
import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet";
|
||||||
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||||||
import { PageLoader, TableSkeleton } from "@/components/ui";
|
import { PageLoader, TableSkeleton } from "@/components/ui";
|
||||||
import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api";
|
import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api";
|
||||||
@ -82,6 +83,7 @@ type BoardChannel = {
|
|||||||
min_met?: boolean;
|
min_met?: boolean;
|
||||||
max_met?: boolean;
|
max_met?: boolean;
|
||||||
behind_pace?: boolean;
|
behind_pace?: boolean;
|
||||||
|
yt_profile?: YtProfileSnippet | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Job = {
|
type Job = {
|
||||||
@ -1137,15 +1139,14 @@ export default function ShortsPage() {
|
|||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-start justify-between gap-2">
|
<div className="flex items-start justify-between gap-2">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<YtChannelProfileSnippet
|
||||||
<OauthClientBadge profileId={ch.oauth_profile_id} size="sm" />
|
profile={ch.yt_profile}
|
||||||
<div className="truncate font-medium text-slate-100">{ch.name || "未命名"}</div>
|
fallbackName={ch.name}
|
||||||
<YouTubeLiveBadge refKey={shortsLiveRef(ch.id)} compact showOffline />
|
fallbackChannelId={ch.youtube_channel_id}
|
||||||
</div>
|
liveChannelPk={ch.id}
|
||||||
<div className="mt-0.5 truncate font-mono text-[10px] text-slate-500">
|
trailing={<OauthClientBadge profileId={ch.oauth_profile_id} size="sm" />}
|
||||||
{ch.youtube_channel_id || "—"}
|
/>
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex shrink-0 flex-col items-end gap-1 text-[10px]">
|
<div className="flex shrink-0 flex-col items-end gap-1 text-[10px]">
|
||||||
<span className={ch.enabled === false ? "text-slate-500" : "text-teal-300"}>
|
<span className={ch.enabled === false ? "text-slate-500" : "text-teal-300"}>
|
||||||
|
|||||||
@ -18,6 +18,7 @@ import { Shell } from "@/components/Shell";
|
|||||||
import { useConfirm } from "@/components/ConfirmDialog";
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
import { useToast } from "@/components/Toast";
|
import { useToast } from "@/components/Toast";
|
||||||
import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge";
|
import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge";
|
||||||
|
import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet";
|
||||||
import { PageLoader, TableSkeleton } from "@/components/ui";
|
import { PageLoader, TableSkeleton } from "@/components/ui";
|
||||||
import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api";
|
import { fetchJson, fmtTs, todayBeijingISO } from "@/lib/api";
|
||||||
|
|
||||||
@ -35,6 +36,7 @@ type Channel = {
|
|||||||
has_refresh_token?: boolean;
|
has_refresh_token?: boolean;
|
||||||
oauth_profile_id?: string;
|
oauth_profile_id?: string;
|
||||||
oauth_error?: string;
|
oauth_error?: string;
|
||||||
|
source_shorts_channel_pk?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type BoardChannel = {
|
type BoardChannel = {
|
||||||
@ -53,6 +55,8 @@ type BoardChannel = {
|
|||||||
gap?: number;
|
gap?: number;
|
||||||
ypp_ok?: number;
|
ypp_ok?: number;
|
||||||
monetize_default?: boolean;
|
monetize_default?: boolean;
|
||||||
|
source_shorts_channel_pk?: string;
|
||||||
|
yt_profile?: YtProfileSnippet | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Job = {
|
type Job = {
|
||||||
@ -582,14 +586,14 @@ export default function YtLongPage() {
|
|||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-start justify-between gap-2">
|
<div className="flex items-start justify-between gap-2">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<YtChannelProfileSnippet
|
||||||
<OauthClientBadge profileId={ch.oauth_profile_id} size="sm" />
|
profile={ch.yt_profile}
|
||||||
<div className="truncate font-medium text-slate-100">{ch.name || "未命名"}</div>
|
fallbackName={ch.name}
|
||||||
</div>
|
fallbackChannelId={ch.youtube_channel_id}
|
||||||
<div className="mt-0.5 truncate font-mono text-[10px] text-slate-500">
|
liveChannelPk={ch.source_shorts_channel_pk || undefined}
|
||||||
{ch.youtube_channel_id || "—"}
|
trailing={<OauthClientBadge profileId={ch.oauth_profile_id} size="sm" />}
|
||||||
</div>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex shrink-0 flex-col items-end gap-1 text-[10px]">
|
<div className="flex shrink-0 flex-col items-end gap-1 text-[10px]">
|
||||||
<span className={ch.enabled === false ? "text-slate-500" : "text-teal-300"}>
|
<span className={ch.enabled === false ? "text-slate-500" : "text-teal-300"}>
|
||||||
|
|||||||
82
frontend/src/components/YtChannelProfileSnippet.tsx
Normal file
82
frontend/src/components/YtChannelProfileSnippet.tsx
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
|
||||||
|
import { shortsLiveRef } from "@/lib/youtubeLive";
|
||||||
|
|
||||||
|
export type YtProfileSnippet = {
|
||||||
|
title?: string;
|
||||||
|
custom_url?: string;
|
||||||
|
youtube_channel_id?: string;
|
||||||
|
thumbnails?: {
|
||||||
|
default?: { url?: string };
|
||||||
|
medium?: { url?: string };
|
||||||
|
high?: { url?: string };
|
||||||
|
};
|
||||||
|
thumb_url?: string;
|
||||||
|
statistics?: {
|
||||||
|
subscriberCount?: string | number;
|
||||||
|
videoCount?: string | number;
|
||||||
|
viewCount?: string | number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
function thumbOf(p?: YtProfileSnippet | null): string {
|
||||||
|
if (!p) return "";
|
||||||
|
return (
|
||||||
|
String(p.thumb_url || "").trim() ||
|
||||||
|
String(p.thumbnails?.medium?.url || p.thumbnails?.default?.url || p.thumbnails?.high?.url || "").trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleOf(p?: YtProfileSnippet | null, fallbackId?: string): string {
|
||||||
|
const raw = String(p?.custom_url || "").trim() || String(fallbackId || p?.youtube_channel_id || "").trim();
|
||||||
|
if (!raw) return "";
|
||||||
|
if (raw.startsWith("http")) return raw.replace(/^https?:\/\/(www\.)?youtube\.com\//i, "");
|
||||||
|
return raw.startsWith("@") ? raw : raw.startsWith("UC") ? raw : `@${raw.replace(/^@/, "")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compact card header matching /youtube 频道管理 profile strip. */
|
||||||
|
export function YtChannelProfileSnippet({
|
||||||
|
profile,
|
||||||
|
fallbackName,
|
||||||
|
fallbackChannelId,
|
||||||
|
liveChannelPk,
|
||||||
|
trailing,
|
||||||
|
className = "",
|
||||||
|
}: {
|
||||||
|
profile?: YtProfileSnippet | null;
|
||||||
|
fallbackName?: string;
|
||||||
|
fallbackChannelId?: string;
|
||||||
|
liveChannelPk?: string;
|
||||||
|
trailing?: ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
const title = String(profile?.title || fallbackName || "未命名").trim() || "未命名";
|
||||||
|
const handle = handleOf(profile, fallbackChannelId);
|
||||||
|
const thumb = thumbOf(profile);
|
||||||
|
const stats = profile?.statistics;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex min-w-0 gap-2.5 ${className}`}>
|
||||||
|
{thumb ? (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img src={thumb} alt="" className="h-11 w-11 shrink-0 rounded-full object-cover" />
|
||||||
|
) : (
|
||||||
|
<div className="h-11 w-11 shrink-0 rounded-full bg-white/10" />
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
<div className="truncate font-medium text-slate-100">{title}</div>
|
||||||
|
{liveChannelPk ? <YouTubeLiveBadge refKey={shortsLiveRef(liveChannelPk)} compact showOffline /> : null}
|
||||||
|
{trailing}
|
||||||
|
</div>
|
||||||
|
{handle ? <div className="truncate text-xs text-slate-500">{handle}</div> : null}
|
||||||
|
<div className="mt-0.5 text-[11px] text-slate-400">
|
||||||
|
订阅 {stats?.subscriberCount ?? "—"} · 视频 {stats?.videoCount ?? "—"} · 播放 {stats?.viewCount ?? "—"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user