47 lines
1.8 KiB
Python
47 lines
1.8 KiB
Python
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]
|