diff --git a/.env.example b/.env.example index 8c89672..9b0197e 100644 --- a/.env.example +++ b/.env.example @@ -5,6 +5,7 @@ DATA_GO_KR_SERVICE_KEY= # 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다. TEAMS_WEBHOOK_URL= +IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr # ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다) DB_HOST=localhost @@ -29,3 +30,5 @@ PG_BIND= REDIS_BIND= # 프론트가 부를 API 주소. 비우면 같은 주소의 /v1 (nginx 가 backend 로 넘김) VITE_API_BASE_URL= +# 공유·링크 미리보기(og:image)에 나가는 우리 주소. 비우면 https://weather.o2o.kr +VITE_SITE_URL= diff --git a/TODO.md b/TODO.md index 4ea5bf6..b90f8b6 100644 --- a/TODO.md +++ b/TODO.md @@ -93,8 +93,14 @@ | [ ] | 팝가에 공연·축제도 있음(`PERFORMANCE`·`FESTIVAL`) — 지금은 팝업(`STORE`)만 받음. 다른 출처와 겹침 처리 정하면 추가 | 팝업 수집 | `backend/services/external/popga.py` | | [x] | 문화정보원 API 가 `23 LIMITED_NUMBER_OF_SERVICE_REQUESTS_PER_SECOND_EXCEEDS_ERROR` 를 냄 — 쪽 사이 1초, 시도 사이 1초 간격을 둬 17개 시도 수집에서 오류 없음 | 콘서트 수집 점검 중 발견 | `backend/services/external/culture_api.py` | | [x] | `event.kind` 칸 추가(1=축제 2=전시 3=콘서트 4=팝업). 행사 종류(축제·전시·콘서트·팝업)를 구분하는 칸이 없음 — 지금은 `source_id` 접두어로만 구분하고 전시·콘서트는 둘 다 `kcis:` 라 섞임 | 콘서트 수집 | `backend/postgres-init/init.sql` (`event`) | -| [ ] | 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) | +| [x] | 히어로 두 칸을 상황별로 고름(비→미세먼지→자외선→일교차→체감→불쾌지수, 모자라면 기본값), 아이콘·색도 상태별 (시안 A, 사용자 결정). 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) | | [ ] | 검색 노출(SEO·AEO) 대응 빌드 방식 정하기 — 지금은 브라우저에서만 그리는 React(Vite)라 검색엔진·AI가 내용을 못 읽음. SSR 말고도 미리 그려 두는 방식(정적 사전 렌더링), 일부 페이지만 서버에서 그리기 등을 비교해 추천안 내기 | 지시 사항 (SEO·AEO 필요) | `frontend/vite.config.ts`, `frontend/nginx.conf` | | [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` | | [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` | | [ ] | 노을 하늘 상황 판정이 실제와 맞는지 확인할 방법 정하기 — 기준값(중·높은 구름 25~75% 등)은 추정값. 사진 기록·사용자 반응 등 후보 | 노을 탭 다시 기획 (10/7) | `backend/services/calc/sky_score.py` (`situation`) | +| [x] | 공유 이미지: 행사 카드의 장소(지도 링크)가 빠짐 — 버튼과 함께 ``도 빼서 생김. 링크는 남기고 버튼만 빼야 함 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`keep`), `frontend/src/b/ui.tsx` (지도 링크) | +| [x] | 공유 이미지: 행사 사진은 백엔드 `/v1/image`(허용 호스트만)로 대신 받음 (사용자 결정). 행사 사진(한국관광공사·문화정보원)이 CORS 차단으로 하얗게 빠짐. 안: 백엔드가 사진을 대신 받아 주기 / 공유 때만 사진 대신 아이콘 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `backend` 이미지 응답 | +| [x] | 공유 이미지: 2장 카드는 한 이미지에 엇갈려 묶음 (사용자 결정). 여러 장 카드는 보고 있는 1장만 나감(주말 예보는 2번째 장 내용이 빠짐). 1장만 / 장마다 이미지 여러 장 / 2장을 한 이미지에 중 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts`, `frontend/src/b/Post.tsx` (`share`) | +| [x] | 공유 이미지: 카드 아래 긴 제목이 한 줄 폭에 눌려 찌그러짐 — 두 줄 나눔 또는 말줄임 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` (`fillText`) | +| [x] | 공유 이미지: 카드 아래 제목을 빼고 주소 알약으로 바꿈 (시안 A, 사용자 결정). 카드 안 제목과 카드 아래 제목이 같아 두 번 보임. 아래 줄을 뺄지, 다른 말(지역·날짜)로 바꿀지 정하기 | 공유 이미지 점검 (10/7) | `frontend/src/b/storyImage.ts` | +| [ ] | 노치(아이폰 상단 카메라 영역) 대응 — 화면 위·아래가 노치·홈 막대에 가리지 않게 safe-area 여백 점검 | 사용자 요청 | `frontend/index.html`, `frontend/src/b/BLayout.tsx` | diff --git a/backend/common/enums.py b/backend/common/enums.py index b2f0426..19d43ec 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -135,6 +135,7 @@ class PostType(CodeEnum): AIR = 12 DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사 MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기) + UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만) class EventKind(CodeEnum): diff --git a/backend/config/settings.py b/backend/config/settings.py index eb717d4..3b0ac98 100644 --- a/backend/config/settings.py +++ b/backend/config/settings.py @@ -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}" diff --git a/backend/crud/weather_crud.py b/backend/crud/weather_crud.py index 541e6f0..f44b2aa 100644 --- a/backend/crud/weather_crud.py +++ b/backend/crud/weather_crud.py @@ -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) diff --git a/backend/router/router.py b/backend/router/router.py index 6598437..28316de 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -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): diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index 5ab6b0f..a59c76d 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -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): diff --git a/backend/router/v1/image/__init__.py b/backend/router/v1/image/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/image/image.py b/backend/router/v1/image/image.py new file mode 100644 index 0000000..c93cdcf --- /dev/null +++ b/backend/router/v1/image/image.py @@ -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"}) diff --git a/backend/scripts/gen_gak_doc.py b/backend/scripts/gen_gak_doc.py index a2e84b0..4328f7f 100644 --- a/backend/scripts/gen_gak_doc.py +++ b/backend/scripts/gen_gak_doc.py @@ -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"]] diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 1ca37d8..f64710c 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -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: diff --git a/backend/services/external/image_proxy.py b/backend/services/external/image_proxy.py new file mode 100644 index 0000000..f3ebb72 --- /dev/null +++ b/backend/services/external/image_proxy.py @@ -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 diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index a48a432..c7ff345 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -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시간 칸 자외선 diff --git a/backend/services/hero_stats.py b/backend/services/hero_stats.py new file mode 100644 index 0000000..02b501c --- /dev/null +++ b/backend/services/hero_stats.py @@ -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 diff --git a/backend/services/weather_service.py b/backend/services/weather_service.py index 6d90d56..045d073 100644 --- a/backend/services/weather_service.py +++ b/backend/services/weather_service.py @@ -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: diff --git a/backend/services/weekend_plan.py b/backend/services/weekend_plan.py index fb3a25c..f3a5835 100644 --- a/backend/services/weekend_plan.py +++ b/backend/services/weekend_plan.py @@ -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: diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py index a98db4d..ff47a6f 100644 --- a/backend/tests/test_feed.py +++ b/backend/tests/test_feed.py @@ -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 diff --git a/backend/tests/test_hero_stats.py b/backend/tests/test_hero_stats.py new file mode 100644 index 0000000..d7b0cc0 --- /dev/null +++ b/backend/tests/test_hero_stats.py @@ -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)) == [] diff --git a/backend/tests/test_image_proxy.py b/backend/tests/test_image_proxy.py new file mode 100644 index 0000000..6d61f55 --- /dev/null +++ b/backend/tests/test_image_proxy.py @@ -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"", headers={"content-type": "text/html"}), + httpx.Response(200, content=b"", 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 diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index 0800a43..ae67e4c 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -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): diff --git a/backend/tests/test_weather_today.py b/backend/tests/test_weather_today.py index aa84365..ee64eb9 100644 --- a/backend/tests/test_weather_today.py +++ b/backend/tests/test_weather_today.py @@ -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 diff --git a/backend/tests/test_weekend_plan.py b/backend/tests/test_weekend_plan.py index 562fe8c..682b0d9 100644 --- a/backend/tests/test_weekend_plan.py +++ b/backend/tests/test_weekend_plan.py @@ -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: diff --git a/compose.yaml b/compose.yaml index 6d9d479..67d2d47 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,6 +9,8 @@ services: args: # 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다 VITE_API_BASE_URL: ${VITE_API_BASE_URL:-} + # 공유·링크 미리보기(og:image)에 나가는 우리 주소 + VITE_SITE_URL: ${VITE_SITE_URL:-https://weather.o2o.kr} ports: - "${FRONT_PORT:-8080}:80" restart: unless-stopped @@ -26,6 +28,7 @@ services: - /app/node_modules environment: - CHOKIDAR_USEPOLLING=true + - VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr} # 백엔드 API: http://localhost:9810/docs backend: diff --git a/docs/각_계산기준.md b/docs/각_계산기준.md index 1049d70..6263703 100644 --- a/docs/각_계산기준.md +++ b/docs/각_계산기준.md @@ -16,28 +16,28 @@ | 순서 | 각 | 코드 | 분류 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 | |---:|---|---|---|---|---:|---:|---:|---:|---:|---:|:---:|:---:| | 1 | 야장각 | `yajang` | 먹고 마시기 | 18~24시 | 30% | 25% | 15% | 10% | 10% | 10% | ○ | | -| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 11~16시 | 30% | 25% | 15% | 10% | 10% | 10% | | ○ | +| 2 | 피크닉각 | `picnic` | 밖에서 놀기 | 11~16시 | 25% | 25% | 15% | 5% | 10% | 10% | | ○ | | 3 | 치맥각 | `chimaek` | 먹고 마시기 | 18~23시 | 30% | 20% | 15% | 15% | 10% | 10% | ○ | | | 4 | 산책각 | `walk` | 밖에서 놀기 | 18~22시 | 30% | 25% | 15% | 10% | 15% | 5% | | | | 5 | 환기각 | `vent` | 집안일 | 10~12시 / 12~14시 / 14~16시 / 16~18시 | 10% | 15% | 15% | 10% | 45% | 5% | | | -| 6 | 등산각 | `hiking` | 밖에서 놀기 | 7~12시 | 30% | 25% | 20% | 10% | 10% | 5% | | ○ | +| 6 | 등산각 | `hiking` | 밖에서 놀기 | 7~12시 | 25% | 25% | 20% | 5% | 10% | 5% | | ○ | | 7 | 세차각 | `carwash` | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 5% | 60% | 10% | 10% | 10% | 5% | | | | 8 | 캠핑각 | `camping` | 밖에서 놀기 | 18~다음 날 8시 | 30% | 25% | 15% | 15% | 10% | 5% | | ○ | -| 9 | 러닝각 | `running` | 밖에서 놀기 | 6~8시 / 19~22시 | 35% | 20% | 10% | 20% | 10% | 5% | | | -| 10 | 별보기각 | `stars` | 밖에서 놀기 | 21~다음 날 2시 | 5% | 15% | 5% | 10% | 20% | 45% | | ○ | +| 9 | 러닝각 | `running` | 밖에서 놀기 | 6~8시 / 19~22시 | 35% | 20% | 10% | 15% | 10% | 5% | | | +| 10 | 별보기각 | `stars` | 밖에서 놀기 | 21~다음 날 2시 | 5% | 10% | 5% | 5% | 15% | 45% | | ○ | | 11 | 짬뽕각 | `jjamppong` | 먹고 마시기 | 11~14시 / 17~20시 | 40% | 25% | 15% | 10% | 5% | 5% | ○ | | | 12 | 막걸리각 | `makgeolli` | 먹고 마시기 | 17~22시 | 15% | 50% | 10% | 15% | 5% | 5% | ○ | | | 13 | 뜨아각 | `iced_hot` | 먹고 마시기 | 7~10시 | 50% | 10% | 15% | 10% | 5% | 10% | ○ | | -| 14 | 빨래각 | `laundry` | 집안일 | 9~16시 | 20% | 35% | 20% | 20% | 0% | 5% | | | -| 15 | 자전거각 | `bike` | 밖에서 놀기 | 9~19시 | 25% | 25% | 30% | 5% | 10% | 5% | | | -| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 7~9시 / 17~20시 | 40% | 25% | 10% | 5% | 15% | 5% | | | +| 14 | 빨래각 | `laundry` | 집안일 | 9~16시 | 15% | 30% | 15% | 10% | 0% | 5% | | | +| 15 | 자전거각 | `bike` | 밖에서 놀기 | 9~19시 | 25% | 25% | 25% | 5% | 10% | 5% | | | +| 16 | 멍뭉산책각 | `dog` | 밖에서 놀기 | 7~9시 / 17~20시 | 35% | 25% | 10% | 5% | 15% | 5% | | | | 17 | 김서림각 | `glasses` | 생활 고민 | 7~9시 | 50% | 10% | 5% | 30% | 0% | 5% | | | | 18 | 화장붕괴각 | `makeup` | 생활 고민 | 10~18시 | 40% | 10% | 10% | 35% | 0% | 5% | | | | 19 | 냉면각 | `naengmyeon` | 먹고 마시기 | 11~14시 | 55% | 15% | 5% | 15% | 5% | 5% | ○ | | | 20 | 택시대란각 | `taxi` | 생활 고민 | 22~다음 날 2시 | 15% | 55% | 10% | 5% | 0% | 15% | | | | 21 | 배달폭주각 | `delivery` | 생활 고민 | 17~21시 | 20% | 50% | 10% | 5% | 5% | 10% | | | -| 22 | 가드닝각 | `garden` | 집안일 | 7~10시 | 30% | 30% | 10% | 15% | 10% | 5% | | | -| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 일몰 앞뒤 1시간 | 15% | 25% | 10% | 5% | 15% | 30% | | | +| 22 | 가드닝각 | `garden` | 집안일 | 7~10시 | 25% | 30% | 10% | 15% | 10% | 5% | | | +| 23 | 사진산책각 | `photo` | 밖에서 놀기 | 일몰 앞뒤 1시간 | 10% | 25% | 10% | 5% | 10% | 30% | | | | 24 | 야구각 | `baseball` | 밖에서 놀기 | 18~22시 | 25% | 40% | 10% | 5% | 10% | 10% | ○ | | | 25 | 공부각 | `study` | 집안일 | 13~18시 | 35% | 35% | 10% | 5% | 5% | 10% | ○ | | | 26 | 넷플릭스각 | `netflix` | 집안일 | 20~24시 | 30% | 35% | 15% | 5% | 0% | 15% | ○ | | @@ -71,11 +71,12 @@ - 분류: 밖에서 놀기 · 아이콘 `picnic` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음 - 시간대: 11~16시 - 요소별 규칙 (비중): - - 기온 30%: 체감 20~26°가 좋음 + - 기온 25%: 체감 20~26°가 좋음 - 비 25%: 비 안 올수록 좋음 - 바람 15%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 9m면 0점) - - 습도 10%: 30~60%가 좋음 (최적 35%) + - 습도 5%: 30~60%가 좋음 (최적 35%) - 미세먼지 10%: 초미세먼지 낮을수록 좋음 + - 자외선 10%: 자외선 2 이하면 만점, 8 이상이면 0점 (Open-Meteo) - 시간·요일 10%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 60 - 점수 깎이는 조건: 비 확률 60% 이상이면 0점 - 반영 못 하는 것: 잔디 상태, 공원 혼잡도는 반영하지 못해요 @@ -151,11 +152,13 @@ - 분류: 밖에서 놀기 · 아이콘 `hiking` · 재미 각 아니오 · 계절 핵심 예 · 계산 근거 화면 있음 - 시간대: 7~12시 - 요소별 규칙 (비중): - - 기온 30%: 체감 10~20°가 좋음, 산 정상 보정 -6° + - 기온 25%: 체감 10~20°가 좋음, 산 정상 보정 -6° - 비 25%: 비 안 올수록 좋음 - 바람 20%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 12m면 0점) - - 습도 10%: 30~60%가 좋음 (최적 35%) + - 습도 5%: 30~60%가 좋음 (최적 35%) - 미세먼지 10%: 초미세먼지 낮을수록 좋음 + - 자외선 5%: 자외선 2 이하면 만점, 8 이상이면 0점 (Open-Meteo) + - 가시거리 5%: 20km 이상이면 만점, 5km 이하면 0점 (Open-Meteo) - 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 50 - 점수 깎이는 조건: 비 확률 70% 이상이면 0점, wind 특보가 있으면 - 반영 못 하는 것: 등산로 통제, 낙석 정보는 산림청 안내를 확인하세요 @@ -197,7 +200,7 @@ - 습도 15%: 낮을수록 좋음 (90%=0점 → 40%=100점) - 미세먼지 10%: 초미세먼지 낮을수록 좋음 - 시간·요일 5%: 요일별 점수: 금 100, 토 100, 그 외 60 -- 점수 깎이는 조건: 비 확률 60% 이상이면 0점, 바람 14m/s 이상이면 0점 +- 점수 깎이는 조건: 비 확률 60% 이상이면 0점, 바람 14m/s 이상이면 0점, 돌풍 15m/s 이상이면 0점 - 반영 못 하는 것: 캠핑장 예약 상황은 반영하지 못해요 - 점수 구간별 설명 (상세 창에 나옴): - 0~29점: 비가 오거나 바람이 너무 세요. 텐트 날아가요! @@ -214,8 +217,9 @@ - 기온 35%: 체감 8~18°가 좋음 - 비 20%: 비 안 올수록 좋음 - 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점) - - 습도 20%: 낮을수록 좋음 (90%=0점 → 40%=100점) + - 습도 15%: 낮을수록 좋음 (90%=0점 → 40%=100점) - 미세먼지 10%: 초미세먼지 낮을수록 좋음 + - 자외선 5%: 자외선 2 이하면 만점, 8 이상이면 0점 (Open-Meteo) - 시간·요일 5%: 고정 100점 - 점수 깎이는 조건: 체감 35° 이상이면 0점, 비 확률 90% 이상이면 0점 - 반영 못 하는 것: 노면 상태는 반영하지 못해요 @@ -232,10 +236,11 @@ - 시간대: 21~다음 날 2시 - 요소별 규칙 (비중): - 기온 5%: 체감 5~25°가 좋음 - - 비 15%: 비 안 올수록 좋음 + - 비 10%: 비 안 올수록 좋음 - 바람 5%: 잔잔할수록 좋음 (초속 5m까지 괜찮음, 12m면 0점) - - 습도 10%: 낮을수록 좋음 (90%=0점 → 40%=100점) - - 미세먼지 20%: 초미세먼지 낮을수록 좋음 + - 습도 5%: 낮을수록 좋음 (90%=0점 → 40%=100점) + - 미세먼지 15%: 초미세먼지 낮을수록 좋음 + - 가시거리 15%: 20km 이상이면 만점, 5km 이하면 0점 (Open-Meteo) - 시간·요일 45%: 달이 어두울수록 좋음 (보름 20점 → 그믐 100점) - 점수 깎이는 조건: 흐린 시간 비율 80% 이상이면 0점 - 반영 못 하는 것: 도시 불빛은 지역 평균으로만 반영해요 @@ -311,14 +316,15 @@ - 분류: 집안일 · 아이콘 `laundry` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음 - 시간대: 9~16시 - 요소별 규칙 (비중): - - 기온 20%: 더울수록 좋음 (10°=0점 → 25°=100점) - - 비 35%: 비 안 올수록 좋음 - - 바람 20%: 적당한 바람(초속 2~5m)이 좋음 - - 습도 20%: 낮을수록 좋음 (90%=0점 → 40%=100점) + - 기온 15%: 더울수록 좋음 (10°=0점 → 25°=100점) + - 비 30%: 비 안 올수록 좋음 + - 바람 15%: 적당한 바람(초속 2~5m)이 좋음 + - 습도 10%: 낮을수록 좋음 (90%=0점 → 40%=100점) - 미세먼지 0%: 초미세먼지 낮을수록 좋음 + - 햇빛 25%: 해 난 비율 80% 이상이면 만점, 20% 이하면 0점 (Open-Meteo) - 시간·요일 5%: 고정 100점 - 점수 깎이는 조건: 비 확률 60% 이상이면 0점 -- 반영 못 하는 것: 집 일조량은 반영하지 못해요 +- 반영 못 하는 것: 집 방향·그늘 일조량은 반영하지 못해요 - 점수 구간별 설명 (상세 창에 나옴): - 0~29점: 비 소식이 있어요. 오늘 빨래는 실내 건조로! - 30~59점: 눅눅하거나 쌀쌀해서 잘 안 말라요. 얇은 것만 널어요. @@ -333,11 +339,12 @@ - 요소별 규칙 (비중): - 기온 25%: 체감 15~24°가 좋음 - 비 25%: 비 안 올수록 좋음 - - 바람 30%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 8m면 0점) + - 바람 25%: 잔잔할수록 좋음 (초속 3m까지 괜찮음, 8m면 0점) - 습도 5%: 30~60%가 좋음 (최적 35%) - 미세먼지 10%: 초미세먼지 낮을수록 좋음 + - 자외선 5%: 자외선 2 이하면 만점, 8 이상이면 0점 (Open-Meteo) - 시간·요일 5%: 요일별 점수: 토 100, 일 100, 공휴일 100, 그 외 70 -- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 10m/s 이상이면 0점 +- 점수 깎이는 조건: 비 확률 70% 이상이면 0점, 바람 10m/s 이상이면 0점, 돌풍 15m/s 이상이면 0점 - 반영 못 하는 것: 자전거 도로 공사는 반영하지 못해요 - 점수 구간별 설명 (상세 창에 나옴): - 0~29점: 비가 오거나 바람이 10m/s 넘어요. 자전거는 쉬어요! @@ -351,14 +358,15 @@ - 분류: 밖에서 놀기 · 아이콘 `dog` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음 - 시간대: 7~9시 / 17~20시 - 요소별 규칙 (비중): - - 기온 40%: 체감 5~22°가 좋음 + - 기온 35%: 체감 5~22°가 좋음 - 비 25%: 비 안 올수록 좋음 - 바람 10%: 잔잔할수록 좋음 (초속 5m까지 괜찮음, 12m면 0점) - 습도 5%: 30~60%가 좋음 (최적 35%) - 미세먼지 15%: 초미세먼지 낮을수록 좋음 + - 자외선 5%: 자외선 2 이하면 만점, 8 이상이면 0점 (Open-Meteo) - 시간·요일 5%: 고정 100점 -- 점수 깎이는 조건: 체감 33° 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점 -- 반영 못 하는 것: 노면 온도는 실측하지 못해요 +- 점수 깎이는 조건: 체감 33° 이상이면 0점, 초미세먼지 75㎍/㎥ 이상이면 0점, 지면 온도 45° 이상이면 0점 +- 반영 못 하는 것: 지표면 온도는 예보 모델 값이라 실제 노면 온도와 달라요 - 점수 구간별 설명 (상세 창에 나옴): - 0~29점: 체감 33° 넘거나 초미세먼지가 매우 나빠요. 발바닥도 폐도 위험, 실내 놀이로! - 30~59점: 덥거나 공기가 탁해요. 짧게 볼일만 보고 들어와요. @@ -471,11 +479,12 @@ - 분류: 집안일 · 아이콘 `garden` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음 - 시간대: 7~10시 - 요소별 규칙 (비중): - - 기온 30%: 체감 12~25°가 좋음 + - 기온 25%: 체감 12~25°가 좋음 - 비 30%: 비 안 올수록 좋음 - 바람 10%: 잔잔할수록 좋음 (초속 4m까지 괜찮음, 10m면 0점) - 습도 15%: 30~60%가 좋음 (최적 35%) - 미세먼지 10%: 초미세먼지 낮을수록 좋음 + - 자외선 5%: 자외선 2 이하면 만점, 8 이상이면 0점 (Open-Meteo) - 시간·요일 5%: 고정 100점 - 점수 깎이는 조건: 비 확률 70% 이상이면 0점 - 반영 못 하는 것: 식물 종류는 반영하지 못해요 @@ -491,11 +500,12 @@ - 분류: 밖에서 놀기 · 아이콘 `photo` · 재미 각 아니오 · 계절 핵심 아니오 · 계산 근거 화면 있음 - 시간대: 일몰 앞뒤 1시간 - 요소별 규칙 (비중): - - 기온 15%: 체감 10~26°가 좋음 + - 기온 10%: 체감 10~26°가 좋음 - 비 25%: 비 안 올수록 좋음 - 바람 10%: 잔잔할수록 좋음 (초속 5m까지 괜찮음, 12m면 0점) - 습도 5%: 30~60%가 좋음 (최적 35%) - - 미세먼지 15%: 초미세먼지 낮을수록 좋음 + - 미세먼지 10%: 초미세먼지 낮을수록 좋음 + - 가시거리 10%: 20km 이상이면 만점, 5km 이하면 0점 (Open-Meteo) - 시간·요일 30%: 그날 노을 점수를 그대로 씀 - 점수 깎이는 조건: 비 확률 80% 이상이면 0점 - 반영 못 하는 것: 장소 혼잡도는 반영하지 못해요 diff --git a/docs/피드_기획.html b/docs/피드_기획.html index e4c3dd1..4c6816c 100644 --- a/docs/피드_기획.html +++ b/docs/피드_기획.html @@ -140,7 +140,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei

