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
@@ -51,6 +51,11 @@ class Settings(BaseSettings):
|
||||
azure_blob_base_url: str = ""
|
||||
azure_blob_sas_token: str = ""
|
||||
|
||||
# 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다
|
||||
youtube_api_key: str = ""
|
||||
youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w"
|
||||
youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM"
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
from router.v1.seo.seo import router as seo_router
|
||||
from router.v1.shorts.shorts import router as shorts_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.talk.talk import router as talk_router
|
||||
from router.v1.watch.watch import router as watch_router
|
||||
@@ -53,6 +54,7 @@ app.include_router(image_router)
|
||||
app.include_router(seo_router)
|
||||
app.include_router(card_router)
|
||||
app.include_router(reel_router)
|
||||
app.include_router(shorts_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,10 @@
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class ShortItem(WebPacketProtocol):
|
||||
id: str # 유튜브 영상 ID
|
||||
title: str
|
||||
|
||||
|
||||
class Res_ShortList(Res_WebPacketProtocol):
|
||||
items: list[ShortItem] = []
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.shorts.protocol import Res_ShortList, ShortItem
|
||||
from services.shorts_service import ShortsService
|
||||
|
||||
router = APIRouter(prefix="/v1/shorts", tags=["shorts"])
|
||||
|
||||
|
||||
@router.get("", response_model=Res_ShortList, response_model_exclude_none=True, summary="오늘 화면 쇼츠 줄: 날씨각 유튜브 채널의 쇼츠, 최신순")
|
||||
async def list_shorts(service: ShortsService = Depends()) -> Res_ShortList:
|
||||
err, items = await service.items()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_ShortList(result=error_info(err))
|
||||
return Res_ShortList(items=[ShortItem(**i) for i in items])
|
||||
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]
|
||||
@@ -0,0 +1,54 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from services.external.youtube import channel_shorts, seconds, video_title
|
||||
|
||||
|
||||
def test_seconds_parses_iso_duration():
|
||||
assert seconds("PT45S") == 45
|
||||
assert seconds("PT1M5S") == 65
|
||||
assert seconds("PT1H") == 3600
|
||||
assert seconds("P1D") is None
|
||||
|
||||
|
||||
def _api(videos: list[dict]) -> httpx.MockTransport:
|
||||
def handle(req: httpx.Request) -> httpx.Response:
|
||||
if req.url.path.endswith("/channels"):
|
||||
return httpx.Response(200, json={"items": [{"contentDetails": {"relatedPlaylists": {"uploads": "UUtest"}}}]})
|
||||
if req.url.path.endswith("/playlistItems"):
|
||||
assert req.url.params["playlistId"] == "UUtest"
|
||||
return httpx.Response(200, json={"items": [{"contentDetails": {"videoId": v["id"]}} for v in videos]})
|
||||
return httpx.Response(200, json={"items": videos})
|
||||
return httpx.MockTransport(handle)
|
||||
|
||||
|
||||
def _video(vid: str, duration: str, published: str, embeddable: bool = True, privacy: str = "public") -> dict:
|
||||
return {"id": vid, "snippet": {"title": f"제목 {vid}", "publishedAt": published}, "contentDetails": {"duration": duration},
|
||||
"status": {"embeddable": embeddable, "privacyStatus": privacy}}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_channel_shorts_keeps_public_embeddable_short_videos_newest_first():
|
||||
videos = [
|
||||
_video("old", "PT30S", "2026-10-20T00:00:00Z"),
|
||||
_video("new", "PT58S", "2026-10-26T00:00:00Z"),
|
||||
_video("long", "PT10M", "2026-10-25T00:00:00Z"),
|
||||
_video("noembed", "PT20S", "2026-10-24T00:00:00Z", embeddable=False),
|
||||
_video("private", "PT20S", "2026-10-23T00:00:00Z", privacy="unlisted"),
|
||||
]
|
||||
async with httpx.AsyncClient(transport=_api(videos)) as client:
|
||||
found = await channel_shorts(client, "key", "UCtest", 10)
|
||||
assert [v["id"] for v in found] == ["new", "old"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_video_title_none_when_embedding_blocked():
|
||||
def handle(req: httpx.Request) -> httpx.Response:
|
||||
if "blocked" in req.url.params["url"]:
|
||||
return httpx.Response(401)
|
||||
return httpx.Response(200, content=json.dumps({"title": "오늘 자전거각"}))
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:
|
||||
assert await video_title(client, "ok") == "오늘 자전거각"
|
||||
assert await video_title(client, "blocked") is None
|
||||
Reference in new issue
Block a user