feat: 워치에 주변 축제 표시 (앱 축제 장, 스킨 날짜 밑 한 줄)
- /v1/watch/summary 에 events 2개: 진행 중 먼저, 이름 앞 [주최] 괄호 제거, 4초 넘으면 축제만 빼고 응답 - 앱: 내 각 다음에 근처 축제 장 (이름 · 상태 · 장소와 그날 날씨) - 스킨: 날짜 밑 "🎉 주변 축제 · 이름" 한 줄 (EventComplicationService, LONG_TEXT, 행사 없으면 숨김) - 스킨 배치: 해 구슬 162→136, 해·링 묶음 24px 아래로, 기온·비 칩 y 366 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a6a738ae61
commit
b4d028a91b
10 files changed
+208
-46
No files matched your search
@@ -27,6 +27,13 @@ class WatchSlot(WebPacketProtocol):
|
||||
rain_prob: Optional[int] = None
|
||||
|
||||
|
||||
class WatchEvent(WebPacketProtocol):
|
||||
name: str
|
||||
place_name: str
|
||||
status_label: str
|
||||
fit: Optional[str] = None
|
||||
|
||||
|
||||
class WatchTimeline(WebPacketProtocol):
|
||||
start_at: datetime
|
||||
kind: Literal["gak", "sunset"]
|
||||
@@ -45,3 +52,4 @@ class Res_WatchSummary(Res_WebPacketProtocol):
|
||||
sunset: Optional[WatchSunset] = None
|
||||
slots: list[WatchSlot] = []
|
||||
timeline: list[WatchTimeline] = []
|
||||
events: list[WatchEvent] = []
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
@@ -6,9 +7,10 @@ from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import ErrorType, SkyGrade
|
||||
from common.logger import LOG
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.v1.watch.protocol import Res_WatchSummary, WatchNow, WatchSlot, WatchSunset, WatchTimeline
|
||||
from router.v1.watch.protocol import Res_WatchSummary, WatchEvent, WatchNow, WatchSlot, WatchSunset, WatchTimeline
|
||||
from services.calc.sky_score import GRADE_LABEL
|
||||
from services.calc.sun import sun_times
|
||||
from services.feed_service import _SUNSET_FULL, _top, feed_ttl_sec, slot_of
|
||||
@@ -16,18 +18,32 @@ from services.index_service import IndexService
|
||||
from services.now_service import NowService
|
||||
from services.sky_service import SkyService
|
||||
from services.weather_service import WeatherService
|
||||
from services.week_service import EventItem, WeekService
|
||||
|
||||
router = APIRouter(prefix="/v1/watch", tags=["watch"])
|
||||
|
||||
MAX_PICKS = 3
|
||||
# 워치 스킨이 큰 원(1위) + 둘레 링 6개(2~7위)를 채운다
|
||||
TOP_N = 7
|
||||
MAX_EVENTS = 2
|
||||
# 워치 readTimeout(10초) 안에 끝나도록. 첫 조회라 TourAPI 를 부르다 늦으면 이번 요약엔 축제를 빼고, 캐시는 다음 조회가 채운다
|
||||
EVENTS_TIMEOUT_SEC = 4
|
||||
# "[하트하트아트앤컬처] 마음의 각도" 처럼 이름 앞 주최·분류 괄호. 워치 칸이 좁아 뺀다
|
||||
_NAME_PREFIX = re.compile(r"^(\[[^\]]*\]\s*)+")
|
||||
|
||||
|
||||
def _best(score: SkyScore, kind: str) -> datetime:
|
||||
return datetime.fromisoformat(next(b["at"] for b in score.best_times if b["kind"] == kind)).astimezone(KST)
|
||||
|
||||
|
||||
async def _events(week: WeekService, region: str) -> tuple[ErrorType, list[EventItem]]:
|
||||
try:
|
||||
return await asyncio.wait_for(week.events(region, None), EVENTS_TIMEOUT_SEC)
|
||||
except TimeoutError:
|
||||
LOG.warning(f"[watch] events {region}: {EVENTS_TIMEOUT_SEC}초 넘어 생략")
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
|
||||
|
||||
def timeline(now: datetime, sunset: Optional[SkyScore], is_today: bool) -> list[WatchTimeline]:
|
||||
"""컴플리케이션이 언제 무엇을 보여줄지. 오늘 노을이 볼 만하면(60점 이상) 일몰 2시간 전부터 보랏빛 하늘까지 노을, 나머지는 각."""
|
||||
if sunset is None or not is_today or sunset.score < _SUNSET_FULL:
|
||||
@@ -47,9 +63,10 @@ async def get_watch_summary(
|
||||
now_service: NowService = Depends(),
|
||||
sky: SkyService = Depends(),
|
||||
index: IndexService = Depends(),
|
||||
week: WeekService = Depends(),
|
||||
) -> Res_WatchSummary:
|
||||
(err_t, today), (err_n, now_w), (err_s, view), (err_i, board) = await asyncio.gather(
|
||||
weather.today(region), now_service.now(region), sky.view(region), index.board(region),
|
||||
(err_t, today), (err_n, now_w), (err_s, view), (err_i, board), (err_e, events) = await asyncio.gather(
|
||||
weather.today(region), now_service.now(region), sky.view(region), index.board(region), _events(week, region),
|
||||
)
|
||||
today = today if err_t is ErrorType.SUCCESS else None
|
||||
now_w = now_w if err_n is ErrorType.SUCCESS else None
|
||||
@@ -95,4 +112,11 @@ async def get_watch_summary(
|
||||
sunset_at=_best(target, "sun"), best_at=_best(target, "peak"),
|
||||
)
|
||||
res.timeline = timeline(now, target, is_today)
|
||||
# 축제를 못 가져와도 요약은 그대로 낸다 (err_e 면 빈 목록)
|
||||
if err_e is ErrorType.SUCCESS:
|
||||
res.events = [
|
||||
WatchEvent(name=_NAME_PREFIX.sub("", i.event.name) or i.event.name, place_name=i.event.place_name, status_label=i.status_label, fit=i.fit)
|
||||
# 진행 중인 행사를 먼저 (스킨은 첫 번째 하나만 보여 준다). 같은 상태 안에서는 서버 순서(가까운 날짜·거리) 그대로
|
||||
for i in sorted(events, key=lambda i: i.status != "live")[:MAX_EVENTS]
|
||||
]
|
||||
return res
|
||||
@@ -4,7 +4,8 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
import services.week_service as week_service
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.router import app
|
||||
from router.v1.watch.watch import timeline
|
||||
|
||||
@@ -12,6 +13,10 @@ REGION = "1141000000"
|
||||
SUN = datetime(2026, 10, 6, 18, 0, tzinfo=KST)
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
def _sunset(score: int) -> SimpleNamespace:
|
||||
return SimpleNamespace(score=score, best_times=[
|
||||
{"at": SUN.isoformat(), "kind": "sun", "label": "해 져요"},
|
||||
@@ -53,6 +58,21 @@ async def test_watch_summary_bundles_now_top_picks_sunset(offline):
|
||||
assert body["sunset"]["best_at"] > body["sunset"]["sunset_at"]
|
||||
assert all(s["at"] > body["issued_at"] for s in body["slots"])
|
||||
assert body["timeline"][0]["start_at"] == body["issued_at"]
|
||||
assert [(e["name"], e["status_label"]) for e in body["events"]] == [("테스트 축제", "진행 중")]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_watch_summary_puts_live_event_first_without_bracket_prefix(offline, monkeypatch):
|
||||
# 서버 순서는 시작일이 가까운 순이라 내일 시작이 먼저지만, 스킨에 하나만 띄우니 진행 중을 앞으로. 이름 앞 [주최] 는 뺀다
|
||||
today = now_kst().date()
|
||||
day = lambda n: (today + timedelta(days=n)).strftime("%Y%m%d")
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([
|
||||
{"contentid": "1", "title": "내일 축제", "addr1": "서울", "eventstartdate": day(1), "eventenddate": day(2)},
|
||||
{"contentid": "2", "title": "[주최] 열리는 축제", "addr1": "서울", "eventstartdate": day(-3), "eventenddate": day(2)},
|
||||
] if sido == "11" else []))
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["열리는 축제", "내일 축제"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
Reference in new issue
Block a user