주말 플랜

계획 · 날마다 1장매일
-
켜지는 때
이번 주말 토·일 각각 독립 카드(포스트는 최대한 나눈다, 10/6). 그날 시간대별 동선: 아침 기온(일교차 크면 겉옷) → 12~16시 바깥 골든타임(비 오는 시간이 있으면 그 시간은 실내, 앞뒤로 바깥) → 그날 열리는 행사 최대 2곳(사진·장소) → 토요일은 일몰 시각에 노을, 일요일은 월요일 아침 기온과 함께 일찍 귀가. 행사는 가까운 순, 일요일은 그날 끝나는 행사 먼저("마지막 날 찬스"). 토요일에 고른 행사는 일요일에 다시 안 나옵니다.
+
켜지는 때
이번 주말 토·일 각각 독립 카드(포스트는 최대한 나눈다, 10/6). 그날 시간대별 동선: 아침 기온(일교차 크면 겉옷) → 12~16시 바깥 골든타임(비 오는 시간이 있으면 그 시간은 실내, 앞뒤로 바깥) → 그날 열리는 행사 최대 2곳(사진·장소) → 토요일은 일몰 시각에 노을, 일요일은 월요일 아침 기온과 함께 일찍 귀가. 행사는 축제→공연→팝업→전시 순으로 종류마다 하나씩, 같은 종류 안에서는 가까운 순이고 일요일은 그날 끝나는 행사 먼저("마지막 날 찬스"). 가깝다고 전시만 이어지지 않게 합니다(10/7). 토요일에 고른 행사는 일요일에 다시 안 나옵니다.
① 유저
"주말에 뭐 하지"에 시간표째로 답을 얻습니다.
② 운영
날마다 내용이 달라 주말 직전까지 볼 이유가 생기고, "토요일 이렇게 놀자" 공유 카드가 됩니다.
@@ -184,8 +184,8 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei 카드 아침05–11시 낮11시–일몰 2시간 전 - 저녁일몰 2시간 전–21시 - 밤21–05시 + 저녁일몰 2시간 전–일몰 1시간 뒤 + 밤일몰 1시간 뒤–05시 지금 날씨히어로고정고정고정고정밤에는 내일 아침 기온을 함께 @@ -211,7 +211,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
2

