douyinWEB/backend/app/youtube_manage.py
2026-08-22 01:03:20 -05:00

616 lines
23 KiB
Python

# -*- coding: utf-8 -*-
"""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:
_refresh_profiles_lock = asyncio.Lock()
return _refresh_profiles_lock
async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]:
ch = db.get_shorts_channel(channel_pk)
if not ch:
raise ValueError("频道不存在")
creds = channel_oauth_creds(ch)
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
raise ValueError("频道未授权 Google OAuth")
token = await refresh_access_token(
client_id=creds["client_id"],
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
)
return token, ch
async def _get(path: str, *, token: str, params: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
resp = await client.get(
f"{API}/{path}",
params=params,
headers={"Authorization": f"Bearer {token}"},
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400:
err = (data.get("error") or {}).get("message") or data or resp.text
raise ValueError(f"YouTube API 错误: {err}")
return data
async def _post(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
resp = await client.post(
f"{API}/{path}",
params=params,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
json=json_body,
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400:
err = (data.get("error") or {}).get("message") or data or resp.text
raise ValueError(f"YouTube API 错误: {err}")
return data
async def _put(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
resp = await client.put(
f"{API}/{path}",
params=params,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
json=json_body,
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400:
err = (data.get("error") or {}).get("message") or data or resp.text
raise ValueError(f"YouTube API 错误: {err}")
return data
async def _delete(path: str, *, token: str, params: dict[str, Any]) -> None:
async with httpx.AsyncClient(timeout=45.0, trust_env=False) as client:
resp = await client.delete(
f"{API}/{path}",
params=params,
headers={"Authorization": f"Bearer {token}"},
)
if resp.status_code >= 400:
data = resp.json() if resp.content else {}
err = (data.get("error") or {}).get("message") or data or resp.text
raise ValueError(f"YouTube API 错误: {err}")
def list_managed_channels() -> list[dict[str, Any]]:
rows = db.list_shorts_channels()
ypp_by_shorts: dict[str, int] = {}
try:
from . import yt_long_db
ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk()
except Exception:
ypp_by_shorts = {}
out = []
for ch in rows:
sn = _snippet_from_channel_row(ch) or {}
cid = str(ch.get("id") or "")
out.append(
{
"id": ch.get("id"),
"name": ch.get("name"),
"youtube_channel_id": ch.get("youtube_channel_id") or sn.get("youtube_channel_id") or "",
"enabled": bool(ch.get("enabled")),
"authorized": bool(str(ch.get("refresh_token") or "").strip()),
"oauth_profile_id": str(ch.get("oauth_profile_id") or "").strip().upper(),
"oauth_ok": ch.get("oauth_ok"),
"oauth_error": str(ch.get("oauth_error") or ""),
"last_status": str(ch.get("last_status") or "offline"),
"last_title": str(ch.get("last_title") or ""),
"last_live_url": str(ch.get("last_live_url") or ""),
"ypp_ok": ypp_by_shorts.get(cid, -1),
"daily_min": ch.get("daily_min"),
"daily_max": ch.get("daily_max"),
"privacy": ch.get("privacy"),
"title": sn.get("title") or ch.get("name"),
"custom_url": sn.get("custom_url") or "",
"thumb_url": sn.get("thumb_url") or "",
"yt_profile": sn or None,
}
)
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(
"channels",
token=token,
params={"part": "snippet,contentDetails,statistics,brandingSettings", "mine": "true"},
)
items = data.get("items") or []
if not items:
raise ValueError("未拿到频道资料(请确认授权账号下有频道)")
item = items[0]
# If stored youtube_channel_id differs, still return mine (Brand account caveat)
yt_id = str(item.get("id") or "")
if yt_id and yt_id != str(ch.get("youtube_channel_id") or ""):
try:
db.update_shorts_channel(channel_pk, youtube_channel_id=yt_id, name=str((item.get("snippet") or {}).get("title") or ch.get("name")))
except Exception:
pass
uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads") or ""
sn = item.get("snippet") or {}
st = item.get("statistics") or {}
thumbs = sn.get("thumbnails") or {}
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,
"youtube_channel_id": yt_id,
"title": sn.get("title"),
"description": sn.get("description"),
"custom_url": sn.get("customUrl"),
"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"),
"subscriberCount": st.get("subscriberCount"),
"videoCount": st.get("videoCount"),
"hiddenSubscriberCount": st.get("hiddenSubscriberCount"),
},
"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": thumb_url},
"medium": {"url": 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 = 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
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())
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
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],
"attempted": len(refreshed) + len(errors),
}
finally:
_refresh_profiles_running = False
async def list_my_videos(channel_pk: str, *, max_results: int = 25, page_token: str = "") -> dict[str, Any]:
profile = await fetch_channel_profile(channel_pk)
uploads = str(profile.get("uploads_playlist_id") or "")
if not uploads:
return {"ok": True, "videos": [], "profile": profile}
token, _ch = await _access_for_channel(channel_pk)
params: dict[str, Any] = {
"part": "snippet,contentDetails,status",
"playlistId": uploads,
"maxResults": max(1, min(int(max_results), 50)),
}
if page_token:
params["pageToken"] = page_token
pl = await _get("playlistItems", token=token, params=params)
ids = []
order_meta = []
for it in pl.get("items") or []:
vid = ((it.get("contentDetails") or {}).get("videoId")) or ((it.get("snippet") or {}).get("resourceId") or {}).get("videoId")
if vid:
ids.append(vid)
order_meta.append(it)
videos: list[dict[str, Any]] = []
if ids:
detail = await _get(
"videos",
token=token,
params={"part": "snippet,status,statistics,contentDetails", "id": ",".join(ids)},
)
by_id = {str(v.get("id")): v for v in (detail.get("items") or [])}
for vid in ids:
v = by_id.get(vid)
if not v:
continue
sn = v.get("snippet") or {}
st = v.get("status") or {}
stats = v.get("statistics") or {}
videos.append(
{
"id": vid,
"title": sn.get("title"),
"description": sn.get("description"),
"published_at": sn.get("publishedAt"),
"thumbnails": sn.get("thumbnails"),
"tags": sn.get("tags") or [],
"categoryId": sn.get("categoryId"),
"privacyStatus": st.get("privacyStatus"),
"publishAt": st.get("publishAt"),
"madeForKids": st.get("madeForKids"),
"duration": (v.get("contentDetails") or {}).get("duration"),
"statistics": {
"viewCount": stats.get("viewCount"),
"likeCount": stats.get("likeCount"),
"commentCount": stats.get("commentCount"),
},
"url": f"https://www.youtube.com/watch?v={vid}",
"shorts_url": f"https://www.youtube.com/shorts/{vid}",
}
)
return {
"ok": True,
"profile": profile,
"videos": videos,
"next_page_token": pl.get("nextPageToken") or "",
"prev_page_token": pl.get("prevPageToken") or "",
}
async def get_video(channel_pk: str, video_id: str) -> dict[str, Any]:
token, _ch = await _access_for_channel(channel_pk)
data = await _get(
"videos",
token=token,
params={"part": "snippet,status,statistics,contentDetails", "id": video_id},
)
items = data.get("items") or []
if not items:
raise ValueError("视频不存在或无权访问")
v = items[0]
sn = v.get("snippet") or {}
st = v.get("status") or {}
stats = v.get("statistics") or {}
return {
"ok": True,
"video": {
"id": v.get("id"),
"title": sn.get("title"),
"description": sn.get("description"),
"tags": sn.get("tags") or [],
"categoryId": sn.get("categoryId") or "22",
"published_at": sn.get("publishedAt"),
"thumbnails": sn.get("thumbnails"),
"privacyStatus": st.get("privacyStatus"),
"publishAt": st.get("publishAt"),
"embeddable": st.get("embeddable"),
"selfDeclaredMadeForKids": st.get("selfDeclaredMadeForKids"),
"duration": (v.get("contentDetails") or {}).get("duration"),
"statistics": stats,
"url": f"https://www.youtube.com/watch?v={v.get('id')}",
},
}
async def update_video(
channel_pk: str,
video_id: str,
*,
title: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[list[str]] = None,
category_id: Optional[str] = None,
privacy_status: Optional[str] = None,
publish_at: Optional[str] = None,
embeddable: Optional[bool] = None,
) -> dict[str, Any]:
token, _ch = await _access_for_channel(channel_pk)
current = await get_video(channel_pk, video_id)
cur = current["video"]
snippet: dict[str, Any] = {
"title": (title if title is not None else cur.get("title")) or "Untitled",
"categoryId": (category_id if category_id is not None else cur.get("categoryId")) or "22",
}
if description is not None:
snippet["description"] = description
else:
snippet["description"] = cur.get("description") or ""
if tags is not None:
snippet["tags"] = tags
elif cur.get("tags"):
snippet["tags"] = cur.get("tags")
status: dict[str, Any] = {}
priv = privacy_status if privacy_status is not None else cur.get("privacyStatus")
if priv:
status["privacyStatus"] = priv
if publish_at is not None:
# Scheduled publish requires private until publishAt
if publish_at.strip():
status["privacyStatus"] = "private"
status["publishAt"] = publish_at.strip()
else:
# clear schedule — omit publishAt by updating without it (API keeps if not sent carefully)
pass
if embeddable is not None:
status["embeddable"] = embeddable
body: dict[str, Any] = {"id": video_id, "snippet": snippet}
parts = ["snippet"]
if status:
body["status"] = status
parts.append("status")
data = await _put(
"videos",
token=token,
params={"part": ",".join(parts)},
json_body=body,
)
return {"ok": True, "video": data}
async def delete_video(channel_pk: str, video_id: str) -> dict[str, Any]:
token, _ch = await _access_for_channel(channel_pk)
await _delete("videos", token=token, params={"id": video_id})
return {"ok": True, "deleted": video_id}
async def list_playlists(channel_pk: str, *, max_results: int = 25) -> dict[str, Any]:
token, _ch = await _access_for_channel(channel_pk)
data = await _get(
"playlists",
token=token,
params={"part": "snippet,contentDetails,status", "mine": "true", "maxResults": max(1, min(max_results, 50))},
)
items = []
for it in data.get("items") or []:
sn = it.get("snippet") or {}
items.append(
{
"id": it.get("id"),
"title": sn.get("title"),
"description": sn.get("description"),
"itemCount": (it.get("contentDetails") or {}).get("itemCount"),
"privacyStatus": (it.get("status") or {}).get("privacyStatus"),
"thumbnails": sn.get("thumbnails"),
}
)
return {"ok": True, "playlists": items}
async def set_thumbnail_from_path(channel_pk: str, video_id: str, file_path: str) -> dict[str, Any]:
token, _ch = await _access_for_channel(channel_pk)
path = Path(file_path)
if not path.is_file():
raise ValueError("缩略图文件不存在")
raw = path.read_bytes()
ctype = "image/jpeg"
if path.suffix.lower() == ".png":
ctype = "image/png"
async with httpx.AsyncClient(timeout=60.0, trust_env=False) as client:
resp = await client.post(
"https://www.googleapis.com/upload/youtube/v3/thumbnails/set",
params={"videoId": video_id},
headers={"Authorization": f"Bearer {token}", "Content-Type": ctype},
content=raw,
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400:
err = (data.get("error") or {}).get("message") or data or resp.text
raise ValueError(f"设置缩略图失败: {err}")
return {"ok": True, "thumbnails": data}
async def channel_dashboard(channel_pk: str) -> dict[str, Any]:
"""Combine YT profile + recent videos + local Shorts job stats."""
listing = await list_my_videos(channel_pk, max_results=15)
from .timeutil import push_date_from_ts
import time
day = push_date_from_ts(time.time())
local = db.list_shorts_jobs(push_date=day, channel_pk=channel_pk, limit=100, offset=0)
by_status: dict[str, int] = {}
for j in local.get("jobs") or []:
st = str(j.get("status") or "")
by_status[st] = by_status.get(st, 0) + 1
return {
"ok": True,
"profile": listing.get("profile"),
"recent_videos": listing.get("videos") or [],
"shorts_today": {"push_date": day, "by_status": by_status, "total": local.get("total") or 0},
}