Merge remote-tracking branch 'origin/main' into feat/weather-saju
# Conflicts: # shared/api/client/@tanstack/react-query.gen.ts # shared/api/client/index.ts # shared/api/client/sdk.gen.ts
This commit is contained in:
commit
c61d488794
17 files changed
+469
-126
No files matched your search
@@ -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 = ""
|
||||
|
||||
@@ -4,7 +4,7 @@ from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.level.protocol import LevelAction, LevelStep, LevelUnlock, Res_Level
|
||||
from router.v1.level.protocol import LevelAction, LevelStep, LevelUnlock, Req_GameRound, Res_GameStart, Res_Level
|
||||
from services.level_service import LEVELS, LevelService, Status
|
||||
|
||||
router = APIRouter(prefix="/v1/level", tags=["level"])
|
||||
@@ -33,3 +33,13 @@ async def attend(user: User = Depends(current_user), service: LevelService = Dep
|
||||
@router.post("/share", response_model=Res_Level, response_model_exclude_none=True, summary="공유를 마쳤을 때 (하루 한 번 각)")
|
||||
async def shared(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.share(user))
|
||||
|
||||
|
||||
@router.post("/game/start", response_model=Res_GameStart, response_model_exclude_none=True, summary="날씨게임 한 판 시작 (라운드 각을 받을 표)")
|
||||
async def game_start(user: User = Depends(current_user), service: LevelService = Depends()) -> Res_GameStart:
|
||||
return Res_GameStart(play=service.game_start(user))
|
||||
|
||||
|
||||
@router.post("/game/round", response_model=Res_Level, response_model_exclude_none=True, summary="날씨게임 라운드를 깼을 때 (2각, 하루 20각)")
|
||||
async def game_round(req: Req_GameRound, user: User = Depends(current_user), service: LevelService = Depends()) -> Res_Level:
|
||||
return _res(*await service.game_round(user, req.play, req.round))
|
||||
@@ -2,7 +2,7 @@ from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class LevelAction(WebPacketProtocol):
|
||||
@@ -36,3 +36,12 @@ class Res_Level(Res_WebPacketProtocol):
|
||||
today: list[LevelAction] = []
|
||||
unlocks: list[LevelUnlock] = []
|
||||
levels: list[LevelStep] = Field([], description="레벨 전체 (이름·필요한 각)")
|
||||
|
||||
|
||||
class Res_GameStart(Res_WebPacketProtocol):
|
||||
play: Optional[str] = Field(None, description="판 시작 표. 라운드를 깰 때 그대로 보낸다")
|
||||
|
||||
|
||||
class Req_GameRound(Req_WebPacketProtocol):
|
||||
play: str = Field(max_length=40)
|
||||
round: int = Field(description="방금 깬 라운드 (1부터)")
|
||||
Vendored
+19
@@ -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]
|
||||
@@ -1,3 +1,6 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
@@ -10,6 +13,7 @@ from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import now_kst
|
||||
from config.settings import settings
|
||||
from crud.level_crud import LevelCRUD
|
||||
|
||||
# 계정 레벨: 모은 각 총량으로 정한다 (쓰는 기능이 생겨도 레벨은 안 내려간다). 사용자 결정 10/28
|
||||
@@ -24,9 +28,14 @@ ACTIONS: dict[str, tuple[int, int, str]] = {
|
||||
"talk": (20, 20, "동네 이야기 글쓰기"),
|
||||
"checkin": (10, 10, "저녁 체크인"),
|
||||
"share": (10, 10, "공유하기"),
|
||||
"game": (2, 20, "날씨게임 라운드 깨기"),
|
||||
"streak": (50, 50, "7일 연속 출석"),
|
||||
}
|
||||
STREAK_DAYS = 7
|
||||
# 날씨게임 점수는 폰에서 계산해 조작될 수 있다. 하루 한도로 막고, 판 시작부터 라운드당 이만큼은 지나야 받는다
|
||||
GAME_ROUND_MIN_SEC = 15
|
||||
GAME_MAX_SEC = 3 * 60 * 60
|
||||
GAME_MAX_ROUND = 100
|
||||
STREAK_LOOKBACK = 60
|
||||
|
||||
# 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로)
|
||||
@@ -52,6 +61,20 @@ def is_unlocked(points: int, key: str) -> bool:
|
||||
return level_of(points) >= unlock_level(key)
|
||||
|
||||
|
||||
def game_token(user_id: uuid.UUID, ts: int) -> str:
|
||||
"""판 시작 표: 시작 시각과 서명. 그 사람만 쓸 수 있다"""
|
||||
sig = hmac.new(settings.jwt_access_secret.encode(), f"game:{user_id}:{ts}".encode(), hashlib.sha256).hexdigest()[:16]
|
||||
return f"{ts}.{sig}"
|
||||
|
||||
|
||||
def game_round_ok(user_id: uuid.UUID, play: str, round_no: int, now: int) -> bool:
|
||||
ts, _, _ = play.partition(".")
|
||||
if not ts.isdigit() or not hmac.compare_digest(game_token(user_id, int(ts)), play):
|
||||
return False
|
||||
elapsed = now - int(ts)
|
||||
return 1 <= round_no <= GAME_MAX_ROUND and round_no * GAME_ROUND_MIN_SEC <= elapsed <= GAME_MAX_SEC
|
||||
|
||||
|
||||
def streak(days: set[date], today: date) -> int:
|
||||
"""오늘부터 거꾸로 이어 출석한 날 수"""
|
||||
n = 0
|
||||
@@ -139,3 +162,11 @@ class LevelService:
|
||||
async def share(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
||||
await award(user.user_id, "share")
|
||||
return await self.status(user)
|
||||
|
||||
def game_start(self, user: User) -> str:
|
||||
return game_token(user.user_id, int(time.time()))
|
||||
|
||||
async def game_round(self, user: User, play: str, round_no: int) -> tuple[ErrorType, Optional[Status]]:
|
||||
if game_round_ok(user.user_id, play, round_no, int(time.time())):
|
||||
await award(user.user_id, "game", f"{play}:{round_no}")
|
||||
return await self.status(user)
|
||||
@@ -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]
|
||||
@@ -102,3 +102,42 @@ async def test_seven_day_attendance_bonus(offline):
|
||||
me = (await c.post("/v1/level/attend", headers=h)).json()
|
||||
# 지난 6일은 장부만 넣어 총량엔 없다: 오늘 출석 10 + 7일 연속 50
|
||||
assert me["streak"] == 7 and me["points"] == 60
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_game_rounds_award_two_each_up_to_twenty(offline):
|
||||
import time
|
||||
|
||||
from services.level_service import GAME_ROUND_MIN_SEC, game_token
|
||||
|
||||
async with client() as c:
|
||||
h = await _login(c, "level_03")
|
||||
other = await _login(c, "level_04")
|
||||
uid = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(select(User.user_id).where(User.login_id == "level_03")))
|
||||
uid = uid[1]
|
||||
|
||||
play = (await c.post("/v1/level/game/start", headers=h)).json()["play"]
|
||||
# 시작하자마자 깬 라운드는 받지 않는다
|
||||
me = (await c.post("/v1/level/game/round", json={"play": play, "round": 1}, headers=h)).json()
|
||||
assert _earned(me, "game") == 0
|
||||
|
||||
# 충분히 지난 판: 라운드마다 2각, 같은 라운드는 한 번
|
||||
old = game_token(uid, int(time.time()) - GAME_ROUND_MIN_SEC * 30)
|
||||
await c.post("/v1/level/game/round", json={"play": old, "round": 1}, headers=h)
|
||||
me = (await c.post("/v1/level/game/round", json={"play": old, "round": 1}, headers=h)).json()
|
||||
assert _earned(me, "game") == 2 and me["points"] == 2
|
||||
|
||||
# 남의 판·위조한 판은 받지 않는다
|
||||
me = (await c.post("/v1/level/game/round", json={"play": old, "round": 2}, headers=other)).json()
|
||||
assert _earned(me, "game") == 0
|
||||
forged = old.split(".")[0] + ".0000000000000000"
|
||||
me = (await c.post("/v1/level/game/round", json={"play": forged, "round": 2}, headers=h)).json()
|
||||
assert _earned(me, "game") == 2
|
||||
|
||||
# 하루 20각까지
|
||||
for r in range(2, 15):
|
||||
me = (await c.post("/v1/level/game/round", json={"play": old, "round": r}, headers=h)).json()
|
||||
assert _earned(me, "game") == 20 and me["points"] == 20
|
||||
|
||||
# 로그인 안 하면 판을 열 수 없다
|
||||
assert (await c.post("/v1/level/game/start")).status_code == 401
|
||||
@@ -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 = []
|
||||
|
||||
Reference in new issue
Block a user