같은 종류 카드는 붙이지 않습니다(확정). 각 3장 사이에는 다른 카드가 하나씩 끼어듭니다.

3

조건이 안 맞는 카드는 아예 빼고, 빈 카드나 "오늘은 없어요" 카드는 만들지 않습니다.예외: 노을은 흐린 날에도 한 줄로 남깁니다(확정).

4

좋아요·댓글은 카드에 붙고, 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.

-
5

시간대가 바뀌는 순간(05·11·16·21시)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.

+
5

시간대가 바뀌는 순간(05·11시, 일몰 2시간 전·일몰 1시간 뒤)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.

6

카드마다 보낼 문구가 있고, 보내면 카드 그대로 이미지+링크로 갑니다(확정).

7

UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/2).

8

지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/2, 256곳).

diff --git a/docs/피드_동작방식.md b/docs/피드_동작방식.md index d168ad3..ce3b5cf 100644 --- a/docs/피드_동작방식.md +++ b/docs/피드_동작방식.md @@ -73,8 +73,8 @@ |---|---|---| | 아침 | 05:00~11:00 | 05:00~11:00 | | 낮 | 11:00~일몰 2시간 전 | 11:00~16:05 | -| 저녁 | 일몰 2시간 전~21:00 | 16:05~21:00 | -| 밤 | 21:00~다음 날 05:00 | 21:00~05:00 | +| 저녁 | 일몰 2시간 전~일몰 1시간 뒤 | 16:05~19:05 | +| 밤 | 일몰 1시간 뒤~다음 날 05:00 (계절 따라 18시대~21시대 시작) | 19:05~05:00 | 시간대가 바뀌면 캐시 키(`feed:{구}:{시간대}`)가 달라져서 그 순간 새 순서로 다시 만들어진다. @@ -84,10 +84,10 @@ |---|---| | 아침 | 특보 → 미세먼지 → 각 1·2·3 → 계절 소식 → 노을 → 날씨 상식 → 주말 예보 → 주말 플랜(토) → 주말 플랜(일) → 당일치기 → 달 → 한 문장 | | 낮 | 각 → 특보 → 미세먼지 → 각 → 각 → 노을 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 | -| 저녁 | 노을 → 각 → 특보 → 각 → 각 → 미세먼지 → 내일 미리보기 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 달 → 한 문장 | -| 밤 | 내일 미리보기 → 특보 → 노을 → 주말 예보 → 각 → 주말 플랜 → 각 → 각 → 주말 플랜 → 당일치기 → 미세먼지 → 계절 소식 → 날씨 상식 → 달 → 한 문장 | +| 저녁 | 노을 → 각 → 달 → 특보 → 각 → 각 → 미세먼지 → 내일 미리보기 → 주말 예보 → 주말 플랜 → 계절 소식 → 주말 플랜 → 당일치기 → 날씨 상식 → 한 문장 | +| 밤 | 내일 미리보기 → 달 → 특보 → 노을 → 주말 예보 → 각 → 주말 플랜 → 각 → 각 → 주말 플랜 → 당일치기 → 미세먼지 → 계절 소식 → 날씨 상식 → 한 문장 | -뜻: 아침엔 "나가기 전에 볼 것"(특보·공기·오늘 각), 낮엔 각을 맨 위로, 저녁엔 노을을 맨 위로, 밤엔 내일 준비(내일 미리보기)와 주말 계획을 앞으로. 내일 미리보기는 저녁·밤에만 나온다. +뜻: 아침엔 "나가기 전에 볼 것"(특보·공기·오늘 각), 낮엔 각을 맨 위로, 저녁엔 노을을 맨 위로, 밤엔 내일 준비(내일 미리보기)와 주말 계획을 앞으로. 저녁·밤엔 하늘을 볼 시간이라 달을 위로. 내일 미리보기는 저녁·밤에만 나온다. **기본 순서 위에 덧붙는 규칙** 1. **특보가 있으면** 맨 위(히어로 바로 아래), 그다음 오늘·내일 날씨. 특보가 없으면 날씨가 맨 위. @@ -119,7 +119,7 @@ - 키: `feed:{구 코드}:{시간대}` (예: `feed:4113500000:morning`) - DB에는 완성본을 저장하지 않는다. Redis가 비어도 DB의 틀과 재료로 다시 만든다. - **얼마나 두나**: 다음에 내용이 바뀌는 시각까지, 최대 1시간. - 바뀌는 시각 = 03:00, 05시, 11시, 일몰 2시간 전, 일몰, 21시, 다음 단기예보 제공 시각, 매시 20분(미세먼지) + 바뀌는 시각 = 03:00, 05시, 11시, 일몰 2시간 전, 일몰, 일몰 1시간 뒤, 다음 단기예보 제공 시각, 매시 20분(미세먼지) - **재료 중 하나라도 못 가져왔으면 60초**만 둔다. 다음 요청이 다시 채우게 하려고. ### 언제 새로 만들어지나 diff --git a/frontend/Dockerfile b/frontend/Dockerfile index d08c117..72f8135 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -16,6 +16,8 @@ CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"] FROM deps AS build ARG VITE_API_BASE_URL="" ENV VITE_API_BASE_URL=$VITE_API_BASE_URL +ARG VITE_SITE_URL="" +ENV VITE_SITE_URL=$VITE_SITE_URL COPY . . RUN npm run build diff --git a/frontend/index.html b/frontend/index.html index cf68ea0..fe31fb9 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,18 +3,30 @@ - + + 날씨각 + + + + + + + + + diff --git a/frontend/public/apple-touch-icon.png b/frontend/public/apple-touch-icon.png new file mode 100644 index 0000000..42156e2 Binary files /dev/null and b/frontend/public/apple-touch-icon.png differ diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg index 6893eb1..e8f4200 100644 --- a/frontend/public/favicon.svg +++ b/frontend/public/favicon.svg @@ -1 +1 @@ - \ No newline at end of file + diff --git a/frontend/public/icons/mask.png b/frontend/public/icons/mask.png new file mode 100644 index 0000000..149e542 Binary files /dev/null and b/frontend/public/icons/mask.png differ diff --git a/frontend/public/og.png b/frontend/public/og.png new file mode 100644 index 0000000..9cdefc0 Binary files /dev/null and b/frontend/public/og.png differ diff --git a/frontend/src/api/client/@tanstack/react-query.gen.ts b/frontend/src/api/client/@tanstack/react-query.gen.ts index 87834e1..2691d9e 100644 --- a/frontend/src/api/client/@tanstack/react-query.gen.ts +++ b/frontend/src/api/client/@tanstack/react-query.gen.ts @@ -3,8 +3,8 @@ import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; -import { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen'; -import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen'; +import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen'; +import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen'; export type QueryKey = [ Pick & { @@ -727,6 +727,24 @@ export const getWatchSummaryOptions = (options: Options) => queryKey: getWatchSummaryQueryKey(options) }); +export const getImageQueryKey = (options: Options) => createQueryKey('getImage', options); + +/** + * 행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만) + */ +export const getImageOptions = (options: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await getImage({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: getImageQueryKey(options) +}); + export const healthzHealthzGetQueryKey = (options?: Options) => createQueryKey('healthzHealthzGet', options); /** diff --git a/frontend/src/api/client/index.ts b/frontend/src/api/client/index.ts index e0949df..943204f 100644 --- a/frontend/src/api/client/index.ts +++ b/frontend/src/api/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen'; -export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; +export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen'; +export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; diff --git a/frontend/src/api/client/sdk.gen.ts b/frontend/src/api/client/sdk.gen.ts index 481e62e..b33c770 100644 --- a/frontend/src/api/client/sdk.gen.ts +++ b/frontend/src/api/client/sdk.gen.ts @@ -2,7 +2,7 @@ import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client'; import { client } from './client.gen'; -import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen'; +import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen'; export type Options = Options2 & { /** @@ -223,6 +223,11 @@ export const likeComment = (options: Option */ export const getWatchSummary = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/watch/summary', ...options }); +/** + * 행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만) + */ +export const getImage = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/image', ...options }); + /** * 헬스체크 */ diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index d6a18a0..d33a082 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -582,6 +582,36 @@ export type Hero = { * 달이 밝게 보이는 비율 0~100 */ moon_pct?: number | null; + /** + * Stats + * + * 히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저 + */ + stats?: Array; +}; + +/** + * HeroStat + */ +export type HeroStat = { + /** + * Icon + */ + icon: string; + /** + * Label + */ + label: string; + /** + * Value + */ + value: string; + /** + * Tone + * + * normal=기본, warn=조심(노랑), rain=비(파랑) + */ + tone: 'normal' | 'warn' | 'rain'; }; /** @@ -946,7 +976,11 @@ export const PostType = { /** * MOON */ - MOON: 14 + MOON: 14, + /** + * UV + */ + UV: 15 } as const; /** @@ -1683,6 +1717,10 @@ export type ResWatchSummary = { * Timeline */ timeline?: Array; + /** + * Events + */ + events?: Array; }; /** @@ -2391,6 +2429,28 @@ export const WarningType = { */ export type WarningType = typeof WarningType[keyof typeof WarningType]; +/** + * WatchEvent + */ +export type WatchEvent = { + /** + * Name + */ + name: string; + /** + * Place Name + */ + place_name: string; + /** + * Status Label + */ + status_label: string; + /** + * Fit + */ + fit?: string | null; +}; + /** * WatchNow */ @@ -3737,6 +3797,44 @@ export type GetWatchSummaryResponses = { export type GetWatchSummaryResponse = GetWatchSummaryResponses[keyof GetWatchSummaryResponses]; +export type GetImageData = { + body?: never; + path?: never; + query: { + /** + * Url + * + * 원본 이미지 주소 + */ + url: string; + }; + url: '/v1/image'; +}; + +export type GetImageErrors = { + /** + * Bad Request + */ + 400: unknown; + /** + * Validation Error + */ + 422: HttpValidationError; + /** + * Bad Gateway + */ + 502: unknown; +}; + +export type GetImageError = GetImageErrors[keyof GetImageErrors]; + +export type GetImageResponses = { + /** + * Successful Response + */ + 200: unknown; +}; + export type HealthzHealthzGetData = { body?: never; path?: never; diff --git a/frontend/src/api/setup.ts b/frontend/src/api/setup.ts index c693c2b..b5217e6 100644 --- a/frontend/src/api/setup.ts +++ b/frontend/src/api/setup.ts @@ -2,6 +2,7 @@ import { client } from './client/client.gen' import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth' export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810' +export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '') type Refresh = 'ok' | 'rejected' | 'unreachable' diff --git a/frontend/src/b/BLayout.tsx b/frontend/src/b/BLayout.tsx index a9955ce..63ef3a2 100644 --- a/frontend/src/b/BLayout.tsx +++ b/frontend/src/b/BLayout.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' import { NavLink, Outlet, useLocation } from 'react-router' import { cx } from '../lib/utils' import { kindOfHour, kst, type TimeKind } from './lib' @@ -14,9 +14,10 @@ import { PinIcon, TabIcon } from './svg' import { Avatar, Skel } from './ui' const TABS = [ - { to: '/', key: 'today', label: '오늘', title: null }, - { to: '/gak', key: 'gak', label: '각', title: '오늘의 각' }, { to: '/sky', key: 'sky', label: '노을', title: '노을' }, + { to: '/gak', key: 'gak', label: '각', title: '오늘의 각' }, + // 메인인 오늘 탭을 가운데에 + { to: '/', key: 'today', label: '오늘', title: null }, { to: '/week', key: 'week', label: '주말·행사', title: '주말·행사' }, { to: '/season', key: 'season', label: '계절·상식', title: '계절·상식' }, ] as const @@ -102,8 +103,32 @@ function SkyBg() { ) } +const PREVIEW_KEY = 'nalssigak.b.skyPreview' +const KINDS: readonly string[] = ['morning', 'day', 'sunset', 'night'] satisfies TimeKind[] + +function readPreview(): TimeKind | null { + try { + const v = sessionStorage.getItem(PREVIEW_KEY) + return v && KINDS.includes(v) ? (v as TimeKind) : null + } catch { + // 저장소가 막힌 브라우저는 '지금'으로 시작한다 + return null + } +} + function SkyProvider({ children }: { children: ReactNode }) { - const [preview, setPreview] = useState(null) + // 고른 시간대는 탭을 옮겨도 이 창에서 유지한다 + const [preview, setPreviewState] = useState(readPreview) + const setPreview = useCallback((k: TimeKind | null) => { + setPreviewState(k) + try { + if (k) sessionStorage.setItem(PREVIEW_KEY, k) + else sessionStorage.removeItem(PREVIEW_KEY) + } catch { + // 저장이 막혀도 이번 화면에서는 메모리 값으로 쓴다 + return + } + }, []) const [serverKind, setServerKind] = useState(null) const [now, setNow] = useState(() => new Date()) useEffect(() => { @@ -112,7 +137,7 @@ function SkyProvider({ children }: { children: ReactNode }) { }, []) const t = kst(now) const kind = preview ?? serverKind ?? kindOfHour(t.h, t.mo, t.mi) - const api = useMemo(() => ({ kind, setPreview, setServerKind }), [kind]) + const api = useMemo(() => ({ kind, preview, setPreview, setServerKind }), [kind, preview, setPreview]) return ( {children} ) @@ -135,12 +160,22 @@ function Shell() { diff --git a/frontend/src/b/Post.tsx b/frontend/src/b/Post.tsx index 8ed1b74..52926cf 100644 --- a/frontend/src/b/Post.tsx +++ b/frontend/src/b/Post.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react' +import { createPortal } from 'react-dom' import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen' import { cx } from '../lib/utils' import { cardBg, clockShort, fall } from './lib' @@ -27,12 +28,13 @@ const ACCOUNTS: Record = { [PostType.AIR]: ['미세먼지', 'vent'], [PostType.DAY_TRIP]: ['당일치기', 'picnic'], [PostType.MOON]: ['오늘 밤 달', 'moon'], + [PostType.UV]: ['자외선', 'glasses'], } type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac'] -const ROW_ICON_BG: Record = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac' } +const ROW_ICON_BG: Record = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac', glasses: 'butter' } /** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */ function slideBg(post: PostData, slide: Slide): SlideBg { @@ -308,11 +310,11 @@ function FullCard({ post }: PostProps) { const [pop, setPop] = useState(0) const [likeFailed, setLikeFailed] = useState(0) const lastTap = useRef(0) - const cardRef = useRef(null) + const trackRef = useRef(null) const [account, avatar] = ACCOUNTS[post.post_type] const n = post.slides.length const bgs = post.slides.map((sl) => slideBg(post, sl)) - const share = () => open({ type: 'share', share: { title: post.title, icon: post.icon, bg: bgs[0] ?? 'sky', messages: post.share_messages ?? [], card: cardRef.current } }) + const share = () => open({ type: 'share', share: { title: post.title, slides: Array.from(trackRef.current?.children ?? []).filter((c) => c instanceof HTMLElement) } }) const comments = () => open({ type: 'comments', postId: post.post_id }) const patch = (values: Partial) => patchFeed(queryClient, post.post_id, values) @@ -368,7 +370,7 @@ function FullCard({ post }: PostProps) { {account} -
+
{n > 1 && (