Merge branch 'main' into feat/open-meteo

This commit is contained in:
skkim committed 2026-10-08 10:58:12 +09:00
commit 3e376ae4b8
49 files changed
+1163 -351

No files matched your search

+3
View File
@@ -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=
+7 -1
View File
@@ -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] | 공유 이미지: 행사 카드의 장소(지도 링크)가 빠짐 — 버튼과 함께 `<a>`도 빼서 생김. 링크는 남기고 버튼만 빼야 함 | 공유 이미지 점검 (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` |
+1
View File
@@ -135,6 +135,7 @@ class PostType(CodeEnum):
AIR = 12
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만)
class EventKind(CodeEnum):
+6
View File
@@ -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}"
+3
View File
@@ -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)
+2
View File
@@ -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):
+8
View File
@@ -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):
View File
Whitespace-only changes.
+22
View File
@@ -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"})
+10 -3
View File
@@ -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"]]
+1 -1
View File
@@ -198,7 +198,7 @@ _WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
_OM_LABEL = {"uv": "자외선", "sun": "햇빛", "view": "가시거리"}
_OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"}
def axis_label(axis: str, rules: dict) -> str:
+39
View File
@@ -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
+86 -18
View File
@@ -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시간 칸 자외선
+88
View File
@@ -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
+19 -5
View File
@@ -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:
+11 -3
View File
@@ -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:
+31 -2
View File
@@ -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
+47
View File
@@ -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)) == []
+93
View File
@@ -0,0 +1,93 @@
import httpx
import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
from services.external import image_proxy
from services.external.image_proxy import ImageFetchFailed, allowed, fetch_image
OK_URL = "https://tong.visitkorea.or.kr/cms/resource/01/test_image.jpg"
@pytest.mark.parametrize("url,ok", [
(OK_URL, True),
("https://www.culture.go.kr/upload/test.jpg", True),
("http://tong.visitkorea.or.kr/cms/a.jpg", False),
("https://evil.example.com/a.jpg", False),
("https://tong.visitkorea.or.kr.evil.example.com/a.jpg", False),
("https://tong.visitkorea.or.kr:8443/a.jpg", False),
("https://user:pw@tong.visitkorea.or.kr/a.jpg", False),
("https://169.254.169.254/latest/meta-data", False),
("not a url", False),
])
def test_allowed(url, ok):
assert allowed(url) is ok
def _client(handler) -> httpx.AsyncClient:
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
@pytest.mark.anyio
async def test_fetch_image_returns_bytes_and_type():
async with _client(lambda r: httpx.Response(200, content=b"\xff\xd8jpeg", headers={"content-type": "image/jpeg; charset=binary"})) as c:
assert await fetch_image(c, OK_URL) == (b"\xff\xd8jpeg", "image/jpeg")
@pytest.mark.anyio
@pytest.mark.parametrize("res", [
httpx.Response(302, headers={"location": "https://evil.example.com/a.jpg"}),
httpx.Response(404),
httpx.Response(200, content=b"<html>", headers={"content-type": "text/html"}),
httpx.Response(200, content=b"<svg/>", headers={"content-type": "image/svg+xml"}),
])
async def test_fetch_image_rejects_redirect_error_and_non_image(res):
async with _client(lambda r: res) as c:
with pytest.raises(ImageFetchFailed):
await fetch_image(c, OK_URL)
@pytest.mark.anyio
async def test_fetch_image_rejects_too_large(monkeypatch):
monkeypatch.setattr(image_proxy, "MAX_BYTES", 10)
async with _client(lambda r: httpx.Response(200, content=b"x" * 11, headers={"content-type": "image/png"})) as c:
with pytest.raises(ImageFetchFailed):
await fetch_image(c, OK_URL)
@pytest.mark.anyio
async def test_image_api_blocks_other_hosts():
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
res = await c.get("/v1/image", params={"url": "https://evil.example.com/a.jpg"})
assert res.status_code == 400
@pytest.mark.anyio
async def test_image_api_serves_image_with_cache(monkeypatch):
async def fake(_client, url):
assert url == OK_URL
return b"png-bytes", "image/png"
monkeypatch.setattr("router.v1.image.image.fetch_image", fake)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
res = await c.get("/v1/image", params={"url": OK_URL})
assert res.status_code == 200
assert res.content == b"png-bytes"
assert res.headers["content-type"] == "image/png"
assert "max-age=86400" in res.headers["cache-control"]
@pytest.mark.anyio
async def test_image_api_reports_upstream_failure(monkeypatch):
async def fail(_client, _url):
raise ImageFetchFailed("status 404")
monkeypatch.setattr("router.v1.image.image.fetch_image", fail)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
res = await c.get("/v1/image", params={"url": OK_URL})
assert res.status_code == 502
def test_allowed_follows_settings(monkeypatch):
from config.settings import settings
monkeypatch.setattr(settings, "image_proxy_hosts", " cdn.example.org , ")
assert allowed("https://cdn.example.org/a.jpg") is True
assert allowed(OK_URL) is False
+1 -1
View File
@@ -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):
+36 -1
View File
@@ -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
+11 -2
View File
@@ -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:
+3
View File
@@ -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:
+41 -31
View File
@@ -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점
- 반영 못 하는 것: 장소 혼잡도는 반영하지 못해요
+4 -4
View File
@@ -140,7 +140,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
<article class="card">
<header><h3>주말 플랜</h3><span class="kind">계획 · 날마다 1장</span><span class="state always">매일</span></header>
<dl><dt>켜지는 때</dt><dd>이번 주말 토·일 각각 독립 카드(포스트는 최대한 나눈다, 10/6). 그날 시간대별 동선: 아침 기온(일교차 크면 겉옷) → 12~16시 바깥 골든타임(비 오는 시간이 있으면 그 시간은 실내, 앞뒤로 바깥) → 그날 열리는 행사 최대 2곳(사진·장소) → 토요일은 일몰 시각에 노을, 일요일은 월요일 아침 기온과 함께 일찍 귀가. 행사는 가까운 순, 일요일은 그날 끝나는 행사 먼저("마지막 날 찬스"). 토요일에 고른 행사는 일요일에 다시 안 나옵니다.</dd></dl>
<dl><dt>켜지는 때</dt><dd>이번 주말 토·일 각각 독립 카드(포스트는 최대한 나눈다, 10/6). 그날 시간대별 동선: 아침 기온(일교차 크면 겉옷) → 12~16시 바깥 골든타임(비 오는 시간이 있으면 그 시간은 실내, 앞뒤로 바깥) → 그날 열리는 행사 최대 2곳(사진·장소) → 토요일은 일몰 시각에 노을, 일요일은 월요일 아침 기온과 함께 일찍 귀가. 행사는 축제→공연→팝업→전시 순으로 종류마다 하나씩, 같은 종류 안에서는 가까운 순이고 일요일은 그날 끝나는 행사 먼저("마지막 날 찬스"). 가깝다고 전시만 이어지지 않게 합니다(10/7). 토요일에 고른 행사는 일요일에 다시 안 나옵니다.</dd></dl>
<dl><dt>① 유저</dt><dd>"주말에 뭐 하지"에 시간표째로 답을 얻습니다.</dd></dl>
<dl><dt>② 운영</dt><dd>날마다 내용이 달라 주말 직전까지 볼 이유가 생기고, "토요일 이렇게 놀자" 공유 카드가 됩니다.</dd></dl>
</article>
@@ -184,8 +184,8 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
<th>카드</th>
<th class="m">아침<small>05–11시</small></th>
<th class="d">낮<small>11시–일몰 2시간 전</small></th>
<th class="e">저녁<small>일몰 2시간 전–21시</small></th>
<th class="n">밤<small>21–05시</small></th>
<th class="e">저녁<small>일몰 2시간 전–일몰 1시간 뒤</small></th>
<th class="n">밤<small>일몰 1시간 뒤–05시</small></th>
</tr></thead>
<tbody>
<tr><td class="name">지금 날씨<small>히어로</small></td><td><span class="pos top">고정</span></td><td><span class="pos top">고정</span></td><td><span class="pos top">고정</span></td><td><span class="pos top">고정</span><span class="note">밤에는 내일 아침 기온을 함께</span></td></tr>
@@ -211,7 +211,7 @@ td .note{display:block;color:var(--muted);font-size:12px;margin-top:3px;line-hei
<div><span class="n">2</span><p>같은 종류 카드는 붙이지 않습니다(확정). 각 3장 사이에는 다른 카드가 하나씩 끼어듭니다.</p></div>
<div><span class="n">3</span><p>조건이 안 맞는 카드는 아예 빼고, 빈 카드나 "오늘은 없어요" 카드는 만들지 않습니다.<small>예외: 노을은 흐린 날에도 한 줄로 남깁니다(확정).</small></p></div>
<div><span class="n">4</span><p>좋아요·댓글은 카드에 붙고, 전국 사용자가 같이 봅니다. 순서가 바뀌어도 같은 카드면 좋아요가 이어집니다.</p></div>
<div><span class="n">5</span><p>시간대가 바뀌는 순간(05·11·16·21시)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.<small>앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.</small></p></div>
<div><span class="n">5</span><p>시간대가 바뀌는 순간(05·11시, 일몰 2시간 전·일몰 1시간 뒤)과 일몰 시각, 예보 갱신 때 피드가 새로 짜입니다.<small>앞에서 문제가 됐던 "새 칸이 늦게 보이는 문제"가 생기지 않습니다.</small></p></div>
<div><span class="n">6</span><p>카드마다 보낼 문구가 있고, 보내면 카드 그대로 이미지+링크로 갑니다(확정).</p></div>
<div><span class="n">7</span><p>UI는 따로 고민하지 않고 인스타그램·페이스북 방식을 그대로 따릅니다(확정, 10/2).</p></div>
<div><span class="n">8</span><p>지역은 날씨를 가져오는 시군구 단위 그대로입니다. 수원시 장안구 같은 일반구도 따로 봅니다(확정, 10/2, 256곳).</p></div>
+6 -6
View File
@@ -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초**만 둔다. 다음 요청이 다시 채우게 하려고.
### 언제 새로 만들어지나
+2
View File
@@ -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
+13 -1
View File
@@ -3,18 +3,30 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<meta name="description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
<title>날씨각</title>
<meta property="og:type" content="website" />
<meta property="og:site_name" content="날씨각" />
<meta property="og:title" content="날씨각" />
<meta property="og:description" content="오늘 날씨를 지수로. 노을, 야장각, 주말 계획까지 날씨각에서 확인하세요." />
<meta property="og:url" content="%VITE_SITE_URL%/" />
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Jua&family=Bagel+Fat+One&family=Gowun+Batang&display=swap"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css"
crossorigin="anonymous"
/>
</head>
<body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><g fill="#ffb02e"><circle cx="32" cy="5.5" r="4.5"/><circle cx="32" cy="58.5" r="4.5"/><circle cx="5.5" cy="32" r="4.5"/><circle cx="58.5" cy="32" r="4.5"/><circle cx="13.3" cy="13.3" r="4.5"/><circle cx="50.7" cy="13.3" r="4.5"/><circle cx="13.3" cy="50.7" r="4.5"/><circle cx="50.7" cy="50.7" r="4.5"/></g><circle cx="32" cy="32" r="21" fill="#ff7a45"/><circle cx="32" cy="32" r="21" fill="url(#g)"/><ellipse cx="18.5" cy="37" rx="4" ry="2.6" fill="#ff4f6d" opacity=".55"/><ellipse cx="45.5" cy="37" rx="4" ry="2.6" fill="#ff4f6d" opacity=".55"/><circle cx="24" cy="29.5" r="3.2" fill="#3a2a2a"/><circle cx="40" cy="29.5" r="3.2" fill="#3a2a2a"/><circle cx="25" cy="28.4" r="1.1" fill="#fff"/><circle cx="41" cy="28.4" r="1.1" fill="#fff"/><path d="M26.5 37.5q5.5 5 11 0" fill="none" stroke="#3a2a2a" stroke-width="2.6" stroke-linecap="round"/><defs><radialGradient id="g" cx=".38" cy=".3" r=".75"><stop offset="0" stop-color="#ffd36b"/><stop offset=".6" stop-color="#ff9a3c" stop-opacity=".6"/><stop offset="1" stop-color="#ff7a45" stop-opacity="0"/></radialGradient></defs></svg>

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 310 KiB

@@ -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<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -727,6 +727,24 @@ export const getWatchSummaryOptions = (options: Options<GetWatchSummaryData>) =>
queryKey: getWatchSummaryQueryKey(options)
});
export const getImageQueryKey = (options: Options<GetImageData>) => createQueryKey('getImage', options);
/**
* 행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)
*/
export const getImageOptions = (options: Options<GetImageData>) => queryOptions<unknown, GetImageError, unknown, ReturnType<typeof getImageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getImage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getImageQueryKey(options)
});
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
/**
+2 -2
View File
@@ -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 UnlikePostLine truncated
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 UnlikeCommentErLine truncated
+6 -1
View File
@@ -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<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -223,6 +223,11 @@ export const likeComment = <ThrowOnError extends boolean = true>(options: Option
*/
export const getWatchSummary = <ThrowOnError extends boolean = true>(options: Options<GetWatchSummaryData, ThrowOnError>): RequestResult<GetWatchSummaryResponses, GetWatchSummaryErrors, ThrowOnError> => (options.client ?? client).get<GetWatchSummaryResponses, GetWatchSummaryErrors, ThrowOnError>({ url: '/v1/watch/summary', ...options });
/**
* 행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)
*/
export const getImage = <ThrowOnError extends boolean = true>(options: Options<GetImageData, ThrowOnError>): RequestResult<GetImageResponses, GetImageErrors, ThrowOnError> => (options.client ?? client).get<GetImageResponses, GetImageErrors, ThrowOnError>({ url: '/v1/image', ...options });
/**
* 헬스체크
*/
+99 -1
View File
@@ -582,6 +582,36 @@ export type Hero = {
* 달이 밝게 보이는 비율 0~100
*/
moon_pct?: number | null;
/**
* Stats
*
* 히어로 두 칸. 지금 챙길 것(비·미세먼지·자외선·일교차·체감·불쾌지수) 먼저
*/
stats?: Array<HeroStat>;
};
/**
* 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<WatchTimeline>;
/**
* Events
*/
events?: Array<WatchEvent>;
};
/**
@@ -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;
+1
View File
@@ -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'
+46 -11
View File
@@ -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<TimeKind | null>(null)
// 고른 시간대는 탭을 옮겨도 이 창에서 유지한다
const [preview, setPreviewState] = useState<TimeKind | null>(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<TimeKind | null>(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 (
<SkyContext value={api}>{children}</SkyContext>
)
@@ -135,12 +160,22 @@ function Shell() {
<Outlet />
</main>
<nav aria-label="주요 메뉴" className="b-tabbar fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t px-[max(4px,calc((100%-432px)/2))] pt-[7px] pb-[calc(8px+env(safe-area-inset-bottom,0px))] backdrop-blur-[10px]">
{TABS.map((t) => (
<NavLink key={t.key} to={t.to} end={t.to === '/'} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
<TabIcon name={t.key} className="size-[25px]" />
{t.label}
</NavLink>
))}
{TABS.map((t) =>
t.key === 'today' ? (
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
<NavLink key={t.key} to={t.to} end className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive ? 'text-(--orange)' : 'text-(--ink3)')}>
<span className="grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
<TabIcon name={t.key} className="size-[30px]" />
</span>
{t.label}
</NavLink>
) : (
<NavLink key={t.key} to={t.to} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
<TabIcon name={t.key} className="size-[25px]" />
{t.label}
</NavLink>
),
)}
</nav>
</div>
</div>
+19 -12
View File
@@ -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, readonly [string, string]> = {
[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<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac' }
const ROW_ICON_BG: Record<string, SlideBg> = { 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<HTMLDivElement>(null)
const trackRef = useRef<HTMLDivElement>(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<PostData>) => patchFeed(queryClient, post.post_id, values)
@@ -368,7 +370,7 @@ function FullCard({ post }: PostProps) {
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div ref={cardRef} className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
{n > 1 && (
<span data-noshot className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
{index + 1}/{n}
@@ -385,15 +387,16 @@ function FullCard({ post }: PostProps) {
if (e.key === 'ArrowRight') slider?.scrollNext()
}}
>
<div className="flex h-full">
<div ref={trackRef} className="flex h-full">
{post.slides.map((s, i) => (
<SlideView key={i} slide={s} bg={bgs[i]} />
))}
</div>
</div>
{n > 1 && <Arrows api={slider} prev={canPrev} next={canNext} />}
{pop > 0 && (
<div key={pop} data-noshot className="pointer-events-none absolute inset-0 z-[4] grid place-items-center" aria-hidden="true">
{/* 좋아요 효과·알림은 카드가 아니라 화면 위에 띄운다 */}
{pop > 0 && createPortal(
<div key={pop} className="pointer-events-none fixed inset-0 z-50 grid place-items-center" aria-hidden="true">
{BURST.map((b, k) => (
<svg key={k} className="b-like-bit absolute w-5" style={{ '--dx': `${b[0]}px`, '--dy': `${b[1]}px`, '--rot': `${b[2]}deg` } as CSSProperties} viewBox="0 0 24 24" fill={b[3]}>
<path d={HEART} />
@@ -408,12 +411,16 @@ function FullCard({ post }: PostProps) {
</defs>
<path d={HEART} />
</svg>
<span className="b-like-toast absolute top-[62%] rounded-full bg-white px-4 py-2 font-jua text-[17px] text-(--heart) opacity-0 shadow-[0_8px_18px_rgb(40_48_74/0.18)]">좋아요했어요!</span>
</div>
<span className="b-like-toast absolute top-[58%] rounded-full bg-white px-4 py-2 font-jua text-[17px] text-(--heart) opacity-0 shadow-[0_8px_18px_rgb(40_48_74/0.18)]">좋아요했어요!</span>
</div>,
document.body,
)}
{likeFailed > 0 && createPortal(
<p role="alert" className="pointer-events-none fixed inset-x-0 bottom-[calc(88px+env(safe-area-inset-bottom,0px))] z-50 m-0 flex justify-center px-4">
<span className="rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</span>
</p>,
document.body,
)}
<p data-noshot role="status" className="pointer-events-none absolute inset-x-0 bottom-4 z-[5] m-0 flex justify-center px-4">
{likeFailed > 0 && <span className="rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</span>}
</p>
</div>
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className="grid size-7 cursor-pointer place-items-center">
+52 -94
View File
@@ -1,6 +1,7 @@
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
import { setTokens, subscribeAuth } from '../api/auth'
import { SITE_URL } from '../api/setup'
import {
addCommentMutation,
deleteCommentMutation,
@@ -24,7 +25,7 @@ import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { useRegion } from './regionContext'
import { useSky } from './skyContext'
import { storyImage } from './storyImage'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
import { HeartIcon } from './svg'
import { Avatar, Ic, Skel, StateBox } from './ui'
@@ -446,138 +447,95 @@ function SeasonWeekSheet() {
}
/* ---------- 보내기 ---------- */
const SIZE_KEYS = Object.keys(SHARE_SIZES) as ShareSize[]
function ShareSheet({ share }: { share: SharePayload }) {
const { region } = useRegion()
const opts = [...share.messages, '직접 쓰기']
const [pick, setPick] = useState(0)
const [mine, setMine] = useState('')
const [toast, setToast] = useState('')
const isMine = pick === opts.length - 1
const msg = isMine ? mine : opts[pick]
const url = window.location.origin
const text = msg.trim() ? `${msg} — ${share.title} · 날씨각` : `${share.title} · 날씨각`
const { kind } = useSky()
const [image, setImage] = useState<{ blob: Blob; src: string } | null>(null)
const [imageError, setImageError] = useState(false)
const [size, setSize] = useState<ShareSize>('story')
const [images, setImages] = useState<Partial<Record<ShareSize, { blob: Blob; src: string }>>>({})
const [failed, setFailed] = useState<Partial<Record<ShareSize, boolean>>>({})
const srcs = useRef<string[]>([])
const [toast, setToast] = useState('')
const image = images[size]
const text = `${share.title} · 날씨각 ${SITE_URL}`
// 창이 열리면 카드를 스토리 크기 이미지로 미리 만들어 둔다
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
useEffect(() => {
if (!share.card) return
let src = ''
if (images[size] || failed[size]) return
let alive = true
storyImage(share.card, { title: share.title, sub: `${region.name} · 날씨각`, sky: kind }).then(
const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' })
shareImage(share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
(blob) => {
if (!alive) return
src = URL.createObjectURL(blob)
setImage({ blob, src })
const src = URL.createObjectURL(blob)
srcs.current.push(src)
setImages((m) => ({ ...m, [size]: { blob, src } }))
},
(e: unknown) => {
console.error('[share] story image', e)
if (alive) setImageError(true)
console.error('[share] image', e)
if (alive) setFailed((m) => ({ ...m, [size]: true }))
},
)
return () => {
alive = false
if (src) URL.revokeObjectURL(src)
}
}, [share.card, share.title, region.name, kind])
}, [size, images, failed, share.slides, kind, region.name])
// 휴대폰은 공유창에 이미지 파일을 넘기고(인스타 스토리·카톡 등), 안 되면 이미지를 내려받는다
const shareImage = () => {
useEffect(() => {
const list = srcs.current
return () => list.forEach((s) => URL.revokeObjectURL(s))
}, [])
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다
const send = () => {
if (!image) return
const file = new File([image.blob], 'nalssigak.png', { type: 'image/png' })
if (navigator.canShare?.({ files: [file] })) {
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
if (navigator.canShare?.({ files: [file], text })) {
navigator.share({ files: [file], title: share.title, text }).then(
() => setToast('보냈어요'),
(e: unknown) => {
if (e instanceof DOMException && e.name === 'AbortError') return
setToast('공유하지 못했어요. 이미지를 내려받아 올려 주세요')
console.error('[share] send', e)
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
},
)
return
}
const a = document.createElement('a')
a.href = image.src
a.download = 'nalssigak.png'
a.download = file.name
a.click()
setToast('이미지를 내려받았어요. 인스타 스토리에 올려 보세요')
}
// 휴대폰 기본 공유창. 없거나 실패하면 링크 복사로 대신한다.
const shareNative = () => {
if (!navigator.share) {
copy()
return
}
navigator.share({ title: share.title, text, url }).then(
() => setToast('보냈어요'),
(e: unknown) => {
if (e instanceof DOMException && e.name === 'AbortError') return
copy()
},
)
}
const copy = () => {
if (!navigator.clipboard) {
setToast('복사가 막혀 있어요')
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(`${text} ${url}`).then(
() => setToast('보낼 말과 링크를 복사했어요'),
() => setToast('복사가 막혀 있어요. 길게 눌러 복사해 주세요'),
navigator.clipboard.writeText(text).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
}
return (
<Body>
<div className={cx('flex items-center gap-3 rounded-[20px] p-3.5', `b-bg-${share.bg}`)}>
<Ic name={share.icon} className="w-[58px]" />
<div>
<b className="block font-jua text-[19px] font-normal">{share.title}</b>
<small className="font-bold opacity-80">날씨각 · {region.name}</small>
</div>
</div>
<div className="mt-3 flex flex-col gap-1.5" role="radiogroup" aria-label="함께 보낼 말">
{opts.map((o, k) => (
<label key={o} className="flex cursor-pointer items-center gap-2.5 rounded-[14px] bg-[#f3f6fb] px-3 py-2.5 font-semibold">
<input type="radio" name="share-msg" checked={pick === k} onChange={() => setPick(k)} className="accent-(--orange)" />
{o}
</label>
<div className="grid grid-cols-3 gap-1.5 rounded-[16px] bg-[#f3f6fb] p-1" role="radiogroup" aria-label="이미지 크기">
{SIZE_KEYS.map((k) => (
<button key={k} type="button" role="radio" aria-checked={size === k} aria-label={`${SHARE_SIZES[k].ratio} 비율`} onClick={() => setSize(k)} className={cx('flex cursor-pointer items-center justify-center gap-2 rounded-[12px] py-2 text-sm font-extrabold', size === k ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink3)')}>
<i className="h-4 rounded-[3px] border-2 border-current" style={{ aspectRatio: `${SHARE_SIZES[k].w} / ${SHARE_SIZES[k].hr}` }} aria-hidden="true" />
{SHARE_SIZES[k].ratio}
</button>
))}
</div>
{isMine && (
<textarea
value={mine}
onChange={(e) => setMine(e.target.value)}
rows={2}
maxLength={80}
placeholder="예: 오늘 한강 갈래? 🌇"
aria-label="보낼 말 직접 쓰기"
className="mt-1.5 w-full resize-none rounded-[14px] border border-[#dfe5ee] px-3 py-2.5"
/>
)}
{share.card && (
<div className="mt-3.5 flex items-center gap-3 rounded-[18px] bg-[#f3f6fb] p-2.5">
{image ? <img src={image.src} alt="공유할 이미지 미리보기" className="h-28 rounded-[10px] shadow-[0_4px_10px_rgb(40_48_74/0.15)]" /> : <span className="grid h-28 w-16 place-items-center rounded-[10px] bg-white text-xs font-bold text-(--ink3)">{imageError ? '실패' : '만드는 중'}</span>}
<div className="flex flex-1 flex-col gap-1.5">
<b className="text-sm font-extrabold">이미지로 보내기</b>
<small className="text-xs font-semibold text-(--ink2)">인스타 스토리 크기(9:16)로 만들어요</small>
<button type="button" onClick={shareImage} disabled={!image} className="cursor-pointer rounded-[14px] bg-(--orange) py-2.5 font-jua text-[15px] text-white shadow-[inset_0_-4px_0_var(--orange-deep)] disabled:opacity-50">
이미지 공유하기
</button>
</div>
</div>
)}
<div className="mt-3.5 grid grid-cols-2 gap-2">
<button type="button" onClick={shareNative} className="cursor-pointer rounded-[16px] bg-(--orange-deep) py-3 font-jua text-base text-white">
공유하기
</button>
<button type="button" onClick={copy} className="cursor-pointer rounded-[16px] bg-(--ink) py-3 font-jua text-base text-white">
링크 복사
</button>
<div className="mt-3 flex h-[300px] items-center justify-center rounded-[18px] bg-[#f3f6fb] p-3">
{image ? (
<img src={image.src} alt={`${SHARE_SIZES[size].ratio} 공유 이미지 미리보기`} className="max-h-full max-w-full rounded-[10px] shadow-[0_4px_12px_rgb(40_48_74/0.18)]" />
) : (
<span className="text-sm font-bold text-(--ink3)">{failed[size] ? '이미지를 만들지 못했어요' : '이미지 만드는 중'}</span>
)}
</div>
<button type="button" onClick={send} disabled={!image} className="mt-3.5 block w-full cursor-pointer rounded-[16px] bg-(--orange) py-3 font-jua text-base text-white shadow-[inset_0_-4px_0_var(--orange-deep)] disabled:opacity-50">
공유하기
</button>
<p className="mt-3 min-h-5 text-center text-[13px] font-bold text-[#1f9d62]" aria-live="polite">
{toast}
</p>
+51 -77
View File
@@ -2,7 +2,7 @@ import { Fragment, useEffect, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
import type { BandArticle, BandEvent, Hero as HeroData, HeroStat as HeroStatData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { PostCard, PostCardSkel } from './Post'
@@ -15,7 +15,7 @@ import { deg, skyText, slotAt } from './weatherText'
type Mode = 'now' | TimeKind
const MODES: [Mode, string][] = [
['now', '지금 시간'],
['now', '지금'],
['morning', '아침'],
['day', '낮'],
['sunset', '저녁'],
@@ -30,6 +30,9 @@ const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }>
night: { label: '밤', clock: '22:10', hour: 22 },
}
// 히어로 칸을 받아 오는 동안 자리만 잡아 둔다
const STAT_HOLD = ['a', 'b']
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
const SHOOTS = [
@@ -37,7 +40,6 @@ const SHOOTS = [
{ top: '20%', left: '52%', '--len': '70px', '--dur': '9s', '--dl': '4s' },
{ top: '34%', left: '94%', '--len': '80px', '--dur': '11s', '--dl': '6.5s' },
]
const ORB_POS = { left: '66%', top: '6px', d: '.5s', f: '4.4s' }
function useNow(ms = 20000) {
const [now, setNow] = useState(() => new Date())
@@ -72,31 +74,29 @@ type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Lo
function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
const { open } = useSheet()
const [mode, setMode] = useState<Mode>('now')
const { preview, setServerKind, setPreview } = useSky()
const mode: Mode = preview ?? 'now'
const setMode = (m: Mode) => setPreview(m === 'now' ? null : m)
const clock = useNow()
const t = kst(clock)
const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)) : mode
const { setServerKind, setPreview } = useSky()
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
useEffect(() => setPreview(mode === 'now' ? null : mode), [mode, setPreview])
useEffect(() => () => setPreview(null), [setPreview])
const slots = today?.slots ?? []
const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined
// 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다
const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c
const feels = mode === 'now' && hero ? hero.feels_c : slot?.feels_c
const top1 = hero?.top1
const who = kind === 'night' ? 'bear' : 'rabbit'
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
const tempLoad = mode === 'now' ? feedLoad : todayLoad
const feelsLine = temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : failed(tempLoad) ? '날씨를 못 불러왔어요' : tempLoad === 'ready' ? '체감 ?°' : null
const tempChip = temp != null ? `${deg(temp)}${slot ? ` ${skyText(slot)}` : ''}` : null
const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
// 아래 값은 모두 로딩·완료·실패 사이 높이가 같다: 글자 자리 스켈레톤, 비 칸은 두 줄 높이로 고정
// 시안 A: 점수 해가 주인공. 위에 시간대 탭과 날짜, 가운데 큰 해, 아래 칩 한 줄과 캐릭터 말풍선(1위 각)
return (
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[32px] px-[18px] pt-4 pb-[18px]" data-t={kind}>
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind}>
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
{STARS.map((s, i) => (
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
@@ -105,36 +105,19 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
<span key={i} className="b-shoot" style={s} />
))}
</div>
<div className="relative z-[3] flex flex-wrap gap-1.5" role="group" aria-label="시간대 배경 미리보기">
<div className="relative z-[3] grid grid-cols-5 rounded-full bg-white/45 p-1" role="tablist" aria-label="시간대 배경 미리보기">
{MODES.map(([m, l]) => (
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full px-2.5 py-[5px] text-xs font-bold', mode === m ? 'bg-(--ink) text-white' : 'bg-white/55 text-(--ink)')}>
<button key={m} type="button" role="tab" aria-selected={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-[5px] text-[13px] font-bold', mode === m ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink) opacity-70')}>
{l}
</button>
))}
</div>
<div className="relative z-[3] mt-3 flex items-end justify-between">
<div>
<p className="mb-1 text-[13.5px] font-bold opacity-85">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 · {mode === 'now' ? '지금' : `${PREVIEW[mode].label} 미리보기`}
</p>
<div className="font-bagel text-[60px] leading-none">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</div>
</div>
<div className="text-right">
<b className="block font-bagel text-[42px] leading-none font-normal">{heroVal(tempLoad, temp != null ? deg(temp) : null, 'w-[72px]')}</b>
<span className="block text-[12.5px] font-bold opacity-85">{feelsLine ?? <Skel className="w-[118px]" />}</span>
</div>
</div>
<div className="relative z-[3] mt-3 grid grid-cols-2 gap-2.5">
<HeroStat icon="thermo" label="불쾌지수">
{heroVal(feedLoad, hero?.discomfort != null ? `${hero.discomfort} · ${hero.discomfort_label ?? ''}` : null, 'w-16')}
</HeroStat>
<HeroStat icon="umbrella" label="지금 비">
{heroVal(feedLoad, hero?.will_rain_2h == null ? null : hero.will_rain_2h ? '2시간 안에 와요' : '2시간 동안 안 와요', 'w-16')}
</HeroStat>
</div>
<div className="relative mt-5 h-[286px]">
<span className="b-cloud b-fall top-6 left-[6%] h-[30px] w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
<div className="b-sun b-fall absolute top-10 left-1/2 -ml-[82px] grid aspect-square w-[164px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
<p className="relative z-[3] mt-2 mb-0 text-[14px] font-bold opacity-90">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]} · <b className="font-bagel text-[19px] font-normal">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</b>
</p>
<div className="relative h-[196px]">
<span className="b-cloud b-fall top-3 left-[4%] h-8 w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-[90px] grid aspect-square w-[180px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && (
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
@@ -142,46 +125,49 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
</svg>
)}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
<b className="block font-bagel text-[56px] leading-[0.9] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[84px]')}</b>
<small className="mt-0.5 block font-jua text-[14.5px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : '오늘 날씨 점수'}</small>
<small className="block font-jua text-[13px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : '오늘 날씨 점수'}</small>
<b className="block font-bagel text-[74px] leading-[0.95] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[120px]')}</b>
</span>
</div>
<span className="b-cloud b-fall top-[188px] left-[54%] h-10 w-[118px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
<span className="b-cloud b-fall top-[140px] left-[58%] h-9 w-[96px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
</div>
{/* 기온 + 서버가 고른 챙길 것(비·미세먼지·자외선·일교차 등)을 한 줄 세 칸으로. 휴대폰에서 두 줄로 넘치지 않게 칸 안에서 위아래로 */}
<div className="relative z-[3] mt-1 grid auto-cols-fr grid-flow-col gap-1.5">
<Stat label={mode === 'now' ? '지금' : PREVIEW[mode].label}>{heroVal(tempLoad, tempChip, 'w-12')}</Stat>
{hero?.stats?.length
? hero.stats.map((s) => (
<Stat key={s.label} label={s.label} tone={s.tone}>
{s.value}
</Stat>
))
: feedLoad === 'loading' && STAT_HOLD.map((k) => <Stat key={k} label="">{heroVal(feedLoad, null, 'w-12')}</Stat>)}
</div>
<div className="relative z-[3] mt-2 flex items-center gap-2">
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[44px] shrink-0 drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
{top1 ? (
<button
type="button"
onClick={() => open({ type: 'gak', indexId: top1.index_id })}
aria-label={`1위 ${top1.name} ${top1.score}점, 계산 근거 보기`}
className="b-fall absolute z-[2] flex w-24 cursor-pointer flex-col items-center"
style={{ left: ORB_POS.left, top: ORB_POS.top, ...fall(ORB_POS.d, ORB_POS.f) }}
>
<span className="relative w-[78px]">
<Ic name={top1.icon} className="w-full drop-shadow-[0_10px_12px_rgb(40_48_74/0.16)]" />
<Ic name={MEDALS[0]} className="absolute -top-2 -left-3.5 w-[30px]" />
</span>
<span className="b-orb-label font-jua text-sm whitespace-nowrap">
1위 {top1.name} <em className="font-bagel text-(--orange) not-italic">{top1.score}</em>
</span>
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="b-bubble flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-[18px] px-3 py-2 text-left">
<span className="min-w-0 flex-1 truncate font-jua text-[16px]">{bubble}</span>
<Ic name={top1.icon} className="w-7 shrink-0" />
<em className="font-bagel text-[17px] text-(--orange) not-italic">{top1.score}</em>
</button>
) : (
feedLoad === 'loading' && (
<span className="absolute z-[2] flex w-24 flex-col items-center gap-1" style={{ left: ORB_POS.left, top: ORB_POS.top }} aria-hidden="true">
<Skel shape className="size-[78px] rounded-full" />
<span className="font-jua text-sm">
<Skel className="w-[72px]" />
</span>
</span>
)
<span className="b-bubble min-w-0 flex-1 rounded-[18px] px-3 py-2 font-jua text-[16px]">{bubble ?? <Skel className="w-[120px]" />}</span>
)}
</div>
<div className="relative z-[3] flex items-end gap-2">
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[50px] drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
<span className="mb-3 rounded-[20px_20px_20px_6px] bg-white px-3.5 py-[9px] font-jua text-base text-(--ink) shadow-[0_8px_16px_rgb(40_48_74/0.1)]">{bubble ?? <Skel className="w-[120px]" />}</span>
</div>
</div>
)
}
/** 히어로 아래 한 칸: 작은 이름 위, 값 아래. tone 은 서버가 정한 상태(비·경고)로 색을 바꾼다 */
function Stat({ label, tone = 'normal', children }: { label: string; tone?: HeroStatData['tone']; children: ReactNode }) {
return (
<span className="b-stat flex min-w-0 flex-col items-center rounded-2xl px-1.5 pt-1.5 pb-2 text-center break-keep" data-tone={tone}>
<small className="text-[11.5px] font-bold opacity-75">{label}</small>
<b className="font-jua text-[14.5px] leading-tight font-normal">{children}</b>
</span>
)
}
const WANING = ['기우는 달', '하현달', '그믐달']
/**
@@ -194,18 +180,6 @@ function moonPath(pct: number, r: number, lit: boolean) {
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function HeroStat({ icon, label, children }: { icon: string; label: string; children: ReactNode }) {
return (
<div className="b-stat flex min-h-[90px] items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
<Ic name={icon} className="w-9 shrink-0" />
<div className="min-w-0">
<small className="block text-xs font-bold opacity-80">{label}</small>
<b className="block font-jua text-lg font-normal">{children}</b>
</div>
</div>
)
}
function Stories({ items }: { items: TopIndex[] }) {
const { open } = useSheet()
return (
+39 -33
View File
@@ -1,4 +1,4 @@
import { useState, type ReactNode } from 'react'
import { useRef, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils'
@@ -165,9 +165,10 @@ export function WeekPage() {
// 날씨(고른 날)가 와야 명소를 부를 수 있다
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready'
const pickRef = useRef<HTMLDivElement>(null)
const sendPlan = () => {
if (!sel) return
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, icon: 'calendar', bg: 'mint', messages: [`${sel.weekday}요일 이렇게 놀자! ${sel.pick} 😆`, '이번 주말 같이 놀자 🙌'] } })
if (!sel || !pickRef.current) return
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, slides: [pickRef.current] } })
}
return (
@@ -214,7 +215,7 @@ export function WeekPage() {
/>
)}
{sel && (
<div className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
<div ref={pickRef} className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
<Ic name={sel.icon} className="w-16" />
<div>
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
@@ -235,35 +236,40 @@ export function WeekPage() {
</select>
</div>
)}
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? <Skel className="w-56" /> : '날씨에 맞춰 골라 보여 줘요'} className="pt-3" />
{placeList.length ? (
<Rail className={cx('transition-opacity', places.isPlaceholderData && 'opacity-60')}>
{placeList.map((p, i) => (
<div key={p.place_id} className={PLACE_CARD}>
<span className={cx('relative grid h-[104px] place-items-center', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)}>
{p.is_good && <span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-(--rain)')}>{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</span>}
<Ic name={p.icon} className="w-[62px]" />
</span>
<span className="block px-3 pt-2.5 pb-3">
<span className="text-[11.5px] font-extrabold text-(--ink3)">
{p.area} · {p.is_outdoor ? '야외' : '실내'}
</span>
<b className="block font-jua text-[16.5px] font-normal">
<MapLink place={p.name}>{p.name}</MapLink>
</b>
<small className="block text-[12.5px] leading-snug font-semibold text-(--ink2)">
{p.reason}
<br />
추천 {p.best_time}
</small>
</span>
</div>
))}
</Rail>
) : placeLoad === 'loading' ? (
<PlacesSkel />
) : (
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? `${sido} 데이트 명소는 아직 준비 중이에요.` : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} className="inset-x-3 top-3 bottom-1" />
{/* 명소 데이터가 없는 지역은 칸 전체를 숨긴다 (지금은 서울만 있음) */}
{!(placeLoad === 'ready' && !placeList.length) && (
<>
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? <Skel className="w-56" /> : '날씨에 맞춰 골라 보여 줘요'} className="pt-3" />
{placeList.length ? (
<Rail className={cx('transition-opacity', places.isPlaceholderData && 'opacity-60')}>
{placeList.map((p, i) => (
<div key={p.place_id} className={PLACE_CARD}>
<span className={cx('relative grid h-[104px] place-items-center', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)}>
{p.is_good && <span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-(--rain)')}>{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</span>}
<Ic name={p.icon} className="w-[62px]" />
</span>
<span className="block px-3 pt-2.5 pb-3">
<span className="text-[11.5px] font-extrabold text-(--ink3)">
{p.area} · {p.is_outdoor ? '야외' : '실내'}
</span>
<b className="block font-jua text-[16.5px] font-normal">
<MapLink place={p.name}>{p.name}</MapLink>
</b>
<small className="block text-[12.5px] leading-snug font-semibold text-(--ink2)">
{p.reason}
<br />
추천 {p.best_time}
</small>
</span>
</div>
))}
</Rail>
) : placeLoad === 'loading' ? (
<PlacesSkel />
) : (
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? `${sido} 데이트 명소는 아직 준비 중이에요.` : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} className="inset-x-3 top-3 bottom-1" />
)}
</>
)}
<Sec title="이번 주말 전국 날씨 순위" sub="낮 10~17시 나들이 날씨 · 대표 지역 30곳 중 10위까지" className="pt-[18px]" />
{rankDays.length ? (
+26
View File
@@ -184,6 +184,26 @@
.b-hero[data-t='sunset'] .b-stat {
background: rgb(30 16 80 / 0.2);
}
/* 히어로 칸 강조: 조심(노랑)·비(파랑). 시간대 배경과 상관없이 같은 색 */
.b-hero .b-stat[data-tone='warn'] {
background: #fff3d6;
color: var(--ink);
box-shadow: inset 0 -5px 0 #ffd98a;
}
.b-hero .b-stat[data-tone='rain'] {
background: #dcecff;
color: var(--ink);
box-shadow: inset 0 -5px 0 #a9cdf5;
}
.b-bubble {
background: #fff;
color: var(--ink);
box-shadow: 0 8px 16px rgb(40 48 74 / 0.1);
}
.b-hero[data-t='night'] .b-bubble {
background: rgb(30 34 70 / 0.85);
color: #fff;
}
.b-orb-label {
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
}
@@ -481,6 +501,7 @@
}
.b-tabbar {
background: rgb(255 255 255 / 0.6);
overflow: visible;
border-color: rgb(255 255 255 / 0.4);
}
.b-app[data-t='night'] .b-topbg {
@@ -573,3 +594,8 @@
.b-app[data-t='night'] .b-band-3 {
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
}
/* 밤엔 메인 탭 동그라미 테두리를 막대 색에 맞춘다 */
.b-app[data-t='night'] .b-tab-main > span {
--tw-ring-color: rgb(18 24 60 / 0.9);
}
+4 -3
View File
@@ -1,6 +1,6 @@
import type { CSSProperties } from 'react'
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple'])
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
@@ -97,11 +97,12 @@ export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–21 · 밤 21–05 */
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
const at = h + minute / 60
const sunset = SUNSET_HOUR[month - 1]
if (at >= 5 && at < 11) return 'morning'
if (at >= 11 && at < 21) return at < SUNSET_HOUR[month - 1] - 2 ? 'day' : 'sunset'
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
return 'night'
}
+1 -3
View File
@@ -1,7 +1,5 @@
import { createContext, use } from 'react'
import type { SlideBg } from './types'
export type SharePayload = { title: string; icon: string; bg: SlideBg; messages: string[]; card?: HTMLElement | null }
export type SharePayload = { title: string; slides: HTMLElement[] }
export type SheetState =
| { type: 'gak'; indexId: number }
+2 -2
View File
@@ -1,8 +1,8 @@
import { createContext, use } from 'react'
import type { TimeKind } from './lib'
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼이 잠시 바꿀 수 있다 */
export type SkyApi = { kind: TimeKind; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
export const SkyContext = createContext<SkyApi | null>(null)
+192 -30
View File
@@ -1,10 +1,10 @@
import { domToCanvas } from 'modern-screenshot'
import { API_BASE_URL } from '../api/setup'
const W = 1080
const H = 1920
const CARD_W = 900
const SIDE = 60
// 시간대별 스토리 배경 (화면 하늘 배경과 같은 색)
// 시간대별 배경 (화면 하늘 배경과 같은 색)
const SKY: Record<string, [string, string, string]> = {
morning: ['#ffe0c4', '#fff0e2', '#e4f2ff'],
day: ['#cde7ff', '#e9f5ff', '#f7fbff'],
@@ -12,56 +12,218 @@ const SKY: Record<string, [string, string, string]> = {
night: ['#0e1433', '#1b2356', '#2a2e6e'],
}
/** 공유 이미지 크기. 위: 로고·지역 날짜, 가운데: 카드, 아래: 주소 */
export const SHARE_SIZES = {
story: { ratio: '9:16', w: 9, hr: 16, h: 1920, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 },
feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, logoY: 140, logoPx: 76, subY: 200, subPx: 34, pillY: 1250, pillH: 84, labelPx: 30, hostPx: 40 },
square: { ratio: '1:1', w: 1, hr: 1, h: 1080, logoY: 115, logoPx: 64, subY: 168, subPx: 30, pillY: 990, pillH: 80, labelPx: 28, hostPx: 38 },
} as const
export type ShareSize = keyof typeof SHARE_SIZES
const LOGO = (px: number) => `${px}px Jua, sans-serif`
const SANS = (px: number) => `bold ${px}px "Pretendard Variable", sans-serif`
const PILL_LABEL = '오늘 내 동네 각 보기'
// 버튼·조작 표시(data-noshot)는 이미지에 넣지 않는다. 링크(장소 등)는 글자라 남긴다
const keep = (n: Node) => !(n instanceof HTMLButtonElement || (n instanceof HTMLElement && n.dataset.noshot != null))
function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
ctx.beginPath()
ctx.roundRect(x, y, w, h, r)
}
/** 게시물 카드 한 장을 인스타 스토리 크기(1080×1920) PNG로 만든다 */
export async function storyImage(card: HTMLElement, opts: { title: string; sub: string; sky: string }): Promise<Blob> {
const shot = await domToCanvas(card, { scale: CARD_W / card.offsetWidth, filter: (n) => !(n instanceof HTMLElement && n.dataset.noshot != null) })
const URL_RE = /url\((['"]?)([^'")]+)\1\)/g
const dataUrls = new Map<string, Promise<string>>()
function dataUrl(url: string): Promise<string> {
let p = dataUrls.get(url)
if (!p) {
p = fetch(url)
.then((r) => {
if (!r.ok) throw new Error(`font ${r.status} ${url}`)
return r.blob()
})
.then((b) => new Promise<string>((resolve, reject) => {
const fr = new FileReader()
fr.onload = () => resolve(fr.result as string)
fr.onerror = () => reject(fr.error)
fr.readAsDataURL(b)
}))
p.catch(() => dataUrls.delete(url))
dataUrls.set(url, p)
}
return p
}
// "U+AC00-AC5F, U+4??" 가 text 의 글자를 하나라도 덮는지
function covers(range: string, codes: number[]) {
if (!range) return true
return range.split(',').some((part) => {
const [a, b] = part.trim().replace(/^u\+/i, '').split('-')
const lo = parseInt(a.replace(/\?/g, '0'), 16)
const hi = parseInt((b ?? a).replace(/\?/g, 'f'), 16)
return codes.some((c) => c >= lo && c <= hi)
})
}
/**
* 카드 글자에 필요한 웹폰트 조각만 data URL 로 넣은 @font-face.
* 이미지는 SVG 로 그려져 문서 폰트를 못 쓰므로 직접 넣어야 글꼴이 안 깨진다 (한글 폰트는 조각 수백 개라 전부 넣지 않는다).
*/
async function fontCss(text: string): Promise<string> {
const codes = [...new Set(Array.from(text, (ch) => ch.codePointAt(0) ?? 0))]
const rules: { css: string; base: string }[] = []
for (const sheet of Array.from(document.styleSheets)) {
let list: CSSRuleList
try {
list = sheet.cssRules
} catch (e) {
console.warn('[share] font css unreadable', sheet.href, e)
continue
}
for (const r of Array.from(list)) {
if (r instanceof CSSFontFaceRule && covers(r.style.getPropertyValue('unicode-range'), codes)) rules.push({ css: r.cssText, base: sheet.href ?? location.href })
}
}
const out = await Promise.all(
rules.map(async ({ css, base }) => {
const urls = [...css.matchAll(URL_RE)].map((m) => m[2])
const data = await Promise.all(urls.map((u) => dataUrl(new URL(u, base).href)))
let i = 0
return css.replace(URL_RE, () => `url("${data[i++]}")`)
}),
)
return out.join('\n')
}
// 다른 사이트 사진은 브라우저가 픽셀을 못 읽는 경우가 있어 백엔드가 대신 받아 준다. 허용 여부는 백엔드(IMAGE_PROXY_HOSTS)가 정한다
function viaProxy(url: string): Promise<string | false> {
if (!URL.canParse(url)) return Promise.resolve(false)
const u = new URL(url)
if (u.origin === location.origin || !u.protocol.startsWith('http')) return Promise.resolve(false)
return dataUrl(`${API_BASE_URL}/v1/image?url=${encodeURIComponent(url)}`).catch((e: unknown) => {
console.warn('[share] image proxy', url, e)
return false as const
})
}
type Box = { x: number; y: number; w: number; h: number }
// 카드 자리. 2장이면 세로 이미지는 지그재그, 나머지는 나란히(오른쪽을 조금 내려) 놓는다
function place(n: number, aspect: number, top: number, bottom: number): Box[] {
const room = bottom - top
if (n === 1) {
const w = Math.min(W - SIDE * 3, room / aspect)
const h = w * aspect
return [{ x: (W - w) / 2, y: top + (room - h) / 2, w, h }]
}
if (room / W > 1.1) {
const h = Math.min(room / 2, ((W - SIDE * 2) * 0.52) * aspect)
const w = h / aspect
const y = top + (room - h * 2) / 2
return [{ x: SIDE, y, w, h }, { x: W - SIDE - w, y: y + h, w, h }]
}
const gap = 40
const w = Math.min((W - SIDE * 2 - gap) / 2, room / aspect / 1.08)
const h = w * aspect
const y = top + (room - h * 1.08) / 2
return [{ x: W / 2 - gap / 2 - w, y, w, h }, { x: W / 2 + gap / 2, y: y + h * 0.08, w, h }]
}
function badge(ctx: CanvasRenderingContext2D, x: number, y: number, n: number) {
ctx.beginPath()
ctx.arc(x, y, 30, 0, Math.PI * 2)
ctx.fillStyle = '#ff7a45'
ctx.fill()
ctx.fillStyle = '#fff'
ctx.font = LOGO(36)
ctx.textBaseline = 'middle'
ctx.fillText(String(n), x, y + 2)
ctx.textBaseline = 'alphabetic'
}
/** 게시물 슬라이드(최대 2장)를 고른 크기의 PNG 한 장으로 만든다 */
export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize; sky: string; sub: string; host: string }): Promise<Blob> {
const z = SHARE_SIZES[opts.size]
const cards = slides.slice(0, 2)
if (!cards.length) throw new Error('no slide to capture')
await Promise.all([
document.fonts.load(LOGO(z.logoPx), '날씨각'),
document.fonts.load(LOGO(z.hostPx), opts.host),
document.fonts.load(LOGO(36), '12'),
document.fonts.load(SANS(z.subPx), opts.sub),
document.fonts.load(SANS(z.labelPx), PILL_LABEL),
])
const css = await fontCss(cards.map((c) => c.textContent ?? '').join(''))
const aspect = cards[0].offsetHeight / cards[0].offsetWidth
const boxes = place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50)
const shots = await Promise.all(cards.map((c, i) => domToCanvas(c, { scale: boxes[i].w / c.offsetWidth, filter: keep, font: css ? { cssText: css } : false, fetchFn: viaProxy })))
const canvas = document.createElement('canvas')
canvas.width = W
canvas.height = H
canvas.height = z.h
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('canvas 2d context unavailable')
const dark = opts.sky === 'night'
const [c1, c2, c3] = SKY[opts.sky] ?? SKY.day
const bg = ctx.createLinearGradient(0, 0, 0, H)
const bg = ctx.createLinearGradient(0, 0, 0, z.h)
bg.addColorStop(0, c1)
bg.addColorStop(0.45, c2)
bg.addColorStop(1, c3)
ctx.fillStyle = bg
ctx.fillRect(0, 0, W, H)
ctx.fillRect(0, 0, W, z.h)
ctx.textAlign = 'center'
ctx.fillStyle = '#ff7a45'
ctx.font = '84px Jua, sans-serif'
ctx.fillText('날씨각', W / 2, 230)
ctx.font = LOGO(z.logoPx)
ctx.fillText('날씨각', W / 2, z.logoY)
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2)
const cardH = (shot.height / shot.width) * CARD_W
const x = (W - CARD_W) / 2
const y = (H - cardH) / 2 + 20
const r = 40 * (boxes[0].w / 900)
shots.forEach((shot, i) => {
const b = boxes[i]
ctx.save()
ctx.shadowColor = 'rgb(40 48 74 / 0.25)'
ctx.shadowBlur = 50
ctx.shadowOffsetY = 20
roundRect(ctx, b.x, b.y, b.w, b.h, r)
ctx.fillStyle = '#fff'
ctx.fill()
ctx.restore()
ctx.save()
roundRect(ctx, b.x, b.y, b.w, b.h, r)
ctx.clip()
ctx.drawImage(shot, b.x, b.y, b.w, b.h)
ctx.restore()
})
if (shots.length > 1) boxes.forEach((b, i) => badge(ctx, b.x + 6, b.y + 6, i + 1))
// 주소 알약: [오늘 내 동네 각 보기 host]
ctx.font = SANS(z.labelPx)
const lw = ctx.measureText(PILL_LABEL).width
ctx.font = LOGO(z.hostPx)
const hw = ctx.measureText(opts.host).width
const gap = 20
const pw = Math.min(W - SIDE * 2, lw + gap + hw + 96)
const px = (W - pw) / 2
ctx.save()
ctx.shadowColor = 'rgb(40 48 74 / 0.25)'
ctx.shadowBlur = 60
ctx.shadowOffsetY = 24
roundRect(ctx, x, y, CARD_W, cardH, 48)
ctx.shadowColor = 'rgb(40 48 74 / 0.14)'
ctx.shadowBlur = 30
ctx.shadowOffsetY = 10
roundRect(ctx, px, z.pillY - z.pillH / 2, pw, z.pillH, z.pillH / 2)
ctx.fillStyle = '#fff'
ctx.fill()
ctx.restore()
ctx.save()
roundRect(ctx, x, y, CARD_W, cardH, 48)
ctx.clip()
ctx.drawImage(shot, x, y, CARD_W, cardH)
ctx.restore()
ctx.fillStyle = dark ? '#f1f3ff' : '#28304a'
ctx.font = '60px Jua, sans-serif'
ctx.fillText(opts.title, W / 2, y + cardH + 120, W - 120)
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = 'bold 38px "Pretendard Variable", sans-serif'
ctx.fillText(opts.sub, W / 2, y + cardH + 190, W - 120)
ctx.textAlign = 'left'
ctx.textBaseline = 'middle'
ctx.fillStyle = '#5a6380'
ctx.font = SANS(z.labelPx)
ctx.fillText(PILL_LABEL, px + 48, z.pillY + 2)
ctx.fillStyle = '#ff7a45'
ctx.font = LOGO(z.hostPx)
ctx.fillText(opts.host, px + 48 + lw + gap, z.pillY + 4, pw - 96 - lw - gap)
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'))
}
+5
View File
@@ -16,6 +16,7 @@
word-break: keep-all;
overflow-wrap: break-word;
-webkit-text-size-adjust: 100%;
touch-action: manipulation;
}
body {
@apply bg-page font-sans text-ink antialiased;
@@ -28,6 +29,10 @@
user-select: text;
-webkit-user-select: text;
}
/* 아이폰 사파리는 16px 보다 작은 입력칸을 누르면 화면을 확대한다 */
:is(input, textarea, select) {
font-size: max(16px, 1em);
}
:focus-visible {
outline: 3px solid var(--color-rain);
outline-offset: 3px;
+3
View File
@@ -5,6 +5,9 @@ import './index.css'
import './api/setup'
import App from './App.tsx'
// iOS는 user-scalable=no를 무시해서 두 손가락 확대를 직접 막는다
for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false })
// 칩·지역·검색어를 바꿔 다시 받는 동안 이전 결과를 그대로 두어 화면이 비거나 접히지 않게 한다
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } },