51 lines
2.1 KiB
Python
51 lines
2.1 KiB
Python
import json
|
|
import xml.etree.ElementTree as ET
|
|
|
|
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"
|
|
# 워커가 하루 3번(07·12·18시 10분) 새로 받는다. 한 번 실패해도 다음 회차까지 이전 목록을 쓰게 넉넉히 둔다
|
|
CACHE_SEC = 2 * 86400
|
|
MAX_ITEMS = 10
|
|
|
|
|
|
class ShortsService:
|
|
async def items(self) -> tuple[ErrorType, list[dict]]:
|
|
"""오늘 화면 쇼츠 줄 [{id, title}]. 워커가 받아 둔 목록을 읽고, 없을 때만(처음 켰을 때) 바로 받는다."""
|
|
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)
|
|
return await self.refresh()
|
|
|
|
async def refresh(self) -> tuple[ErrorType, list[dict]]:
|
|
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 Data API 로, 없으면 채널 쇼츠 RSS 로."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
items = await self._fetch(client)
|
|
except (httpx.HTTPError, KeyError, ValueError, ET.ParseError) 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)
|
|
else:
|
|
found = await youtube.feed_shorts(client, settings.youtube_channel_id, MAX_ITEMS)
|
|
return [{"id": v["id"], "title": v["title"]} for v in found]
|