Files
o2o-weather/backend/router/v1/watch/watch.py
T
HyeongBaeYangandClaude Opus 5.5 8c7fbdaac7 feat: 날씨각 워치 스킨(WFF) — 1~7위 링, 구름·비·눈 애니메이션, 귀여운 해
- watchface 모듈: 큰 원 1위 + 둘레 링 2~7위, 시간대 하늘, 구름 흐름, 비·눈 오버레이
- 앱: 순위별 컴플리케이션(1~7위), 비·눈 컴플리케이션, 히어로 장 비·눈·해 광선
- 백엔드: /v1/watch/summary top 을 7개로

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:38:11 +09:00

99 lines
4.8 KiB
Python

import asyncio
from datetime import datetime, timedelta
from typing import Optional
from fastapi import APIRouter, Depends, Query
from common.database.model.models import SkyScore
from common.enums import ErrorType, SkyGrade
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 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
from services.index_service import IndexService
from services.now_service import NowService
from services.sky_service import SkyService
from services.weather_service import WeatherService
router = APIRouter(prefix="/v1/watch", tags=["watch"])
MAX_PICKS = 3
# 워치 스킨이 큰 원(1위) + 둘레 링 6개(2~7위)를 채운다
TOP_N = 7
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)
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:
return [WatchTimeline(start_at=now, kind="gak")]
start, end = _best(sunset, "sun") - timedelta(hours=2), _best(sunset, "twilight")
if now >= end:
return [WatchTimeline(start_at=now, kind="gak")]
items = [WatchTimeline(start_at=now, kind="gak")] if now < start else []
return items + [WatchTimeline(start_at=max(start, now), kind="sunset"), WatchTimeline(start_at=end, kind="gak")]
@router.get("/summary", response_model=Res_WatchSummary, response_model_exclude_none=True, summary="워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표")
async def get_watch_summary(
region: str = Query(..., description="구 행정코드"),
pick: Optional[str] = Query(None, description="내 각 코드, 쉼표로 최대 3개 (예: running,laundry)"),
weather: WeatherService = Depends(),
now_service: NowService = Depends(),
sky: SkyService = Depends(),
index: IndexService = 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),
)
today = today if err_t is ErrorType.SUCCESS else None
now_w = now_w if err_n is ErrorType.SUCCESS else None
view = view if err_s is ErrorType.SUCCESS else None
board = board if err_i is ErrorType.SUCCESS else None
found = next((x.region for x in (today, now_w, view, board) if x is not None), None)
if found is None:
return Res_WatchSummary(result=error_info(err_t))
now = now_kst()
sunset_at = sun_times(now.date(), float(found.lat), float(found.lon)).sunset_at
res = Res_WatchSummary(
region_code=found.code, region_name=found.name, issued_at=now, refresh_at=now + timedelta(seconds=feed_ttl_sec(now, sunset_at)),
mode=slot_of(now, sunset_at),
)
if today is not None:
past = [s for s in today.slots if s.at <= now]
cur = past[-1] if past else (today.slots[0] if today.slots else None)
if cur is not None:
res.now = WatchNow(temp_c=float(cur.row.temp_c) if cur.row else None, icon=cur.icon)
res.slots = [
WatchSlot(at=s.at.astimezone(KST), icon=s.icon, temp_c=float(s.row.temp_c) if s.row else None, rain_prob=s.row.rain_prob if s.row else None)
for s in today.slots if s.at > now
]
if now_w is not None:
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "text": now_w.rain_2h_text})
res.warning = now_w.warnings[0].text if now_w.warnings else None
if board is not None:
res.top = [_top(i) for i in board.items[:TOP_N]]
codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS]
by_code = {i.definition.code: i for i in board.items}
res.picks = [_top(by_code[c]) for c in codes if c in by_code]
target, is_today = None, False
if view is not None:
is_today = now < sunset_at
target = view.sunset if is_today else next((x for x in view.days if x.score_date > now.date()), None)
if target is not None:
res.sunset = WatchSunset(
is_today=is_today, score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)],
sunset_at=_best(target, "sun"), best_at=_best(target, "peak"),
)
res.timeline = timeline(now, target, is_today)
return res