import re 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" 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")