fix(youtube): cache channel avatars on S3, refresh only on demand
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
e943e7873b
commit
82bcd5a26b
@ -518,11 +518,6 @@ 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
|
||||||
|
|
||||||
|
|
||||||
@ -1194,10 +1189,6 @@ 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)
|
||||||
|
|
||||||
|
|
||||||
@ -2405,9 +2396,10 @@ async def youtube_manage_profiles() -> dict[str, Any]:
|
|||||||
|
|
||||||
@app.post("/api/youtube/manage/profiles/refresh")
|
@app.post("/api/youtube/manage/profiles/refresh")
|
||||||
async def youtube_manage_profiles_refresh(
|
async def youtube_manage_profiles_refresh(
|
||||||
max_age_sec: float = Query(3600, ge=0, le=86400 * 7),
|
max_age_sec: float = Query(0, ge=0, le=86400 * 365),
|
||||||
limit: int = Query(8, ge=1, le=30),
|
limit: int = Query(50, ge=1, le=100),
|
||||||
) -> dict[str, Any]:
|
) -> 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)
|
return await youtube_manage.refresh_stale_yt_profiles(max_age_sec=max_age_sec, limit=limit)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -2,26 +2,30 @@
|
|||||||
"""YouTube Data API helpers using Shorts-channel OAuth (upload + readonly)."""
|
"""YouTube Data API helpers using Shorts-channel OAuth (upload + readonly)."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from . import db
|
from . import db
|
||||||
|
from . import s3_storage
|
||||||
from .shorts_oauth import channel_oauth_creds
|
from .shorts_oauth import channel_oauth_creds
|
||||||
from .shorts_upload import refresh_access_token
|
from .shorts_upload import refresh_access_token
|
||||||
|
|
||||||
API = "https://www.googleapis.com/youtube/v3"
|
API = "https://www.googleapis.com/youtube/v3"
|
||||||
|
log = logging.getLogger("youtube_manage")
|
||||||
|
|
||||||
_refresh_profiles_lock: Optional[Any] = None
|
_refresh_profiles_lock: Optional[Any] = None
|
||||||
_refresh_profiles_running = False
|
_refresh_profiles_running = False
|
||||||
|
_S3_PUBLIC_HOSTS = ("s3.nomadro.com", "feiniu.nomadro.com")
|
||||||
|
|
||||||
|
|
||||||
def _get_refresh_lock():
|
def _get_refresh_lock():
|
||||||
global _refresh_profiles_lock
|
global _refresh_profiles_lock
|
||||||
if _refresh_profiles_lock is None:
|
if _refresh_profiles_lock is None:
|
||||||
import asyncio
|
|
||||||
|
|
||||||
_refresh_profiles_lock = asyncio.Lock()
|
_refresh_profiles_lock = asyncio.Lock()
|
||||||
return _refresh_profiles_lock
|
return _refresh_profiles_lock
|
||||||
|
|
||||||
@ -117,6 +121,44 @@ def list_managed_channels() -> list[dict[str, Any]]:
|
|||||||
return out
|
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]:
|
async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
|
||||||
token, ch = await _access_for_channel(channel_pk)
|
token, ch = await _access_for_channel(channel_pk)
|
||||||
data = await _get(
|
data = await _get(
|
||||||
@ -139,12 +181,13 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
|
|||||||
sn = item.get("snippet") or {}
|
sn = item.get("snippet") or {}
|
||||||
st = item.get("statistics") or {}
|
st = item.get("statistics") or {}
|
||||||
thumbs = sn.get("thumbnails") or {}
|
thumbs = sn.get("thumbnails") or {}
|
||||||
thumb_url = (
|
thumb_cdn = (
|
||||||
((thumbs.get("medium") or {}).get("url"))
|
((thumbs.get("medium") or {}).get("url"))
|
||||||
or ((thumbs.get("default") or {}).get("url"))
|
or ((thumbs.get("default") or {}).get("url"))
|
||||||
or ((thumbs.get("high") or {}).get("url"))
|
or ((thumbs.get("high") or {}).get("url"))
|
||||||
or ""
|
or ""
|
||||||
)
|
)
|
||||||
|
thumb_url = await _mirror_avatar_to_s3(channel_pk, thumb_cdn) if thumb_cdn else ""
|
||||||
profile = {
|
profile = {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"channel_pk": channel_pk,
|
"channel_pk": channel_pk,
|
||||||
@ -152,8 +195,12 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]:
|
|||||||
"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": thumbs,
|
"thumbnails": {
|
||||||
"thumb_url": thumb_url,
|
"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,
|
"uploads_playlist_id": uploads,
|
||||||
"statistics": {
|
"statistics": {
|
||||||
"viewCount": st.get("viewCount"),
|
"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 "",
|
"youtube_channel_id": profile.get("youtube_channel_id") or "",
|
||||||
"thumb_url": thumb_url,
|
"thumb_url": thumb_url,
|
||||||
"thumbnails": {
|
"thumbnails": {
|
||||||
"default": {"url": ((thumbs.get("default") or {}).get("url")) or thumb_url},
|
"default": {"url": thumb_url},
|
||||||
"medium": {"url": ((thumbs.get("medium") or {}).get("url")) or thumb_url},
|
"medium": {"url": thumb_url},
|
||||||
},
|
},
|
||||||
"statistics": {
|
"statistics": {
|
||||||
"subscriberCount": stats.get("subscriberCount"),
|
"subscriberCount": stats.get("subscriberCount"),
|
||||||
@ -259,8 +306,12 @@ def list_yt_profile_caches() -> dict[str, dict[str, Any]]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
async def refresh_stale_yt_profiles(*, max_age_sec: float = 6 * 3600, limit: int = 4) -> dict[str, Any]:
|
async def refresh_stale_yt_profiles(*, max_age_sec: float = 0, limit: int = 50) -> dict[str, Any]:
|
||||||
"""Refresh a few authorized channels whose cached profile is missing/stale."""
|
"""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
|
import time
|
||||||
|
|
||||||
global _refresh_profiles_running
|
global _refresh_profiles_running
|
||||||
@ -284,7 +335,15 @@ async def refresh_stale_yt_profiles(*, max_age_sec: float = 6 * 3600, limit: int
|
|||||||
continue
|
continue
|
||||||
age_at = float(ch.get("yt_profile_at") or 0)
|
age_at = float(ch.get("yt_profile_at") or 0)
|
||||||
has = bool(str(ch.get("yt_profile_json") or "").strip())
|
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
|
continue
|
||||||
candidates.append((age_at, pk))
|
candidates.append((age_at, pk))
|
||||||
candidates.sort(key=lambda x: x[0]) # oldest / empty first
|
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)
|
refreshed.append(pk)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
errors.append(f"{pk[:8]}:{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:
|
finally:
|
||||||
_refresh_profiles_running = False
|
_refresh_profiles_running = False
|
||||||
|
|
||||||
|
|||||||
@ -220,24 +220,46 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
}
|
}
|
||||||
}, [toast]);
|
}, [toast]);
|
||||||
|
|
||||||
const loadProfile = useCallback(async (channelPk: string) => {
|
const loadAllProfiles = useCallback(async () => {
|
||||||
if (!channelPk) return;
|
|
||||||
try {
|
try {
|
||||||
const cached = await fetchJson("/api/youtube/manage/profiles").catch(() => ({ profiles: {} }));
|
const cached = await fetchJson("/api/youtube/manage/profiles");
|
||||||
const fromCache = cached?.profiles?.[channelPk];
|
const map = (cached?.profiles || {}) as Record<string, YtProfileSnippet>;
|
||||||
if (fromCache) {
|
if (map && typeof map === "object") {
|
||||||
setProfiles((p) => ({ ...p, [channelPk]: fromCache }));
|
setProfiles(map);
|
||||||
}
|
}
|
||||||
const live = await fetchJson(`/api/youtube/manage/${channelPk}/profile`);
|
|
||||||
setProfiles((p) => ({ ...p, [channelPk]: live }));
|
|
||||||
} catch {
|
} 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(() => {
|
useEffect(() => {
|
||||||
void loadGroups();
|
void loadGroups();
|
||||||
}, [loadGroups]);
|
void loadAllProfiles();
|
||||||
|
}, [loadGroups, loadAllProfiles]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@ -248,8 +270,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
setStreamKeyDraft(String(selected.stream_key || ""));
|
setStreamKeyDraft(String(selected.stream_key || ""));
|
||||||
setNoteDraft(String(selected.note || ""));
|
setNoteDraft(String(selected.note || ""));
|
||||||
setShowKey(true);
|
setShowKey(true);
|
||||||
if (selected.channel_pk) void loadProfile(selected.channel_pk);
|
}, [selected]);
|
||||||
}, [selected, loadProfile]);
|
|
||||||
|
|
||||||
async function createGroup() {
|
async function createGroup() {
|
||||||
if (!newChannelPk) {
|
if (!newChannelPk) {
|
||||||
@ -514,6 +535,17 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。
|
频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void refreshAllAvatars()}
|
||||||
|
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm disabled:opacity-40"
|
||||||
|
title="从 YouTube 拉取并固化到 S3;平时只读缓存"
|
||||||
|
>
|
||||||
|
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||||
|
刷新头像
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => void loadGroups()}
|
onClick={() => void loadGroups()}
|
||||||
@ -523,6 +555,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
刷新
|
刷新
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-2 sm:grid-cols-[1.2fr_1fr_auto]">
|
<div className="grid gap-2 sm:grid-cols-[1.2fr_1fr_auto]">
|
||||||
<select
|
<select
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user