Merge branch 'main' into feat/open-meteo
This commit is contained in:
commit
3e376ae4b8
49 files changed
+1163
-351
No files matched your search
@@ -135,6 +135,7 @@ class PostType(CodeEnum):
|
||||
AIR = 12
|
||||
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
|
||||
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
|
||||
UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만)
|
||||
|
||||
|
||||
class EventKind(CodeEnum):
|
||||
|
||||
@@ -28,6 +28,8 @@ class Settings(BaseSettings):
|
||||
|
||||
data_go_kr_service_key: str = ""
|
||||
teams_webhook_url: str = ""
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr"
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
@@ -40,6 +42,10 @@ class Settings(BaseSettings):
|
||||
"""인코딩 키를 넣어도 디코딩해 둔다. httpx 가 다시 인코딩하므로 이중 인코딩을 막는다."""
|
||||
return unquote(v) if "%" in v else v
|
||||
|
||||
@property
|
||||
def image_proxy_host_set(self) -> frozenset[str]:
|
||||
return frozenset(h.strip().lower() for h in self.image_proxy_hosts.split(",") if h.strip())
|
||||
|
||||
@property
|
||||
def db_url(self) -> str:
|
||||
return f"postgresql+asyncpg://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}"
|
||||
|
||||
@@ -52,6 +52,9 @@ class WeatherCRUD:
|
||||
async def latest_issued(self, s: AsyncSession, region_code: str) -> Optional[datetime]:
|
||||
return await s.scalar(select(func.max(WeatherHourly.issued_at)).where(WeatherHourly.region_code == region_code))
|
||||
|
||||
async def has_hourly_at(self, s: AsyncSession, region_code: str, at: datetime) -> bool:
|
||||
return await s.get(WeatherHourly, (region_code, at)) is not None
|
||||
|
||||
async def hourly_between(self, s: AsyncSession, region_code: str, start: datetime, end: datetime) -> list[WeatherHourly]:
|
||||
stmt = (
|
||||
select(WeatherHourly)
|
||||
|
||||
@@ -9,6 +9,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from router.v1.auth.account import router as auth_router
|
||||
from router.v1.feed.feed import router as feed_router
|
||||
from router.v1.image.image import router as image_router
|
||||
from router.v1.index.index import router as index_router
|
||||
from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
@@ -41,6 +42,7 @@ app.include_router(feed_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
|
||||
@@ -133,6 +133,13 @@ class TopIndex(WebPacketProtocol):
|
||||
summary: Optional[str] = None
|
||||
|
||||
|
||||
class HeroStat(WebPacketProtocol):
|
||||
icon: str
|
||||
label: str
|
||||
value: str
|
||||
tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)")
|
||||
|
||||
|
||||
class Hero(WebPacketProtocol):
|
||||
now_at: datetime
|
||||
sky_mode: Literal["morning", "day", "sunset", "night"]
|
||||
@@ -147,6 +154,7 @@ class Hero(WebPacketProtocol):
|
||||
bubble: Optional[str] = None
|
||||
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
|
||||
moon_pct: Optional[int] = Field(default=None, description="달이 밝게 보이는 비율 0~100")
|
||||
stats: list[HeroStat] = Field(default_factory=list, description="히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저")
|
||||
|
||||
|
||||
class BandEvent(WebPacketProtocol):
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,22 @@
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import Response
|
||||
|
||||
from common.logger import LOG
|
||||
from services.external.image_proxy import TIMEOUT_SEC, ImageFetchFailed, allowed, fetch_image
|
||||
|
||||
router = APIRouter(prefix="/v1/image", tags=["image"])
|
||||
|
||||
|
||||
# 이미지 자체를 돌려주므로 다른 API 와 달리 실패는 HTTP 상태 코드로 알린다
|
||||
@router.get("", summary="행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)", responses={200: {"content": {"image/*": {}}}, 400: {}, 502: {}})
|
||||
async def get_image(url: str = Query(..., max_length=2048, description="원본 이미지 주소")) -> Response:
|
||||
if not allowed(url):
|
||||
raise HTTPException(status_code=400, detail="url not allowed")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=TIMEOUT_SEC, headers={"User-Agent": "nalssigak-bot"}) as client:
|
||||
data, ctype = await fetch_image(client, url)
|
||||
except (ImageFetchFailed, httpx.HTTPError) as e:
|
||||
LOG.warning(f"[image] fetch failed {url}: {e!r}")
|
||||
raise HTTPException(status_code=502, detail="image fetch failed") from e
|
||||
return Response(content=data, media_type=ctype, headers={"Cache-Control": "public, max-age=86400", "X-Content-Type-Options": "nosniff"})
|
||||
@@ -7,7 +7,7 @@ OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
|
||||
|
||||
CAT = {1: "밖에서 놀기", 2: "먹고 마시기", 3: "집안일", 4: "생활 고민"}
|
||||
WD = {"mon": "월", "tue": "화", "wed": "수", "thu": "목", "fri": "금", "sat": "토", "sun": "일", "holiday": "공휴일", "default": "그 외"}
|
||||
FIELD = {"rain_prob": ("비 확률", "%"), "wind_ms": ("바람", "m/s"), "feels_c": ("체감", "°"), "pm25": ("초미세먼지", "㎍/㎥"), "cloudy_ratio": ("흐린 시간 비율", "%")}
|
||||
FIELD = {"rain_prob": ("비 확률", "%"), "wind_ms": ("바람", "m/s"), "feels_c": ("체감", "°"), "pm25": ("초미세먼지", "㎍/㎥"), "cloudy_ratio": ("흐린 시간 비율", "%"), "gust_ms": ("돌풍", "m/s"), "ground_c": ("지면 온도", "°")}
|
||||
|
||||
|
||||
def win(w):
|
||||
@@ -70,7 +70,12 @@ def zero(z):
|
||||
return s + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
|
||||
|
||||
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", None), ("time", "시간·요일", tim)]
|
||||
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", None),
|
||||
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
|
||||
("sun", "햇빛", lambda r: f"해 난 비율 {round(r['full'] * 100)}% 이상이면 만점, {round(r['zero'] * 100)}% 이하면 0점 (Open-Meteo)"),
|
||||
("view", "가시거리", lambda r: f"{r['full']}km 이상이면 만점, {r['zero']}km 이하면 0점 (Open-Meteo)"),
|
||||
("time", "시간·요일", tim)]
|
||||
_OPTIONAL = ("uv", "sun", "view") # 비중이 있는 각에만 적는다
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -103,7 +108,9 @@ def main() -> None:
|
||||
P(f"- 시간대: {' / '.join(win(w) for w in x['windows'])}")
|
||||
P("- 요소별 규칙 (비중):")
|
||||
for key, label, fn in AX:
|
||||
w = x["weight_" + key]
|
||||
w = x.get("weight_" + key, 0)
|
||||
if key in _OPTIONAL and not w:
|
||||
continue
|
||||
rule = "초미세먼지 낮을수록 좋음" if fn is None else fn(x["factor_rules"][key])
|
||||
P(f" - {label} {w}%: {rule}")
|
||||
zs = [zero(z) for z in x["zero_rules"]]
|
||||
|
||||
@@ -198,7 +198,7 @@ _WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "
|
||||
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
|
||||
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
||||
_OM_LABEL = {"uv": "자외선", "sun": "햇빛", "view": "가시거리"}
|
||||
_OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"}
|
||||
|
||||
|
||||
def axis_label(axis: str, rules: dict) -> str:
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
|
||||
from config.settings import settings
|
||||
|
||||
# 공유 이미지에 행사 사진을 그리려고 대신 받아 준다. 사진 서버가 브라우저가 픽셀을 읽는 것(CORS)을 막기 때문. 허용 호스트는 IMAGE_PROXY_HOSTS.
|
||||
MAX_BYTES = 5 * 1024 * 1024
|
||||
TIMEOUT_SEC = 10.0
|
||||
|
||||
|
||||
class ImageFetchFailed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def allowed(url: str) -> bool:
|
||||
"""https, 허용한 호스트, 기본 포트, 계정 정보 없음일 때만."""
|
||||
try:
|
||||
u = urlsplit(url)
|
||||
port = u.port
|
||||
except ValueError:
|
||||
return False
|
||||
return u.scheme == "https" and u.hostname in settings.image_proxy_host_set and port in (None, 443) and not u.username and not u.password
|
||||
|
||||
|
||||
async def fetch_image(client: httpx.AsyncClient, url: str) -> tuple[bytes, str]:
|
||||
"""이미지 바이트와 content-type. 리다이렉트는 따라가지 않는다."""
|
||||
async with client.stream("GET", url, follow_redirects=False) as res:
|
||||
if res.status_code != 200:
|
||||
raise ImageFetchFailed(f"status {res.status_code}")
|
||||
ctype = res.headers.get("content-type", "").split(";")[0].strip().lower()
|
||||
if not ctype.startswith("image/") or ctype == "image/svg+xml":
|
||||
raise ImageFetchFailed(f"content-type {ctype or '-'}")
|
||||
buf = bytearray()
|
||||
async for chunk in res.aiter_bytes():
|
||||
buf += chunk
|
||||
if len(buf) > MAX_BYTES:
|
||||
raise ImageFetchFailed("too large")
|
||||
return bytes(buf), ctype
|
||||
@@ -1,6 +1,6 @@
|
||||
import asyncio
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Optional
|
||||
|
||||
@@ -10,8 +10,8 @@ from redis.exceptions import RedisError
|
||||
from common.cache.lock import redis_lock
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Article, Post, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
||||
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, WarningType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
||||
from common.utils.text import compass, day_range, hour_label, short_day
|
||||
@@ -20,7 +20,7 @@ from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.v1.feed.protocol import (
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeekDay, WeekSlide,
|
||||
)
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
@@ -28,6 +28,7 @@ from services.air_service import pm10_grade, pm25_grade
|
||||
from services.calc.moon import illumination, nearest, phase_name
|
||||
from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE
|
||||
from services.calc.sun import sun_times
|
||||
from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
@@ -59,20 +60,24 @@ LINEUP = [
|
||||
(17, PostType.AIR, RefType.NONE, None),
|
||||
(18, PostType.DAY_TRIP, RefType.NONE, None),
|
||||
(19, PostType.MOON, RefType.NONE, None),
|
||||
(20, PostType.UV, RefType.NONE, None),
|
||||
]
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
}
|
||||
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||
_FEED_TTL_MAX = 3600
|
||||
_PARTIAL_TTL = 60
|
||||
_SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용
|
||||
_NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||
_RAIN_PROB = 40
|
||||
_UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다
|
||||
_HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸
|
||||
_SUNSET_FULL = 60
|
||||
_FEED_DAY_START = 3 # 03:00 에 그날 카드가 바뀐다
|
||||
_COMMUTE_HOURS = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
||||
@@ -116,16 +121,31 @@ def _discomfort_label(v: int) -> str:
|
||||
return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌"
|
||||
|
||||
|
||||
def _hero_input(now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float]) -> HeroInput:
|
||||
temps = [float(x.row.temp_c) for x in today.slots if x.row] if today else []
|
||||
rainy = [h for h in now_w.rain_hours if h.rain_type is not RainType.NONE] if now_w else []
|
||||
ahead = [x for x in today.slots if x.row and x.at > now] if today else []
|
||||
later = next((x.at for x in ahead if x.row.rain_type != RainType.NONE.value or x.row.rain_prob >= _HERO_RAIN_PROB), None)
|
||||
return HeroInput(
|
||||
now=now, night=slot in ("evening", "night"), rain_at=rainy[0].at if rainy else None,
|
||||
rain_later_at=later, today_known=bool(ahead),
|
||||
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
|
||||
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
|
||||
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||
moon=phase_name(_tonight(now)),
|
||||
)
|
||||
|
||||
|
||||
def feed_day(now: datetime) -> date:
|
||||
return (now - timedelta(hours=_FEED_DAY_START)).date()
|
||||
|
||||
|
||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–21 · 밤 21–05."""
|
||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||
h = now.hour
|
||||
if 5 <= h < 11:
|
||||
return "morning"
|
||||
if 11 <= h < 21:
|
||||
if h >= 11 and now < sunset_at + _NIGHT_AFTER_SUNSET:
|
||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
||||
return "night"
|
||||
|
||||
@@ -135,7 +155,7 @@ def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
day = now.date()
|
||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||
sunset = sunset_at.astimezone(KST)
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, at(day, 21),
|
||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + _NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
@@ -317,7 +337,8 @@ class FeedService:
|
||||
by_article = {a.article_id: a for a in articles or []}
|
||||
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]
|
||||
ctx = _Ctx(region=region, now=now, slot=slot, sunset_at=sunset_at, today=today, tomorrow=tomorrow, now_w=now_w, sky=sky, board=board,
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip)
|
||||
days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip,
|
||||
uv=await self._uv_today(region.code, now))
|
||||
|
||||
gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
|
||||
cards = []
|
||||
@@ -334,7 +355,7 @@ class FeedService:
|
||||
items = board.items if board else []
|
||||
feed = Res_Feed(
|
||||
region_code=region.code, region_name=region.name, slot=slot,
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board),
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour)),
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
@@ -365,7 +386,22 @@ class FeedService:
|
||||
return (pick, []), True
|
||||
return (pick, pick_events(pick.best.day, items)), False
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard]) -> Hero:
|
||||
async def _uv_today(self, region_code: str, now: datetime) -> list[OpenMeteoHourly]:
|
||||
"""오늘 09~18시 3시간 칸 끝 시각의 자외선 (Open-Meteo)."""
|
||||
day = kst_midnight(now.date())
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
lambda s: self.weather_crud.openmeteo_between(s, region_code, day + timedelta(hours=9), day + timedelta(hours=18))
|
||||
)
|
||||
return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||
|
||||
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour))
|
||||
if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None:
|
||||
return None
|
||||
return float(rows[0].uv_index)
|
||||
|
||||
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
|
||||
today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero:
|
||||
top = board.items[0] if board and board.items else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
@@ -377,6 +413,7 @@ class FeedService:
|
||||
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
|
||||
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=phase_name(_tonight(now)), moon_pct=round(illumination(_tonight(now)) * 100),
|
||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(_hero_input(now, slot, cur, now_w, today, uv))],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -446,6 +483,8 @@ class FeedService:
|
||||
return self._day_trip(base, *c.trip)
|
||||
if t is PostType.MOON:
|
||||
return self._moon(base, c)
|
||||
if t is PostType.UV:
|
||||
return self._uv_post(base, c)
|
||||
return None
|
||||
|
||||
def _moon(self, base: dict, c: "_Ctx") -> PostData:
|
||||
@@ -548,6 +587,25 @@ class FeedService:
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"생활 알림 · {c.region.short_name}", line=line, icon=icon, rows=rows)],
|
||||
share_messages=[f"{line} {tail}"])
|
||||
|
||||
def _uv_post(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""오늘 낮 자외선. 가장 셀 때가 '보통'(3) 아래면 챙길 게 없어 끈다."""
|
||||
if not c.uv:
|
||||
return None
|
||||
peak = max(c.uv, key=lambda r: r.uv_index)
|
||||
top = float(peak.uv_index)
|
||||
if top < _UV_SHOW:
|
||||
return None
|
||||
label = uv_label(top)
|
||||
at = peak.forecast_at.astimezone(KST)
|
||||
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv]
|
||||
high = top >= UV_HIGH
|
||||
if high:
|
||||
rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요"))
|
||||
line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림")
|
||||
return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
|
||||
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
|
||||
|
||||
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
||||
air = c.now_w.air if c.now_w else None
|
||||
@@ -623,15 +681,24 @@ class FeedService:
|
||||
slides=[RowsSlide(kind="rows", eyebrow="오늘의 한 문장", line=a.body[0], icon=a.icon, rows=rows)], share_messages=[a.body[0]])
|
||||
|
||||
|
||||
def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
|
||||
"""seed 의 점수 구간 설명 {"0": …, "30": …, "60": …, "80": …} 중 점수가 들어가는 구간 문장."""
|
||||
lo = next((x for x in sorted((int(k) for k in sentences or {}), reverse=True) if score >= x), None)
|
||||
return sentences[str(lo)] if lo is not None else None
|
||||
|
||||
|
||||
def _gak_caption(i: IndexItem) -> str:
|
||||
"""슬라이드에 없는 내일 점수, 없으면 하기 좋은 시간."""
|
||||
"""점수 구간 설명 문장 + 슬라이드에 없는 내일 점수(없으면 하기 좋은 시간)."""
|
||||
band = _band_sentence(i.definition.sentences, i.score.score)
|
||||
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
|
||||
if nxt is not None:
|
||||
diff = nxt.score - i.score.score
|
||||
how = "비슷해요" if abs(diff) < 5 else f"오늘보다 {abs(diff)}점 {'높아요' if diff > 0 else '낮아요'}"
|
||||
return f"내일은 {nxt.score}점, {how}."
|
||||
spans = [_span(w) for w in i.definition.windows or []]
|
||||
return f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
||||
tail = f"내일은 {nxt.score}점, {how}."
|
||||
else:
|
||||
spans = [_span(w) for w in i.definition.windows or []]
|
||||
tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
|
||||
return f"{band} {tail}" if band else tail
|
||||
|
||||
|
||||
def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]:
|
||||
@@ -683,3 +750,4 @@ class _Ctx:
|
||||
articles: dict[int, Article]
|
||||
quotes: list[Article]
|
||||
trip: Optional[tuple[TripPick, list[EventItem]]] = None
|
||||
uv: list[OpenMeteoHourly] = field(default_factory=list) # 오늘 낮 3시간 칸 자외선
|
||||
@@ -0,0 +1,88 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from common.enums import AirGrade
|
||||
from common.utils.kma_time import KST
|
||||
from common.utils.text import hour_label
|
||||
from services.air_service import GRADE_LABEL
|
||||
|
||||
Tone = Literal["normal", "warn", "rain"]
|
||||
|
||||
UV_HIGH = 6.0
|
||||
TEMP_SWING_C = 10.0
|
||||
WIND_CHILL_C = 3.0
|
||||
MUGGY = 75
|
||||
SHOWN = 2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HeroStatItem:
|
||||
key: str
|
||||
icon: str
|
||||
label: str
|
||||
value: str
|
||||
tone: Tone = "normal"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HeroInput:
|
||||
now: datetime
|
||||
night: bool
|
||||
rain_at: Optional[datetime] = None # 앞으로 2시간 안에 비 오는 첫 시각 (초단기)
|
||||
rain_later_at: Optional[datetime] = None # 그 뒤 오늘 안에 비 오는 첫 시각 (단기예보)
|
||||
today_known: bool = False # 오늘 남은 시간 예보가 있어 '오늘 비 안 와요'라고 말할 수 있는지
|
||||
air: Optional[AirGrade] = None
|
||||
uv: Optional[float] = None
|
||||
temp_min: Optional[float] = None
|
||||
temp_max: Optional[float] = None
|
||||
temp: Optional[float] = None
|
||||
feels: Optional[float] = None
|
||||
discomfort: Optional[int] = None
|
||||
moon: Optional[str] = None
|
||||
|
||||
|
||||
def uv_label(uv: float) -> str:
|
||||
return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험"
|
||||
|
||||
|
||||
def _discomfort_label(v: int) -> str:
|
||||
return "보통" if v < 75 else "높음" if v < 80 else "매우 높음"
|
||||
|
||||
|
||||
def _rain_value(now: datetime, at: datetime) -> str:
|
||||
return "지금 와요" if at <= now else f"{hour_label(at.astimezone(KST).hour)}쯤 와요"
|
||||
|
||||
|
||||
def hero_stats(x: HeroInput) -> list[HeroStatItem]:
|
||||
"""히어로 두 칸. 지금 챙겨야 할 것(경고)을 먼저, 모자라면 기본값으로 채운다."""
|
||||
alerts: list[HeroStatItem] = []
|
||||
if x.rain_at is not None:
|
||||
alerts.append(HeroStatItem("rain", "umbrella", "지금 비", _rain_value(x.now, x.rain_at), "rain"))
|
||||
elif x.rain_later_at is not None:
|
||||
alerts.append(HeroStatItem("rain", "umbrella", "오늘 비", _rain_value(x.now, x.rain_later_at), "rain"))
|
||||
if x.air in (AirGrade.BAD, AirGrade.VERY_BAD):
|
||||
alerts.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn"))
|
||||
if not x.night and x.uv is not None and x.uv >= UV_HIGH:
|
||||
alerts.append(HeroStatItem("uv", "glasses", "자외선", f"{round(x.uv)} · {uv_label(x.uv)}", "warn"))
|
||||
if x.temp_min is not None and x.temp_max is not None and x.temp_max - x.temp_min >= TEMP_SWING_C:
|
||||
alerts.append(HeroStatItem("swing", "coldwind", f"일교차 {round(x.temp_max - x.temp_min)}°", "아침엔 겉옷"))
|
||||
if x.temp is not None and x.feels is not None and x.temp - x.feels >= WIND_CHILL_C:
|
||||
alerts.append(HeroStatItem("chill", "coldwind", f"체감 {round(x.feels)}°", "바람 쌀쌀"))
|
||||
if x.discomfort is not None and x.discomfort >= MUGGY:
|
||||
alerts.append(HeroStatItem("muggy", "muggy", "불쾌지수", f"{x.discomfort} · {_discomfort_label(x.discomfort)}", "warn"))
|
||||
|
||||
# 챙길 게 없을 땐 하루 기준 비 소식과 밤의 달만. '미세먼지 좋음'·'자외선 낮음' 같은 값으로 칸을 채우지 않는다
|
||||
fills: list[HeroStatItem] = []
|
||||
if x.today_known and x.rain_at is None and x.rain_later_at is None:
|
||||
fills.append(HeroStatItem("rain", "moon" if x.night else "sun", "오늘 밤 비" if x.night else "오늘 비", "안 와요"))
|
||||
if x.night and x.moon:
|
||||
fills.append(HeroStatItem("moon", "moon", "오늘 밤 달", x.moon))
|
||||
|
||||
picked: list[HeroStatItem] = []
|
||||
for item in alerts + fills:
|
||||
if item.key not in {p.key for p in picked} and not (item.icon == "coldwind" and any(p.icon == "coldwind" for p in picked)):
|
||||
picked.append(item)
|
||||
if len(picked) == SHOWN:
|
||||
break
|
||||
return picked
|
||||
@@ -170,19 +170,33 @@ class WeatherService:
|
||||
"""예보가 지났으면 새로 받는다. 이미 있으면 뒤에서 갱신하고, background=False 면 받을 때까지 기다린다."""
|
||||
latest = latest_vilage_base(now)
|
||||
err, issued = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.latest_issued(s, region.code))
|
||||
if err is not ErrorType.SUCCESS or (issued is not None and issued >= latest):
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return
|
||||
from_midnight = issued is None or await self._midnight_missing(region, now)
|
||||
if issued is not None and issued >= latest and not from_midnight:
|
||||
return
|
||||
if issued is None or not background:
|
||||
await self._refresh(region, now, latest, wait=issued is None)
|
||||
await self._refresh(region, now, latest, wait=issued is None, from_midnight=from_midnight)
|
||||
return
|
||||
task = asyncio.create_task(self._refresh(region, now, latest, wait=False))
|
||||
task = asyncio.create_task(self._refresh(region, now, latest, wait=False, from_midnight=from_midnight))
|
||||
_background.add(task)
|
||||
task.add_done_callback(_background.discard)
|
||||
|
||||
async def _refresh(self, region: Region, now: datetime, latest: datetime, wait: bool) -> None:
|
||||
async def _midnight_missing(self, region: Region, now: datetime) -> bool:
|
||||
"""오늘 0시 칸이 비었는지. 전날 23시 발표 받기가 실패했을 때 다시 받되, 10분에 한 번만 시도한다."""
|
||||
err, has = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_hourly_at(s, region.code, kst_midnight(now.date())))
|
||||
if err is not ErrorType.SUCCESS or has:
|
||||
return False
|
||||
try:
|
||||
return bool(await REDIS.conn.set(f"vilage0:{region.code}:{now:%Y%m%d}", "1", ex=600, nx=True))
|
||||
except RedisError as e:
|
||||
LOG.error(f"[weather] {region.code} midnight retry: {e}")
|
||||
return False
|
||||
|
||||
async def _refresh(self, region: Region, now: datetime, latest: datetime, wait: bool, from_midnight: bool) -> None:
|
||||
async with redis_lock(f"lock:vilage:{region.code}") as acquired:
|
||||
if acquired:
|
||||
bases = [day_start_base(now.date()), latest] if wait else [latest]
|
||||
bases = [day_start_base(now.date()), latest] if from_midnight else [latest]
|
||||
await self._fetch_and_store(region, sorted(set(bases)))
|
||||
return
|
||||
if wait:
|
||||
|
||||
@@ -2,6 +2,7 @@ from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import EventKind
|
||||
from common.utils.kma_time import KST
|
||||
from common.utils.text import day_range, short_day
|
||||
from services.week_service import DayPlan, EventItem, image_credit
|
||||
@@ -10,6 +11,8 @@ _HOT = 28
|
||||
_COLD = 10
|
||||
_BIG_GAP = 10
|
||||
_MAX_EVENTS = 2
|
||||
# 주말 동선은 축제를 먼저, 전시는 마지막. 가깝다고 미술관만 이어지지 않게
|
||||
_KIND_RANK = {EventKind.FESTIVAL: 0, EventKind.CONCERT: 1, EventKind.POPUP: 2, EventKind.EXHIBITION: 3}
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -77,11 +80,16 @@ def forecast(days: list[DayPlan]) -> WeekendForecast:
|
||||
|
||||
|
||||
def pick_events(d: date, events: list[EventItem], exclude: frozenset[int] = frozenset()) -> list[EventItem]:
|
||||
"""그날 열리는 행사 중 가까운 순. 일요일은 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
|
||||
"""그날 열리는 행사를 축제→공연→팝업→전시 순으로 종류마다 하나씩, 같은 종류는 가까운 순. 일요일은 같은 종류 안에서 그날 끝나는 것을 먼저 (마지막 날 찬스)."""
|
||||
sunday = d.weekday() == 6
|
||||
open_ = [e for e in events if e.event.start_date <= d <= e.event.end_date and e.event.event_id not in exclude]
|
||||
open_.sort(key=lambda e: (sunday and e.event.end_date != d, e.distance_km if e.distance_km is not None else 9999))
|
||||
return open_[:_MAX_EVENTS]
|
||||
open_.sort(key=lambda e: (_KIND_RANK.get(e.event.kind, len(_KIND_RANK)), sunday and e.event.end_date != d,
|
||||
e.distance_km if e.distance_km is not None else 9999))
|
||||
first, rest, kinds = [], [], set()
|
||||
for e in open_:
|
||||
(rest if e.event.kind in kinds else first).append(e)
|
||||
kinds.add(e.event.kind)
|
||||
return (first + rest)[:_MAX_EVENTS]
|
||||
|
||||
|
||||
def _place(e: EventItem) -> str:
|
||||
|
||||
@@ -100,8 +100,11 @@ def test_slot_follows_sunset():
|
||||
|
||||
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
||||
at = lambda h, m=0: datetime(2026, 10, 2, h, m, tzinfo=KST) # noqa: E731
|
||||
assert [slot_of(at(h, m), sunset) for h, m in ((4, 59), (5, 0), (11, 0), (16, 9), (16, 10), (20, 59), (21, 0))] == [
|
||||
"night", "morning", "day", "day", "evening", "evening", "night"]
|
||||
assert [slot_of(at(h, m), sunset) for h, m in ((4, 59), (5, 0), (11, 0), (16, 9), (16, 10), (19, 9), (19, 10), (23, 0))] == [
|
||||
"night", "morning", "day", "day", "evening", "evening", "night", "night"]
|
||||
summer = datetime(2026, 6, 21, 19, 57, tzinfo=KST)
|
||||
assert slot_of(datetime(2026, 6, 21, 20, 30, tzinfo=KST), summer) == "evening"
|
||||
assert slot_of(datetime(2026, 6, 21, 20, 57, tzinfo=KST), summer) == "night"
|
||||
|
||||
|
||||
def test_arrange_orders_by_slot_and_keeps_same_types_apart():
|
||||
@@ -338,3 +341,29 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
assert rows["거리"].startswith("여기서 약 ") and rows["날씨"] == "비 10% · 체감 21° · 맑음"
|
||||
assert "춘천" in trip["caption"]
|
||||
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
|
||||
|
||||
|
||||
def test_gak_caption_starts_with_score_band_sentence():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _gak_caption
|
||||
d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}])
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1)
|
||||
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요."
|
||||
item.definition.sentences = {}
|
||||
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
|
||||
|
||||
|
||||
def test_uv_post_only_when_moderate_or_higher():
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import FeedService
|
||||
at = lambda h: datetime(2026, 10, 7, h, tzinfo=KST) # noqa: E731
|
||||
base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9))
|
||||
ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731
|
||||
post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)]))
|
||||
assert post.title == "자외선 높음" and post.caption == "가장 셀 때 낮 12시 · 6" and post.slides[0].rows[-1].label == "이렇게 해요"
|
||||
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
||||
assert FeedService._uv_post(None, base, ctx([])) is None
|
||||
@@ -0,0 +1,47 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from common.enums import AirGrade
|
||||
from common.utils.kma_time import KST
|
||||
from services.hero_stats import HeroInput, hero_stats
|
||||
|
||||
NOW = datetime(2026, 10, 7, 14, 20, tzinfo=KST)
|
||||
|
||||
|
||||
def _view(x: HeroInput) -> list[tuple[str, str, str, str]]:
|
||||
return [(s.icon, s.label, s.value, s.tone) for s in hero_stats(x)]
|
||||
|
||||
|
||||
def test_clear_day_shows_uv_warning_and_temp_swing():
|
||||
x = HeroInput(now=NOW, night=False, air=AirGrade.GOOD, uv=6.1, temp_min=13, temp_max=23, temp=23, feels=23, discomfort=68)
|
||||
assert _view(x) == [("glasses", "자외선", "6 · 높음", "warn"), ("coldwind", "일교차 10°", "아침엔 겉옷", "normal")]
|
||||
|
||||
|
||||
def test_rain_comes_first():
|
||||
x = HeroInput(now=NOW, night=False, rain_at=NOW + timedelta(minutes=40), air=AirGrade.GOOD, uv=1.0)
|
||||
assert _view(x) == [("umbrella", "지금 비", "오후 3시쯤 와요", "rain")]
|
||||
|
||||
|
||||
def test_rain_later_today_and_no_rain_today():
|
||||
later = HeroInput(now=NOW, night=False, rain_later_at=NOW.replace(hour=18), today_known=True, air=AirGrade.GOOD, uv=1.0)
|
||||
assert _view(later) == [("umbrella", "오늘 비", "오후 6시쯤 와요", "rain")]
|
||||
dry = HeroInput(now=NOW, night=False, today_known=True, air=AirGrade.GOOD, uv=1.0)
|
||||
assert _view(dry) == [("sun", "오늘 비", "안 와요", "normal")]
|
||||
|
||||
|
||||
def test_bad_air_beats_uv_and_wears_mask():
|
||||
x = HeroInput(now=NOW, night=False, air=AirGrade.VERY_BAD, uv=7.2)
|
||||
assert _view(x) == [("mask", "미세먼지", "매우나쁨", "warn"), ("glasses", "자외선", "7 · 높음", "warn")]
|
||||
|
||||
|
||||
def test_summer_night_muggy_then_moon_and_no_card_for_no_rain():
|
||||
x = HeroInput(now=NOW.replace(hour=21), night=True, uv=0.0, temp=28, feels=31, discomfort=80, moon="보름달")
|
||||
assert _view(x) == [("muggy", "불쾌지수", "80 · 매우 높음", "warn"), ("moon", "오늘 밤 달", "보름달", "normal")]
|
||||
|
||||
|
||||
def test_one_coldwind_card_only():
|
||||
x = HeroInput(now=NOW, night=False, temp_min=5, temp_max=17, temp=10, feels=6, uv=2.0)
|
||||
assert [s.icon for s in hero_stats(x)] == ["coldwind"] # 낮은 자외선으로 빈 칸을 채우지 않는다
|
||||
|
||||
|
||||
def test_nothing_known_gives_nothing():
|
||||
assert hero_stats(HeroInput(now=NOW, night=False)) == []
|
||||
@@ -0,0 +1,93 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
from services.external import image_proxy
|
||||
from services.external.image_proxy import ImageFetchFailed, allowed, fetch_image
|
||||
|
||||
OK_URL = "https://tong.visitkorea.or.kr/cms/resource/01/test_image.jpg"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url,ok", [
|
||||
(OK_URL, True),
|
||||
("https://www.culture.go.kr/upload/test.jpg", True),
|
||||
("http://tong.visitkorea.or.kr/cms/a.jpg", False),
|
||||
("https://evil.example.com/a.jpg", False),
|
||||
("https://tong.visitkorea.or.kr.evil.example.com/a.jpg", False),
|
||||
("https://tong.visitkorea.or.kr:8443/a.jpg", False),
|
||||
("https://user:pw@tong.visitkorea.or.kr/a.jpg", False),
|
||||
("https://169.254.169.254/latest/meta-data", False),
|
||||
("not a url", False),
|
||||
])
|
||||
def test_allowed(url, ok):
|
||||
assert allowed(url) is ok
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_image_returns_bytes_and_type():
|
||||
async with _client(lambda r: httpx.Response(200, content=b"\xff\xd8jpeg", headers={"content-type": "image/jpeg; charset=binary"})) as c:
|
||||
assert await fetch_image(c, OK_URL) == (b"\xff\xd8jpeg", "image/jpeg")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("res", [
|
||||
httpx.Response(302, headers={"location": "https://evil.example.com/a.jpg"}),
|
||||
httpx.Response(404),
|
||||
httpx.Response(200, content=b"<html>", headers={"content-type": "text/html"}),
|
||||
httpx.Response(200, content=b"<svg/>", headers={"content-type": "image/svg+xml"}),
|
||||
])
|
||||
async def test_fetch_image_rejects_redirect_error_and_non_image(res):
|
||||
async with _client(lambda r: res) as c:
|
||||
with pytest.raises(ImageFetchFailed):
|
||||
await fetch_image(c, OK_URL)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_image_rejects_too_large(monkeypatch):
|
||||
monkeypatch.setattr(image_proxy, "MAX_BYTES", 10)
|
||||
async with _client(lambda r: httpx.Response(200, content=b"x" * 11, headers={"content-type": "image/png"})) as c:
|
||||
with pytest.raises(ImageFetchFailed):
|
||||
await fetch_image(c, OK_URL)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_image_api_blocks_other_hosts():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
res = await c.get("/v1/image", params={"url": "https://evil.example.com/a.jpg"})
|
||||
assert res.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_image_api_serves_image_with_cache(monkeypatch):
|
||||
async def fake(_client, url):
|
||||
assert url == OK_URL
|
||||
return b"png-bytes", "image/png"
|
||||
monkeypatch.setattr("router.v1.image.image.fetch_image", fake)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
res = await c.get("/v1/image", params={"url": OK_URL})
|
||||
assert res.status_code == 200
|
||||
assert res.content == b"png-bytes"
|
||||
assert res.headers["content-type"] == "image/png"
|
||||
assert "max-age=86400" in res.headers["cache-control"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_image_api_reports_upstream_failure(monkeypatch):
|
||||
async def fail(_client, _url):
|
||||
raise ImageFetchFailed("status 404")
|
||||
monkeypatch.setattr("router.v1.image.image.fetch_image", fail)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
res = await c.get("/v1/image", params={"url": OK_URL})
|
||||
assert res.status_code == 502
|
||||
|
||||
|
||||
def test_allowed_follows_settings(monkeypatch):
|
||||
from config.settings import settings
|
||||
monkeypatch.setattr(settings, "image_proxy_hosts", " cdn.example.org , ")
|
||||
assert allowed("https://cdn.example.org/a.jpg") is True
|
||||
assert allowed(OK_URL) is False
|
||||
@@ -157,7 +157,7 @@ def test_gust_and_ground_temperature_zero_rules():
|
||||
def test_estimate_and_labels_cover_openmeteo_axes():
|
||||
r = estimate(_uv_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.factors["uv"] == 70 and r.factors["sun"] == 0 and r.factors["view"] == 0
|
||||
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선", "햇빛", "가시거리"]
|
||||
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선 약함", "햇빛", "가시거리"]
|
||||
|
||||
|
||||
def _fc(lo=15.0, hi=23.0, am=0, pm=0, sky=Sky.CLEAR):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
@@ -5,8 +6,10 @@ from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.weather_service as weather_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from common.utils.kma_time import kst_midnight, latest_vilage_base, now_kst
|
||||
from services.external.kma import day_start_base
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
@@ -32,6 +35,7 @@ async def clean_region():
|
||||
lambda s: s.execute(text(f"DELETE FROM weather_daily WHERE region_code='{REGION}'")),
|
||||
lambda s: s.execute(text(f"DELETE FROM sun_time WHERE region_code='{REGION}'")),
|
||||
])
|
||||
await REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
||||
await wipe()
|
||||
yield
|
||||
await wipe()
|
||||
@@ -106,3 +110,34 @@ def test_slot_view_shows_sunset_only_when_clear():
|
||||
assert _slot_view(at, row(Sky.CLEAR), sun)[0::2] == ("sunset", "노을")
|
||||
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
||||
assert _slot_view(at, row(Sky.PARTLY), sun)[0::2] == ("cloud", "구름 많음")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_refetches_midnight_when_first_fetch_missed_it(monkeypatch, clean_region):
|
||||
"""전날 23시 발표 받기가 실패해 0시~ 칸이 비면, 다음 요청 때 그 발표를 다시 받아 채운다."""
|
||||
midnight_base = day_start_base(now_kst().date())
|
||||
if latest_vilage_base(now_kst()) == midnight_base:
|
||||
pytest.skip("최신 발표가 전날 23시면 두 발표가 같다")
|
||||
calls = []
|
||||
fail_midnight = True
|
||||
|
||||
async def fake_fetch(client, nx, ny, base):
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
calls.append(base)
|
||||
if base == midnight_base and fail_midnight:
|
||||
raise DataGoKrRequestFailed("timeout")
|
||||
return [it for it in _fake_items(base) if base == midnight_base or it["fcstDate"] + it["fcstTime"] > base.strftime("%Y%m%d%H%M")]
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
first = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||
assert first["slots"][0].get("temp_c") is None
|
||||
fail_midnight = False
|
||||
await REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
||||
await client.get("/v1/weather/today", params={"region": REGION})
|
||||
await asyncio.gather(*weather_service._background)
|
||||
body = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||
|
||||
assert calls.count(midnight_base) == 2
|
||||
assert body["slots"][0]["temp_c"] == 18
|
||||
@@ -1,6 +1,7 @@
|
||||
from datetime import date, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import EventKind
|
||||
from common.utils.kma_time import KST
|
||||
from services.week_service import DayPlan, EventItem
|
||||
from services.weekend_plan import day_plan, forecast, pick_events
|
||||
@@ -14,8 +15,8 @@ def _day(d: date, lo=12.0, hi=26.0, rainy=False, rain_hours=None, prob=10) -> Da
|
||||
headline="", summary="", pick="", rain_hours=rain_hours, is_rainy=rainy, rain_prob=prob)
|
||||
|
||||
|
||||
def _event(name, start, end, dist, image="https://img/x.jpg") -> EventItem:
|
||||
e = SimpleNamespace(event_id=hash(name), name=name, icon="fireworks", start_date=start, end_date=end, place_name="경기도 고양시 일산동구 호수로 595", image_url=image, source_id="1")
|
||||
def _event(name, start, end, dist, image="https://img/x.jpg", kind=EventKind.FESTIVAL) -> EventItem:
|
||||
e = SimpleNamespace(event_id=hash(name), name=name, kind=kind, icon="fireworks", start_date=start, end_date=end, place_name="경기도 고양시 일산동구 호수로 595", image_url=image, source_id="1")
|
||||
return EventItem(event=e, status="live", status_label="진행 중", fit=None, distance_km=dist)
|
||||
|
||||
|
||||
@@ -64,6 +65,14 @@ def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
assert pick_events(SUN, [near, far], frozenset(e.event.event_id for e in sat)) == []
|
||||
|
||||
|
||||
def test_festival_and_concert_come_before_nearer_galleries():
|
||||
events = [_event("옆 전시1", SAT, SUN, 0.5, kind=EventKind.EXHIBITION), _event("옆 전시2", SAT, SUN, 0.6, kind=EventKind.EXHIBITION),
|
||||
_event("먼 공연", SAT, SAT, 20.0, kind=EventKind.CONCERT), _event("먼 축제", SAT, SUN, 25.0)]
|
||||
assert [e.event.name for e in pick_events(SAT, events)] == ["먼 축제", "먼 공연"]
|
||||
only_galleries = events[:2]
|
||||
assert [e.event.name for e in pick_events(SAT, only_galleries)] == ["옆 전시1", "옆 전시2"]
|
||||
|
||||
|
||||
def test_cloudy_weekend_is_not_called_clear():
|
||||
cloudy = [_day(SAT), _day(SUN)]
|
||||
for d in cloudy:
|
||||
|
||||
Reference in new issue
Block a user