Files
o2o-weather/backend/services/external/youtube.py
T

75 lines
3.6 KiB
Python

import asyncio
import re
import xml.etree.ElementTree as ET
from typing import Optional
import httpx
# YouTube Data API v3 (API 키). 채널 업로드 목록 → 영상 정보로 쇼츠만 고른다
API_URL = "https://www.googleapis.com/youtube/v3"
# 키 없이 영상 제목만 받을 때
OEMBED_URL = "https://www.youtube.com/oembed"
# 키 없이 채널 쇼츠 목록을 받을 때: 채널 ID의 UC 를 UUSH 로 바꾼 재생목록이 그 채널의 쇼츠만 모은 목록이다
FEED_URL = "https://www.youtube.com/feeds/videos.xml"
_NS = {"a": "http://www.w3.org/2005/Atom", "yt": "http://www.youtube.com/xml/schemas/2015"}
SHORT_MAX_SEC = 180 # 쇼츠는 3분 이하
_DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$")
def seconds(iso: str) -> Optional[int]:
"""ISO 8601 길이("PT1M5S") → 초. 형식이 다르면 None."""
m = _DURATION.match(iso or "")
if not m:
return None
h, mi, s = (int(g or 0) for g in m.groups())
return h * 3600 + mi * 60 + s
async def channel_shorts(client: httpx.AsyncClient, key: str, channel_id: str, limit: int) -> list[dict]:
"""채널의 공개·퍼가기 허용 쇼츠 [{id, title, published}], 최신순."""
res = await client.get(f"{API_URL}/channels", params={"part": "contentDetails", "id": channel_id, "key": key})
res.raise_for_status()
channels = res.json().get("items") or []
if not channels:
return []
uploads = channels[0]["contentDetails"]["relatedPlaylists"]["uploads"]
res = await client.get(f"{API_URL}/playlistItems", params={"part": "contentDetails", "playlistId": uploads, "maxResults": 50, "key": key})
res.raise_for_status()
ids = [i["contentDetails"]["videoId"] for i in res.json().get("items") or []]
if not ids:
return []
res = await client.get(f"{API_URL}/videos", params={"part": "snippet,contentDetails,status", "id": ",".join(ids), "key": key})
res.raise_for_status()
found = []
for v in res.json().get("items") or []:
status, sec = v.get("status", {}), seconds(v["contentDetails"].get("duration", ""))
if status.get("privacyStatus") != "public" or not status.get("embeddable") or sec is None or sec > SHORT_MAX_SEC:
continue
found.append({"id": v["id"], "title": v["snippet"]["title"], "published": v["snippet"]["publishedAt"]})
found.sort(key=lambda x: x["published"], reverse=True)
return found[:limit]
async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str]:
"""영상 제목. 없거나 퍼가기가 막힌 영상이면 None."""
res = await client.get(OEMBED_URL, params={"url": f"https://www.youtube.com/shorts/{video_id}", "format": "json"})
if res.status_code in (401, 403, 404):
return None
res.raise_for_status()
return res.json().get("title")
async def feed_shorts(client: httpx.AsyncClient, channel_id: str, limit: int) -> list[dict]:
"""키 없이 채널의 공개 쇼츠 [{id, title, published}], 최신순. 퍼가기를 막은 영상은 뺀다."""
res = await client.get(FEED_URL, params={"playlist_id": "UUSH" + channel_id.removeprefix("UC")})
res.raise_for_status()
root = ET.fromstring(res.text)
entries = [
{"id": e.findtext("yt:videoId", namespaces=_NS), "title": e.findtext("a:title", namespaces=_NS), "published": e.findtext("a:published", namespaces=_NS)}
for e in root.findall("a:entry", _NS)
]
entries = sorted((e for e in entries if e["id"] and e["title"]), key=lambda e: e["published"] or "", reverse=True)[:limit]
embeddable = await asyncio.gather(*(video_title(client, e["id"]) for e in entries))
return [e for e, ok in zip(entries, embeddable) if ok]