diff --git a/backend/app/main.py b/backend/app/main.py index ed666d2..46518d8 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -518,11 +518,6 @@ async def shorts_status() -> dict[str, Any]: cfg = await _db(db.get_settings_map) 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) - # 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 @@ -1194,10 +1189,6 @@ async def x_clips_job_retry(job_id: str) -> dict[str, Any]: @app.get("/api/yt-long/status") 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) @@ -2405,9 +2396,10 @@ async def youtube_manage_profiles() -> dict[str, Any]: @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), + max_age_sec: float = Query(0, ge=0, le=86400 * 365), + limit: int = Query(50, ge=1, le=100), ) -> dict[str, Any]: + """Manual only: refresh channel cards + mirror avatars to S3. Default force all.""" return await youtube_manage.refresh_stale_yt_profiles(max_age_sec=max_age_sec, limit=limit) diff --git a/backend/app/youtube_manage.py b/backend/app/youtube_manage.py index a62c147..0659b83 100644 --- a/backend/app/youtube_manage.py +++ b/backend/app/youtube_manage.py @@ -2,26 +2,30 @@ """YouTube Data API helpers using Shorts-channel OAuth (upload + readonly).""" from __future__ import annotations +import asyncio +import logging from pathlib import Path from typing import Any, Optional +from urllib.parse import urlparse import httpx from . import db +from . import s3_storage from .shorts_oauth import channel_oauth_creds from .shorts_upload import refresh_access_token API = "https://www.googleapis.com/youtube/v3" +log = logging.getLogger("youtube_manage") _refresh_profiles_lock: Optional[Any] = None _refresh_profiles_running = False +_S3_PUBLIC_HOSTS = ("s3.nomadro.com", "feiniu.nomadro.com") 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 @@ -117,6 +121,44 @@ def list_managed_channels() -> list[dict[str, Any]]: return out +def _is_s3_public_url(url: str) -> bool: + try: + host = (urlparse(str(url or "")).hostname or "").lower() + except Exception: + return False + return any(host == h or host.endswith("." + h) for h in _S3_PUBLIC_HOSTS) + + +async def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str: + """Download YouTube CDN avatar and store a stable S3 URL. Falls back to CDN on failure.""" + url = str(cdn_url or "").strip() + if not url: + return "" + if _is_s3_public_url(url): + return url + if not s3_storage.s3_enabled(): + return url + try: + async with httpx.AsyncClient(timeout=30.0, trust_env=False, follow_redirects=True) as client: + resp = await client.get(url, headers={"User-Agent": "Mozilla/5.0"}) + resp.raise_for_status() + data = resp.content + if len(data) < 64: + return url + ctype = (resp.headers.get("content-type") or "image/jpeg").split(";")[0].strip() or "image/jpeg" + suffix = ".jpg" + if "png" in ctype: + suffix = ".png" + elif "webp" in ctype: + suffix = ".webp" + key = f"youtube/avatars/{channel_pk}{suffix}" + public = await asyncio.to_thread(s3_storage.upload_bytes, data, key, ctype) + return public or url + except Exception as exc: + log.info("yt avatar s3 mirror fail channel=%s: %s", channel_pk[:8], exc) + return url + + async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]: token, ch = await _access_for_channel(channel_pk) data = await _get( @@ -139,12 +181,13 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]: sn = item.get("snippet") or {} st = item.get("statistics") or {} thumbs = sn.get("thumbnails") or {} - thumb_url = ( + thumb_cdn = ( ((thumbs.get("medium") or {}).get("url")) or ((thumbs.get("default") or {}).get("url")) or ((thumbs.get("high") or {}).get("url")) or "" ) + thumb_url = await _mirror_avatar_to_s3(channel_pk, thumb_cdn) if thumb_cdn else "" profile = { "ok": True, "channel_pk": channel_pk, @@ -152,8 +195,12 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]: "title": sn.get("title"), "description": sn.get("description"), "custom_url": sn.get("customUrl"), - "thumbnails": thumbs, - "thumb_url": thumb_url, + "thumbnails": { + "default": {"url": thumb_url or thumb_cdn}, + "medium": {"url": thumb_url or thumb_cdn}, + }, + "thumb_url": thumb_url or thumb_cdn, + "thumb_cdn": thumb_cdn, "uploads_playlist_id": uploads, "statistics": { "viewCount": st.get("viewCount"), @@ -187,8 +234,8 @@ def profile_snippet(profile: dict[str, Any] | None) -> dict[str, Any] | None: "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}, + "default": {"url": thumb_url}, + "medium": {"url": thumb_url}, }, "statistics": { "subscriberCount": stats.get("subscriberCount"), @@ -259,8 +306,12 @@ def list_yt_profile_caches() -> dict[str, dict[str, Any]]: 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.""" +async def refresh_stale_yt_profiles(*, max_age_sec: float = 0, limit: int = 50) -> dict[str, Any]: + """Manual bulk refresh: pull YouTube profiles + mirror avatars to S3. + + Default max_age_sec=0 means force-refresh all authorized channels (up to limit). + Not intended for background polling — avatars rarely change. + """ import time global _refresh_profiles_running @@ -284,7 +335,15 @@ async def refresh_stale_yt_profiles(*, max_age_sec: float = 6 * 3600, limit: int 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: + sn = _snippet_from_channel_row(ch) if has else None + thumb = str((sn or {}).get("thumb_url") or "") + needs_s3 = bool(thumb) and not _is_s3_public_url(thumb) + if ( + has + and age_at + and (now - age_at) < max_age_sec + and not needs_s3 + ): continue candidates.append((age_at, pk)) candidates.sort(key=lambda x: x[0]) # oldest / empty first @@ -294,7 +353,12 @@ async def refresh_stale_yt_profiles(*, max_age_sec: float = 6 * 3600, limit: int refreshed.append(pk) except Exception as exc: errors.append(f"{pk[:8]}:{exc}") - return {"ok": True, "refreshed": refreshed, "errors": errors[:8]} + return { + "ok": True, + "refreshed": refreshed, + "errors": errors[:8], + "attempted": len(refreshed) + len(errors), + } finally: _refresh_profiles_running = False diff --git a/frontend/src/components/YtAssignPanel.tsx b/frontend/src/components/YtAssignPanel.tsx index 25ecd7b..a9c68a3 100644 --- a/frontend/src/components/YtAssignPanel.tsx +++ b/frontend/src/components/YtAssignPanel.tsx @@ -220,24 +220,46 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { } }, [toast]); - const loadProfile = useCallback(async (channelPk: string) => { - if (!channelPk) return; + const loadAllProfiles = useCallback(async () => { try { - const cached = await fetchJson("/api/youtube/manage/profiles").catch(() => ({ profiles: {} })); - const fromCache = cached?.profiles?.[channelPk]; - if (fromCache) { - setProfiles((p) => ({ ...p, [channelPk]: fromCache })); + const cached = await fetchJson("/api/youtube/manage/profiles"); + const map = (cached?.profiles || {}) as Record; + if (map && typeof map === "object") { + setProfiles(map); } - const live = await fetchJson(`/api/youtube/manage/${channelPk}/profile`); - setProfiles((p) => ({ ...p, [channelPk]: live })); } catch { - // keep fallback + // keep fallback placeholders } }, []); + const refreshAllAvatars = useCallback(async () => { + setBusy(true); + try { + const r = await fetchJson("/api/youtube/manage/profiles/refresh?max_age_sec=0&limit=50", { + method: "POST", + }); + await loadAllProfiles(); + const n = Array.isArray(r?.refreshed) ? r.refreshed.length : 0; + const errN = Array.isArray(r?.errors) ? r.errors.length : 0; + if (r?.skipped === "busy") { + toast.push("头像刷新进行中,请稍后再试", "err"); + } else { + toast.push( + errN ? `已更新 ${n} 个头像(${errN} 失败)` : `已更新 ${n} 个频道头像到 S3`, + errN ? "err" : "ok" + ); + } + } catch (e) { + toast.push((e as Error).message, "err"); + } finally { + setBusy(false); + } + }, [loadAllProfiles, toast]); + useEffect(() => { void loadGroups(); - }, [loadGroups]); + void loadAllProfiles(); + }, [loadGroups, loadAllProfiles]); useEffect(() => { if (!selected) { @@ -248,8 +270,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { setStreamKeyDraft(String(selected.stream_key || "")); setNoteDraft(String(selected.note || "")); setShowKey(true); - if (selected.channel_pk) void loadProfile(selected.channel_pk); - }, [selected, loadProfile]); + }, [selected]); async function createGroup() { if (!newChannelPk) { @@ -514,14 +535,26 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) { 频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。

- +
+ + +