378 lines
14 KiB
Python
378 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""YouTube Data API helpers using Shorts-channel OAuth (upload + readonly)."""
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from typing import Any, Optional
|
|
|
|
import httpx
|
|
|
|
from . import db
|
|
from .shorts_oauth import channel_oauth_creds
|
|
from .shorts_upload import refresh_access_token
|
|
|
|
API = "https://www.googleapis.com/youtube/v3"
|
|
|
|
|
|
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()
|
|
out = []
|
|
for ch in rows:
|
|
out.append(
|
|
{
|
|
"id": ch.get("id"),
|
|
"name": ch.get("name"),
|
|
"youtube_channel_id": ch.get("youtube_channel_id"),
|
|
"enabled": bool(ch.get("enabled")),
|
|
"authorized": bool(str(ch.get("refresh_token") or "").strip()),
|
|
"daily_min": ch.get("daily_min"),
|
|
"daily_max": ch.get("daily_max"),
|
|
"privacy": ch.get("privacy"),
|
|
}
|
|
)
|
|
return out
|
|
|
|
|
|
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 {}
|
|
return {
|
|
"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": sn.get("thumbnails"),
|
|
"uploads_playlist_id": uploads,
|
|
"statistics": {
|
|
"viewCount": st.get("viewCount"),
|
|
"subscriberCount": st.get("subscriberCount"),
|
|
"videoCount": st.get("videoCount"),
|
|
"hiddenSubscriberCount": st.get("hiddenSubscriberCount"),
|
|
},
|
|
"raw": item,
|
|
}
|
|
|
|
|
|
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},
|
|
}
|