feat: 오늘 화면 히어로 아래 날씨각 유튜브 쇼츠 줄 — 첫 카드 소리 없이 자동재생, 누르면 전체 화면에서 위아래로 넘겨 보기. 목록은 /v1/shorts(API 키 있으면 채널 쇼츠, 없으면 설정한 영상 ID), 1시간 캐시
This commit is contained in:
1 parent
f9988855d3
commit
b718955927
15 files changed
+875
-6
No files matched your search
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
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")
|
||||
@@ -0,0 +1,46 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
from services.external import youtube
|
||||
|
||||
CACHE_KEY = "shorts:list"
|
||||
CACHE_SEC = 3600
|
||||
MAX_ITEMS = 10
|
||||
|
||||
|
||||
class ShortsService:
|
||||
async def items(self) -> tuple[ErrorType, list[dict]]:
|
||||
"""오늘 화면 쇼츠 줄 [{id, title}]. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
|
||||
try:
|
||||
cached = await REDIS.conn.get(CACHE_KEY)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[shorts] cache get: {e}")
|
||||
cached = None
|
||||
if cached:
|
||||
return ErrorType.SUCCESS, json.loads(cached)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
items = await self._fetch(client)
|
||||
except (httpx.HTTPError, KeyError, ValueError) as e:
|
||||
LOG.error(f"[shorts] fetch: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
try:
|
||||
await REDIS.conn.set(CACHE_KEY, json.dumps(items, ensure_ascii=False), ex=CACHE_SEC)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[shorts] cache set: {e}")
|
||||
return ErrorType.SUCCESS, items
|
||||
|
||||
async def _fetch(self, client: httpx.AsyncClient) -> list[dict]:
|
||||
if settings.youtube_api_key:
|
||||
found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS)
|
||||
return [{"id": v["id"], "title": v["title"]} for v in found]
|
||||
ids = [i.strip() for i in settings.youtube_shorts.split(",") if i.strip()][:MAX_ITEMS]
|
||||
titles = await asyncio.gather(*(youtube.video_title(client, i) for i in ids))
|
||||
return [{"id": i, "title": t} for i, t in zip(ids, titles) if t]
|
||||
Reference in new issue
Block a user