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
@@ -14,10 +14,9 @@ INSTAGRAM_USER_ID=
PUBLIC_BASE_URL=https://weather.o2o.kr
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
# 오늘 화면 쇼츠 줄 (YouTube Data API v3 키, console.cloud.google.com/apis/credentials 에서 발급·YouTube Data API v3 만 허용).
# 비우면 채널 쇼츠를 자동으로 못 받고 YOUTUBE_SHORTS(영상 ID, 쉼표로 구분, 최신순)만 보여 준다. 둘 다 비우면 기본값(영상 3개)
# 비우면 채널 쇼츠 RSS(키 없음, 최신 15개)로 받는다
YOUTUBE_API_KEY=
YOUTUBE_CHANNEL_ID=UCWdesmwvHFsnjMUWNcDaA9w
YOUTUBE_SHORTS=
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
DB_HOST=localhost
+1 -1
View File
@@ -59,7 +59,7 @@
| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` |
| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | |
| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | |
| [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` |
| [x] | 오늘 화면 쇼츠 줄 — 영상 ID 고정 목록(`youtube_shorts`) 없앰. API 키가 없으면 채널 쇼츠 RSS(`UUSH…` 재생목록, 키 없음)로 자동으로 받음. 키(`YOUTUBE_API_KEY`)를 운영 .env 에 넣으면 Data API 로 바뀌어 퍼가기·길이까지 거름 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 10/28 운영에 키가 없어 고정 목록만 나와 새 쇼츠가 안 붙음. 채널 RSS가 다시 200 | `backend/services/external/youtube.py`, `backend/services/shorts_service.py` |
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
| [ ] | 쇼츠 API 실패·빈 목록일 때 공유 링크로 들어오면 남색 빈 화면만 보임 — 그 영상 ID 하나라도 띄우거나 × 버튼·안내 문구 보이기 | 10/27 QA 실패 (`items` 가 비면 빈 div 만 그림) | `frontend/src/b/Shorts.tsx` |
+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 = []