fix: 쇼츠 줄을 고정 영상 ID 대신 채널 쇼츠 RSS로 — API 키가 없어도 새 쇼츠가 자동으로 붙게, youtube_shorts 설정 삭제

This commit is contained in:
minaChoi committed 2026-10-28 16:58:56 +09:00
1 parent c8df1f5ef6
commit 4d79ec839c
6 files changed
+55 -13

No files matched your search

+1 -2
View File
@@ -51,10 +51,9 @@ class Settings(BaseSettings):
azure_blob_base_url: str = ""
azure_blob_sas_token: str = ""
# 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다
# 오늘 화면 쇼츠 줄. API 키가 있으면 Data API 로(공개·퍼가기 허용·3분 이하), 없으면 채널 쇼츠 RSS 로 받는다
youtube_api_key: str = ""
youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w"
youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM"
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
google_client_id: str = ""
+19
View File
@@ -1,4 +1,6 @@
import asyncio
import re
import xml.etree.ElementTree as ET
from typing import Optional
import httpx
@@ -7,6 +9,9 @@ import httpx
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)?$")
@@ -53,3 +58,17 @@ async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str]
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]
+6 -7
View File
@@ -1,5 +1,5 @@
import asyncio
import json
import xml.etree.ElementTree as ET
import httpx
from redis.exceptions import RedisError
@@ -29,11 +29,11 @@ class ShortsService:
return await self.refresh()
async def refresh(self) -> tuple[ErrorType, list[dict]]:
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 Data API 로, 없으면 채널 쇼츠 RSS 로."""
try:
async with httpx.AsyncClient(timeout=10) as client:
items = await self._fetch(client)
except (httpx.HTTPError, KeyError, ValueError) as e:
except (httpx.HTTPError, KeyError, ValueError, ET.ParseError) as e:
LOG.error(f"[shorts] fetch: {e}")
return ErrorType.EXTERNAL_API_ERROR, []
try:
@@ -45,7 +45,6 @@ class ShortsService:
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]
else:
found = await youtube.feed_shorts(client, settings.youtube_channel_id, MAX_ITEMS)
return [{"id": v["id"], "title": v["title"]} for v in found]
+27 -1
View File
@@ -6,7 +6,7 @@ import pytest
from common.cache.redis_client import REDIS
from common.enums import ErrorType
from services import shorts_service
from services.external.youtube import channel_shorts, seconds, video_title
from services.external.youtube import channel_shorts, feed_shorts, seconds, video_title
from services.shorts_service import CACHE_KEY, ShortsService
@@ -58,6 +58,32 @@ async def test_video_title_none_when_embedding_blocked():
assert await video_title(client, "blocked") is None
def _feed(entries: list[tuple[str, str]]) -> str:
items = "".join(
f"<entry><yt:videoId>{vid}</yt:videoId><title>제목 {vid}</title><published>{published}</published></entry>" for vid, published in entries
)
return f'<feed xmlns="http://www.w3.org/2005/Atom" xmlns:yt="http://www.youtube.com/xml/schemas/2015">{items}</feed>'
@pytest.mark.anyio
async def test_feed_shorts_reads_channel_shorts_feed_newest_first_without_blocked():
seen = {}
def handle(req: httpx.Request) -> httpx.Response:
if req.url.path.endswith("/feeds/videos.xml"):
seen["playlist"] = req.url.params["playlist_id"]
return httpx.Response(200, text=_feed([("old", "2026-10-20T00:00:00+00:00"), ("new", "2026-10-28T00:00:00+00:00"), ("blocked", "2026-10-27T00:00:00+00:00")]))
if "blocked" in req.url.params["url"]:
return httpx.Response(401)
return httpx.Response(200, content=json.dumps({"title": "x"}))
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:
found = await feed_shorts(client, "UCtest", 10)
assert seen["playlist"] == "UUSHtest"
assert [v["id"] for v in found] == ["new", "old"]
assert found[0]["title"] == "제목 new"
@pytest.mark.anyio
async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch):
calls = []