Merge remote-tracking branch 'origin/main' into main-2

This commit is contained in:
minaChoi committed 2026-10-06 16:36:23 +09:00
commit 66c35fab72
109 files changed
+2687

No files matched your search

View File
Whitespace-only changes.
+47
View File
@@ -0,0 +1,47 @@
from datetime import datetime
from typing import Literal, Optional
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
from router.v1.feed.protocol import TopIndex
class WatchNow(WebPacketProtocol):
temp_c: Optional[float] = None
icon: Optional[str] = None
rain_2h: Optional[bool] = None
text: Optional[str] = None
class WatchSunset(WebPacketProtocol):
is_today: bool
score: int
grade_label: str
sunset_at: datetime
best_at: datetime
class WatchSlot(WebPacketProtocol):
at: datetime
icon: str
temp_c: Optional[float] = None
rain_prob: Optional[int] = None
class WatchTimeline(WebPacketProtocol):
start_at: datetime
kind: Literal["gak", "sunset"]
class Res_WatchSummary(Res_WebPacketProtocol):
region_code: Optional[str] = None
region_name: Optional[str] = None
issued_at: Optional[datetime] = None
refresh_at: Optional[datetime] = None
mode: Optional[Literal["morning", "day", "evening", "night"]] = None
now: Optional[WatchNow] = None
warning: Optional[str] = None
top: list[TopIndex] = []
picks: list[TopIndex] = []
sunset: Optional[WatchSunset] = None
slots: list[WatchSlot] = []
timeline: list[WatchTimeline] = []
+98
View File
@@ -0,0 +1,98 @@
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