Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96cbd19c61 | ||
|
|
0a16c5329d | ||
|
|
aad8784b48 | ||
|
|
3c9b163dd4 | ||
|
|
b0cd5ef1ef | ||
|
|
0d6ab29552 | ||
|
|
ba94a381a9 | ||
|
|
882932a51b | ||
|
|
a68268234d | ||
|
|
2ca060b626 | ||
|
|
3975e41f56 | ||
|
|
646a45c88e | ||
|
|
e0d2ad2c9b | ||
|
|
422e354f61 | ||
|
|
0aeceac257 | ||
|
|
b586db0de7 | ||
|
|
599ef05dcf | ||
|
|
92cfeabe19 | ||
|
|
e270261e32 | ||
|
|
2b1b929f8f | ||
|
|
3712c7561a | ||
|
|
0b536e1f90 | ||
|
|
260ded8c79 | ||
|
|
012d8a4821 | ||
|
|
ee46a101db | ||
|
|
a21283651e | ||
|
|
e28a2e297e | ||
|
|
043210c049 | ||
|
|
29700f9d76 | ||
|
|
d95c69e3b7 | ||
|
|
fd4a00bcf7 | ||
|
|
18a7cffb39 | ||
|
|
8a7b269c04 | ||
|
|
114c87341e | ||
|
|
1990a1f998 | ||
|
|
c0e0363759 | ||
|
|
a74e3b49d0 | ||
|
|
35cd7695fa | ||
|
|
39f11d1327 | ||
|
|
2621db0450 | ||
|
|
a8871b9231 | ||
|
|
8f32999261 | ||
|
|
65909b40ad | ||
|
|
2720a23483 | ||
|
|
4daad2ecc5 | ||
|
|
d020d27715 | ||
|
|
c0ba463e54 | ||
|
|
92620c537b | ||
|
|
055eec69ef | ||
|
|
8a677a766d | ||
|
|
db233d8ffc | ||
|
|
5c05824ce0 | ||
|
|
43e1925d70 | ||
|
|
9a82cfbedc | ||
|
|
1324898a71 | ||
|
|
b91212b9e1 | ||
|
|
66a73a4756 | ||
|
|
767ccf029a | ||
|
|
72301e9f10 | ||
|
|
0b8eb84b55 | ||
|
|
0a4b210e6c | ||
|
|
57cad25f32 | ||
|
|
b023d55901 | ||
|
|
aa774c2a44 | ||
|
|
c94f7263d8 |
No files matched your search
@@ -94,7 +94,13 @@
|
||||
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` |
|
||||
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` |
|
||||
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
|
||||
| [ ] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [x] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 → 10/12 D4-2로 결정(해 안 점수 + 문장 두 줄은 서버 값 그대로 + 상태 한 줄 + 하루 흐름 칸, 높이는 지금 그대로 약 400px) | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
|
||||
| [x] | **[결정 필요]** 히어로 D4-2 상태 한 줄 — ① 습도는 서버가 %만 줘서 단계 기준을 새로 정해야 함 ② 불쾌지수 '불쾌'처럼 판정 이름을 그대로 쓸지 ③ 미세먼지·자외선은 늘 보일지, 조심할 때만 보일지 → 10/12 결정: 습도 건조(30% 미만)·보통(60% 이하)·습함, 불쾌지수 단계 이름 그대로, 늘 4개(밤엔 자외선 빼기) | 히어로 D4-2 시안 | `backend/services/hero_stats.py`, `backend/services/feed_service.py`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [ ] | **[결정 필요]** 각 목록 '지금 아님' 문구 — 계절이 아니라 각 시간대(등산 7~12시·피크닉 11~16시)가 지났다는 뜻인데 '가을' 표시 옆에 있어 비활성처럼 읽힘. 그 각의 시간('오전에 좋아요' 등)으로 바꿀지 | 사용자 지적 | `frontend/src/b/GakPage.tsx`, `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | **[결정 필요]** 계절별 각 늘리기 — 지금 '가을' 표시는 `is_core` 4개(피크닉·등산·캠핑·별보기)에 글자로 박혀 있고 계절 전환이 없음. 계절마다 각 후보 목록을 만들어 검토받고, 계절 필드로 바꾸기 → 10/12 `months` 칸 + 새 각 12개, 계절 표시는 서버 `season` | 사용자 요청 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` |
|
||||
| [ ] | 운영 DB에 `index_definition.months` 칸 추가 — `deploy.sh` 가 배포 때 `init.sql`(`ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]';`)과 `load_seed.py` 를 돌려서 자동으로 들어감. 배포 뒤 각 탭에 계절 표시가 나오는지만 확인 | 계절 각 | `backend/postgres-init/init.sql`, `deploy.sh` |
|
||||
| [ ] | **[검토 필요]** 새 각 12개 문구 — 설명·한 줄 문장(0/30/60/80)·한계 문구, '제철 아님' 표시 문구 | 계절 각 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` |
|
||||
| [ ] | 새 각 전용 아이콘 — 꽃구경(화분)·이불빨래/실내건조(빨래)·빙수(아이스커피)·한강밤바람(야장)·억새(볏단)·해돋이(노을)·붕어빵/군고구마(고구마)는 있는 그림 재사용 중 | 계절 각 | `frontend/public/icons/` |
|
||||
| [x] | 댓글 좋아요 실패 시 알림 없음 (연결·서버 오류면 줄에 안내, 지워진 댓글이면 목록 새로고침) (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) |
|
||||
| [x] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° → 10/7 노을 탭 다시 기획으로 대체: 점수 대신 하늘 상황 5가지, 결론은 상황 기준 | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` |
|
||||
| [x] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
|
||||
@@ -114,7 +120,7 @@
|
||||
| [x] | 히어로 두 칸을 상황별로 고름(비→미세먼지→자외선→일교차→체감→불쾌지수, 모자라면 기본값), 아이콘·색도 상태별 (시안 A, 사용자 결정). 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
| [x] | 검색 노출 1단계: 메타는 `index.html` 하나로 유지 + canonical, `robots.txt`·`sitemap.xml`(메인 한 줄) 추가 — 탭별 HTML로 나누는 안은 효과(탭별 공유 미리보기·탭별 색인)가 작아 보류. 도메인 `weather.o2o.kr` 고정이라 바뀌면 두 파일도 수정 | 10/8 논의 | `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml` |
|
||||
| [ ] | **[보류]** AEO·일반 검색어 유입 — 본문이 HTML에 없어 네이버 Yeti·AI 크롤러(GPTBot 등)는 메타만 읽고, 일반 검색어("세차하기 좋은 날씨" 등)는 메타만으로 순위에 못 듦. 지금 탭 내용은 지역별·매일 바뀌는 값이라 색인돼도 금방 틀림. 하려면 검색어용 페이지(각 기준·월별 노을 시간·노을 명소·계절 글·월별 행사)를 새로 만들어야 함 → 기획 결정 필요. 계절 이야기 글은 지역 무관이라 글마다 주소만 붙이면 바로 후보 | 10/8 논의 | [검색 유입 기획](https://claude.ai/artifact/SKz9SipYyguERGF8weUpZs), [검색어 리서치](https://claude.ai/artifact/Eu5ax3DbR9SdnhKdMRzE3p) |
|
||||
| [ ] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 | 등록·제출 없으면 새 도메인은 색인이 늦음 | https://search.google.com/search-console , https://searchadvisor.naver.com |
|
||||
| [x] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 (둘 다 등록됨, 10/13 확인) | 등록·제출 없으면 새 도메인은 색인이 늦음 | https://search.google.com/search-console , https://searchadvisor.naver.com |
|
||||
| [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% 등)은 추정값. 추천안: 서쪽이 트인 공개 웹캠·CCTV 6~8곳을 워커가 매일 '가장 붉을 때' 시각에 캡처하고, 같은 날 13시 기준 예보(상황·판정)를 따로 남김. 사람이 주 1회 사진에 잿빛/은은/고움/붉음 라벨(30분 내외) → 판정(나가 볼 만해요/애매/쉬어요) 3×3 적중표, 특히 '나가 볼 만해요' 적중률(목표 70%↑). 6~8주(약 300장)면 기준값 조정 가능. 비용 0원, 테이블 1개+워커 잡 1개+라벨 CSV로 2~3일. 결정할 것: 웹캠 출처·이용 조건, 라벨 담당 | 노을 탭 다시 기획 (10/7). 사용자 '예뻤어요/별로'는 출시 전엔 표본이 없고 출시 후 보조 지표로, 기상청 ASOS 운량은 전운량·중하층운량만이라 구름 입력 검증용이지 노을이 예뻤는지는 못 알려줌, 인스타 해시태그는 예쁜 날만 올라와 '쉬어요' 검증 불가·수집 약관 문제. `sky_score`는 갱신 때 덮어쓰고 7일 뒤 지워져 지금은 과거 예보가 안 남음 | `backend/services/calc/sky_score.py` (`situation`), `backend/services/sky_service.py`, `backend/scheduler/jobs.py` |
|
||||
|
||||
@@ -185,6 +185,7 @@ class IndexDefinition(Base):
|
||||
sentences: Mapped[dict] = mapped_column(JSONB)
|
||||
sort_order: Mapped[int] = mapped_column(SmallInteger)
|
||||
priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2")
|
||||
months: Mapped[list] = mapped_column(JSONB, default=list, server_default="[]") # 제철 달. 비면 일 년 내내
|
||||
|
||||
|
||||
class IndexScore(Base):
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import html
|
||||
|
||||
|
||||
def hour_label(h: int) -> str:
|
||||
if h == 0:
|
||||
return "자정"
|
||||
@@ -35,3 +38,10 @@ _COMPASS = ("북", "북북동", "북동", "동북동", "동", "동남동", "남
|
||||
def compass(deg: float) -> str:
|
||||
"""방위각 → 16방위 이름. 263 → "서" """
|
||||
return _COMPASS[round(deg / 22.5) % 16]
|
||||
|
||||
|
||||
def plain(s: str) -> str:
|
||||
"""HTML 문자 참조를 다 푼다. 두 번 인코딩돼 오는 출처도 있어("<") 더 안 바뀔 때까지."""
|
||||
while (u := html.unescape(s)) != s:
|
||||
s = u
|
||||
return s
|
||||
@@ -31,6 +31,9 @@ class Settings(BaseSettings):
|
||||
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
|
||||
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
|
||||
|
||||
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
|
||||
frontend_internal_url: str = "http://frontend"
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
jwt_access_minutes: int = 60
|
||||
|
||||
@@ -5,6 +5,7 @@ from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Event, Holiday, Place, WeatherDaily
|
||||
from common.utils.text import plain
|
||||
|
||||
|
||||
class WeekCRUD:
|
||||
@@ -46,6 +47,8 @@ class WeekCRUD:
|
||||
async def upsert_events(self, s: AsyncSession, rows: list[dict]) -> None:
|
||||
if not rows:
|
||||
return
|
||||
# 출처마다 이름에 "<" 같은 HTML 문자가 섞여 와서, 넣기 전에 푼다
|
||||
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"])} for r in rows]
|
||||
stmt = insert(Event).values(rows)
|
||||
await s.execute(stmt.on_conflict_do_update(
|
||||
index_elements=["source_id"],
|
||||
|
||||
@@ -292,12 +292,14 @@ CREATE TABLE IF NOT EXISTS public.index_definition (
|
||||
limit_description VARCHAR(200) NULL, -- 반영 못 한 것
|
||||
sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes}
|
||||
sort_order SMALLINT NOT NULL DEFAULT 0,
|
||||
priority SMALLINT NOT NULL DEFAULT 2 -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
priority SMALLINT NOT NULL DEFAULT 2, -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다
|
||||
months JSONB NOT NULL DEFAULT '[]' -- 제철 달 [9, 10, 11]. 비어 있으면 일 년 내내. 제철이 아니면 순위·피드에서 빠진다
|
||||
);
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 2;
|
||||
ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]';
|
||||
|
||||
-- 노을 명소.
|
||||
CREATE TABLE IF NOT EXISTS public.sunset_spot (
|
||||
|
||||
@@ -14,6 +14,7 @@ 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
|
||||
from router.v1.season.season import router as season_router
|
||||
from router.v1.seo.seo import router as seo_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.watch.watch import router as watch_router
|
||||
from router.v1.weather.weather import router as weather_router
|
||||
@@ -43,6 +44,7 @@ app.include_router(auth_router)
|
||||
app.include_router(reaction_router)
|
||||
app.include_router(watch_router)
|
||||
app.include_router(image_router)
|
||||
app.include_router(seo_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
|
||||
@@ -11,6 +11,7 @@ class Row(WebPacketProtocol):
|
||||
label: str
|
||||
value: str
|
||||
place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)")
|
||||
level: Optional[int] = Field(default=None, description="자외선 단계 1 낮음 ~ 5 위험. 있으면 앱이 값을 단계 색 칩으로 그린다")
|
||||
|
||||
|
||||
class HourCell(WebPacketProtocol):
|
||||
@@ -142,6 +143,8 @@ class TopIndex(WebPacketProtocol):
|
||||
rank: int
|
||||
summary: Optional[str] = None
|
||||
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
|
||||
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
|
||||
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
|
||||
|
||||
|
||||
class HeroStat(WebPacketProtocol):
|
||||
@@ -162,11 +165,13 @@ class Hero(WebPacketProtocol):
|
||||
rain_2h_text: Optional[str] = None
|
||||
will_rain_2h: Optional[bool] = None
|
||||
weather_score: Optional[int] = None
|
||||
weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}")
|
||||
top1: Optional[TopIndex] = None
|
||||
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="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저")
|
||||
status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)")
|
||||
|
||||
|
||||
class BandEvent(WebPacketProtocol):
|
||||
|
||||
@@ -17,7 +17,7 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
d = i.definition
|
||||
return IndexSummary(
|
||||
index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun,
|
||||
is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
is_core=d.is_core, season=i.season, in_season=i.in_season, score=i.score.score, rank=i.rank, summary=i.score.summary,
|
||||
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend],
|
||||
active=i.active, slot=i.slot, slots=[SlotPoint(slot=k, label=SLOT_LABEL[k], score=v) for k, v in i.slots.items()],
|
||||
)
|
||||
@@ -27,7 +27,7 @@ def _summary(i: IndexItem, today: date) -> IndexSummary:
|
||||
async def list_indices(
|
||||
region: str = Query(..., description="구 행정코드"),
|
||||
category: Optional[IndexCategory] = Query(None),
|
||||
core: bool = Query(False, description="이번 계절 핵심 지수만"),
|
||||
core: bool = Query(False, description="지금 제철인 각만"),
|
||||
service: IndexService = Depends(),
|
||||
) -> Res_IndexList:
|
||||
err, board = await service.board(region)
|
||||
@@ -35,7 +35,7 @@ async def list_indices(
|
||||
return Res_IndexList(result=error_info(err))
|
||||
items = [_summary(i, board.day) for i in board.items]
|
||||
top3 = [_summary(i, board.day) for i in board.ranked[:3]]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)]
|
||||
filtered = [x for x in items if (category is None or x.category is category) and (not core or x.season)]
|
||||
return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered)
|
||||
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ class IndexSummary(WebPacketProtocol):
|
||||
category: IndexCategory
|
||||
is_fun: bool
|
||||
is_core: bool
|
||||
season: Optional[str] = Field(default=None, description="지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음")
|
||||
in_season: bool = Field(default=True, description="false 면 제철이 아니라 순위 밖, 목록 맨 끝")
|
||||
score: int
|
||||
rank: int
|
||||
summary: str
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
from fastapi import APIRouter, Depends, Path
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from common.enums import ErrorType
|
||||
from services.seo_service import SeoService
|
||||
|
||||
router = APIRouter(prefix="/v1/seo", tags=["seo"])
|
||||
|
||||
_SLUG = r"^[a-z]+$"
|
||||
|
||||
|
||||
@router.get("/today/{sido}/{place}", response_class=HTMLResponse, summary="지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)")
|
||||
async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
err, html = await service.page(f"today/{sido}/{place}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
|
||||
async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
|
||||
err, html = await service.page(f"today/{sido}/{place}/{gu}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
@@ -9,6 +9,7 @@ class WatchNow(WebPacketProtocol):
|
||||
temp_c: Optional[float] = None
|
||||
icon: Optional[str] = None
|
||||
rain_2h: Optional[bool] = None
|
||||
thunder: Optional[bool] = None # 2시간 안에 낙뢰 예보
|
||||
text: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ async def get_watch_summary(
|
||||
for s in today.slots if s.at > now
|
||||
]
|
||||
if now_w is not None:
|
||||
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "text": now_w.rain_2h_text})
|
||||
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "thunder": now_w.thunder_2h, "text": now_w.rain_2h_text})
|
||||
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
||||
|
||||
if board is not None:
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""프론트 지역 검색 페이지 목록(frontend/seo/region.json)을 seed/region.csv 로 다시 만든다.
|
||||
|
||||
region.csv 가 바뀌면 실행: python backend/scripts/gen_region_pages.py
|
||||
"""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SRC = os.path.join(ROOT, "backend", "seed", "region.csv")
|
||||
OUT = os.path.join(ROOT, "frontend", "seo", "region.json")
|
||||
|
||||
SIDO = dict(서울='seoul', 부산='busan', 대구='daegu', 인천='incheon', 광주='gwangju', 대전='daejeon', 울산='ulsan', 세종='sejong', 경기='gyeonggi', 강원='gangwon', 충북='chungbuk', 충남='chungnam', 전북='jeonbuk', 전남='jeonnam', 경북='gyeongbuk', 경남='gyeongnam', 제주='jeju')
|
||||
R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin 동대문 dongdaemun 중랑 jungnang 성북 seongbuk 강북 gangbuk 도봉 dobong 노원 nowon 은평 eunpyeong 서대문 seodaemun 마포 mapo 양천 yangcheon 강서 gangseo 구로 guro 금천 geumcheon 영등포 yeongdeungpo 동작 dongjak 관악 gwanak 서초 seocho 강남 gangnam 송파 songpa 강동 gangdong
|
||||
목포 mokpo 여수 yeosu 순천 suncheon 나주 naju 광양 gwangyang 동 dong 서 seo 남 nam 북 buk 광산 gwangsan 담양 damyang 곡성 gokseong 구례 gurye 고흥 goheung 보성 boseong 화순 hwasun 장흥 jangheung 강진 gangjin 해남 haenam 영암 yeongam 무안 muan 함평 hampyeong 영광 yeonggwang 장성 jangseong 완도 wando 진도 jindo 신안 sinan
|
||||
영도 yeongdo 부산진 busanjin 동래 dongnae 해운대 haeundae 사하 saha 금정 geumjeong 연제 yeonje 수영 suyeong 사상 sasang 기장 gijang 수성 suseong 달서 dalseo 달성 dalseong 군위 gunwi
|
||||
제물포 jemulpo 영종 yeongjong 미추홀 michuhol 연수 yeonsu 남동 namdong 부평 bupyeong 계양 gyeyang 서해 seohae 검단 geomdan 강화 ganghwa 옹진 ongjin 유성 yuseong 대덕 daedeok 울주 ulju 세종특별자치 sejong
|
||||
수원 suwon 성남 seongnam 의정부 uijeongbu 안양 anyang 부천 bucheon 광명 gwangmyeong 평택 pyeongtaek 동두천 dongducheon 안산 ansan 고양 goyang 과천 gwacheon 구리 guri 남양주 namyangju 오산 osan 시흥 siheung 군포 gunpo 의왕 uiwang 하남 hanam 용인 yongin 파주 paju 이천 icheon 안성 anseong 김포 gimpo 화성 hwaseong 광주 gwangju 양주 yangju 포천 pocheon 여주 yeoju 연천 yeoncheon 가평 gapyeong 양평 yangpyeong
|
||||
청주 cheongju 충주 chungju 제천 jecheon 보은 boeun 옥천 okcheon 영동 yeongdong 증평 jeungpyeong 진천 jincheon 괴산 goesan 음성 eumseong 단양 danyang
|
||||
천안 cheonan 공주 gongju 보령 boryeong 아산 asan 서산 seosan 논산 nonsan 계룡 gyeryong 당진 dangjin 금산 geumsan 부여 buyeo 서천 seocheon 청양 cheongyang 홍성 hongseong 예산 yesan 태안 taean
|
||||
포항 pohang 경주 gyeongju 김천 gimcheon 안동 andong 구미 gumi 영주 yeongju 영천 yeongcheon 상주 sangju 문경 mungyeong 경산 gyeongsan 의성 uiseong 청송 cheongsong 영양 yeongyang 영덕 yeongdeok 청도 cheongdo 고령 goryeong 성주 seongju 칠곡 chilgok 예천 yecheon 봉화 bonghwa 울진 uljin 울릉 ulleung
|
||||
창원 changwon 진주 jinju 통영 tongyeong 사천 sacheon 김해 gimhae 밀양 miryang 거제 geoje 양산 yangsan 의령 uiryeong 함안 haman 창녕 changnyeong 고성 goseong 남해 namhae 하동 hadong 산청 sancheong 함양 hamyang 거창 geochang 합천 hapcheon 제주 jeju 서귀포 seogwipo
|
||||
춘천 chuncheon 원주 wonju 강릉 gangneung 동해 donghae 태백 taebaek 속초 sokcho 삼척 samcheok 홍천 hongcheon 횡성 hoengseong 영월 yeongwol 평창 pyeongchang 정선 jeongseon 철원 cheorwon 화천 hwacheon 양구 yanggu 인제 inje 양양 yangyang
|
||||
전주 jeonju 군산 gunsan 익산 iksan 정읍 jeongeup 남원 namwon 김제 gimje 완주 wanju 진안 jinan 무주 muju 장수 jangsu 임실 imsil 순창 sunchang 고창 gochang 부안 buan'''.split()
|
||||
ROMAN = dict(zip(R[::2], R[1::2]))
|
||||
G = '''장안 jangan 권선 gwonseon 팔달 paldal 영통 yeongtong 수정 sujeong 중원 jungwon 분당 bundang 만안 manan 동안 dongan 원미 wonmi 소사 sosa 오정 ojeong 상록 sangnok 단원 danwon 덕양 deogyang 일산동 ilsandong 일산서 ilsanseo 처인 cheoin 기흥 giheung 수지 suji
|
||||
만세 manse 효행 hyohaeng 병점 byeongjeom 동탄 dongtan 상당 sangdang 서원 seowon 흥덕 heungdeok 청원 cheongwon 동남 dongnam 서북 seobuk 남 nam 북 buk 의창 uichang 성산 seongsan 마산합포 masanhappo 마산회원 masanhoewon 진해 jinhae 완산 wansan 덕진 deokjin'''.split()
|
||||
GU = dict(zip(G[::2], G[1::2]))
|
||||
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
||||
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
|
||||
pages = {}
|
||||
for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
||||
sido, *rest = row['name'].split()
|
||||
place = rest[0]
|
||||
r = dict(code=row['code'], name=row['name'], short_name=row['short_name'], lat=float(row['lat']), lon=float(row['lon']))
|
||||
path = f"{SIDO[sido]}/{ROMAN[place[:-1]]}"
|
||||
p = pages.setdefault(path, dict(path=path, name='세종시' if sido == '세종' else f'{sido} {place}', main=None, regions=[]))
|
||||
p['regions'].append(r)
|
||||
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
|
||||
p['main'] = r['code']
|
||||
# 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang
|
||||
if len(rest) == 2:
|
||||
gu = f"{path}/{GU[rest[1][:-1]]}"
|
||||
pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r])
|
||||
out = list(pages.values())
|
||||
assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']]
|
||||
assert sum(len(p['regions']) for p in out if p['path'].count('/') == 1) == 256
|
||||
json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
||||
print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities')
|
||||
@@ -55,6 +55,8 @@ class Context:
|
||||
wind_warning: bool
|
||||
lookahead_rain_prob: int
|
||||
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
||||
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
||||
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -203,13 +205,17 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
|
||||
return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), (
|
||||
f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
if kind == "sunrise_score":
|
||||
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), (
|
||||
f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
|
||||
)
|
||||
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점"
|
||||
|
||||
|
||||
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
|
||||
_WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"}
|
||||
_HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"}
|
||||
_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "sunrise_score": "일출 하늘 예쁨", "fixed": "시간대 알맞음"}
|
||||
# Open-Meteo 보조 축. 비중이 있는 지수에만 나온다.
|
||||
_OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"}
|
||||
|
||||
@@ -224,7 +230,7 @@ def axis_label(axis: str, rules: dict) -> str:
|
||||
rule = rules.get("air", _AIR_RULE)
|
||||
return "공기 탁함" if rule["full"] > rule["zero"] else "공기 맑음"
|
||||
table = {"temp": _TEMP_LABEL, "wind": _WIND_LABEL, "humidity": _HUMIDITY_LABEL, "time": _TIME_LABEL}[axis]
|
||||
return table[rules[axis]["type"]]
|
||||
return rules[axis].get("label") or table[rules[axis]["type"]]
|
||||
|
||||
|
||||
def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
@@ -244,15 +250,21 @@ def _zero(rules: list[dict], agg: dict) -> tuple[Optional[str], Optional[int]]:
|
||||
|
||||
_FIELD_TEXT = {
|
||||
"rain_prob": "비 확률", "wind_ms": "바람", "feels_c": "체감", "pm25": "초미세먼지", "cloudy_ratio": "흐린 하늘",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도",
|
||||
"gust_ms": "돌풍", "ground_c": "지표면 온도", "humidity": "습도",
|
||||
}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°"}
|
||||
_UNIT = {"rain_prob": "%", "wind_ms": "m/s", "feels_c": "°", "pm25": "㎍/㎥", "cloudy_ratio": "%", "gust_ms": "m/s", "ground_c": "°", "humidity": "%"}
|
||||
|
||||
|
||||
def _cond(r: dict) -> tuple[str, str, str]:
|
||||
"""조건 하나를 (이유, '…이거나', '…이면') 꼴로."""
|
||||
if r["field"] == "warning":
|
||||
return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면"
|
||||
if r["field"] == "snow":
|
||||
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
|
||||
if r["field"] == "rain":
|
||||
return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면"
|
||||
if r["field"] == "rain_before":
|
||||
return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면"
|
||||
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
|
||||
return f"{base}이라", f"{base}이거나", f"{base}이면"
|
||||
|
||||
@@ -333,6 +345,9 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)),
|
||||
"warning": "wind" if ctx.wind_warning else None,
|
||||
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
|
||||
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
|
||||
"rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)),
|
||||
"rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no",
|
||||
}
|
||||
reason, cap = _zero(definition.zero_rules, agg)
|
||||
if reason is not None:
|
||||
@@ -351,7 +366,7 @@ def hour_temp(lo: float, hi: float, hour: int) -> float:
|
||||
|
||||
|
||||
def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]:
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다."""
|
||||
"""중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률과 눈(늘 없음으로 봄)만 본다."""
|
||||
if fc.temp_min_c is None or fc.temp_max_c is None:
|
||||
return None
|
||||
best: Optional[Result] = None
|
||||
@@ -381,7 +396,10 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
factors = {a: v for a, (v, _) in scored.items()}
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = _weighted(factors, weights)
|
||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] == "rain_prob"], {"rain_prob": max_prob})
|
||||
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
||||
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
|
||||
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
|
||||
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
|
||||
if reason is not None:
|
||||
score = min(score, cap)
|
||||
mid = hours[len(hours) // 2]
|
||||
|
||||
@@ -11,7 +11,9 @@ VILAGE_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilag
|
||||
ULTRA_URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst"
|
||||
WARNING_URL = "https://apis.data.go.kr/1360000/WthrWrnInfoService/getPwnCd"
|
||||
_SKY = {"1": Sky.CLEAR, "3": Sky.PARTLY, "4": Sky.CLOUDY}
|
||||
_PTY = {"0": RainType.NONE, "1": RainType.RAIN, "2": RainType.SLEET, "3": RainType.SNOW, "4": RainType.SHOWER}
|
||||
# 단기예보 0~4, 초단기예보는 5 빗방울 · 6 빗방울눈날림 · 7 눈날림이 더 있다
|
||||
_PTY = {"0": RainType.NONE, "1": RainType.RAIN, "2": RainType.SLEET, "3": RainType.SNOW, "4": RainType.SHOWER,
|
||||
"5": RainType.RAIN, "6": RainType.SLEET, "7": RainType.SNOW}
|
||||
_REQUIRED = ("TMP", "SKY", "PTY", "POP", "REH")
|
||||
|
||||
|
||||
@@ -77,13 +79,13 @@ def day_start_base(day: date) -> datetime:
|
||||
|
||||
|
||||
def parse_ultra(items: list[dict]) -> list[dict]:
|
||||
"""초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온."""
|
||||
"""초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온·낙뢰(LGT, 0 이면 없음)."""
|
||||
by_time: dict[datetime, dict[str, str]] = {}
|
||||
for it in items:
|
||||
at = datetime.strptime(it["fcstDate"] + it["fcstTime"], "%Y%m%d%H%M").replace(tzinfo=KST)
|
||||
by_time.setdefault(at, {})[it["category"]] = it["fcstValue"]
|
||||
return [
|
||||
{"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"])}
|
||||
{"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"]), "lightning": parse_amount(v.get("LGT", "")) > 0}
|
||||
for at, v in sorted(by_time.items())
|
||||
if "PTY" in v and "T1H" in v
|
||||
]
|
||||
|
||||
@@ -13,7 +13,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, next_vilage_available, now_kst
|
||||
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst
|
||||
from common.utils.text import compass, day_range, hour_label, short_day
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
@@ -30,7 +30,7 @@ from services.calc.index_calc import rank_score
|
||||
from services.calc.moon import MoonNight, nearest, night, view_line
|
||||
from services.calc.sky_score import GRADE_LABEL, sky_title
|
||||
from services.calc.sun import sun_times
|
||||
from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label
|
||||
from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level
|
||||
from services.index_service import IndexBoard, IndexItem, IndexService
|
||||
from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
@@ -117,6 +117,7 @@ _AIR_LINE = {
|
||||
AirGrade.BAD: ("공기가 탁해요,\n마스크 챙겨요", "😷 마스크 챙겨!"),
|
||||
AirGrade.VERY_BAD: ("공기가 많이 탁해요,\n바깥은 짧게", "😷 오늘은 실내로!"),
|
||||
}
|
||||
_AIR_RAIN_LINE = ("공기는 맑은데 비가 와요,\n창문은 닫아 둬요", "☔ 창문은 닫아 둬!") # 맑음·보통인데 지금~2시간 안에 비
|
||||
_AIR_ADVICE = {
|
||||
AirGrade.BAD: "KF80 마스크 쓰고, 오래 뛰는 바깥 운동은 줄여요",
|
||||
AirGrade.VERY_BAD: "외출은 줄이고 창문은 닫아 둬요. 나가면 KF94 마스크",
|
||||
@@ -130,10 +131,6 @@ def _pick(articles: list[Article], day: date) -> Optional[Article]:
|
||||
return articles[day.toordinal() % len(articles)] if articles else None
|
||||
|
||||
|
||||
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], moon: Optional[str],
|
||||
) -> HeroInput:
|
||||
@@ -142,12 +139,12 @@ def _hero_input(
|
||||
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,
|
||||
now=now, night=slot in ("evening", "night"), after_dark=slot == "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,
|
||||
moon=moon,
|
||||
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -156,12 +153,13 @@ def feed_day(now: datetime) -> date:
|
||||
|
||||
|
||||
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽."""
|
||||
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·초단기예보·미세먼지 갱신·정각(지금 구간이 줄어듦) 중 가장 빠른 쪽."""
|
||||
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, sunset + NIGHT_AFTER_SUNSET,
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)]
|
||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY,
|
||||
now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)]
|
||||
air = now.replace(minute=20, second=0, microsecond=0)
|
||||
changes.append(air if air > now else air + timedelta(hours=1))
|
||||
nxt = min(c for c in changes if c > now)
|
||||
@@ -238,7 +236,8 @@ def _by_position(posts: list[Post]) -> list[Post]:
|
||||
|
||||
def _top(i: IndexItem) -> TopIndex:
|
||||
d = i.definition
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active)
|
||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active,
|
||||
slots=i.slots, slot_ranks=i.slot_ranks)
|
||||
|
||||
|
||||
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
|
||||
@@ -324,6 +323,9 @@ class FeedService:
|
||||
async with redis_lock("lock:feed:build", ttl_sec=20):
|
||||
await build_feed_day(day, self.crud, self.season_crud, self.regions)
|
||||
res, partial = await self._assemble(region, now, day, slot, sunset_at)
|
||||
# 각을 못 낸 피드는 저장하지 않는다. 처음 온 지역은 예보를 받는 중이라 다음 요청에서 바로 채운다
|
||||
if not res.bands.top5:
|
||||
return ErrorType.SUCCESS, res
|
||||
try:
|
||||
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
|
||||
except RedisError as e:
|
||||
@@ -374,7 +376,8 @@ class FeedService:
|
||||
for p, item in zip(gak_posts, gak):
|
||||
cards.append(self._gak(p, item))
|
||||
has_warning = bool(now_w and now_w.warnings)
|
||||
items = board.items if board else []
|
||||
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
|
||||
items = [i for i in board.items if i.in_season] 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, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
|
||||
@@ -418,27 +421,29 @@ class FeedService:
|
||||
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)
|
||||
"""지금 칸의 자외선. Open-Meteo 는 3시간 칸이라 지금 시각을 넘지 않는 마지막 칸을 쓴다."""
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour - timedelta(hours=2), hour))
|
||||
rows = [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
|
||||
return float(max(rows, key=lambda r: r.forecast_at).uv_index) if rows else None
|
||||
|
||||
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, moon: Optional[tuple[MoonNight, str]] = None) -> Hero:
|
||||
top = board.ranked[0] if board and board.ranked else None
|
||||
bubble = None
|
||||
if top is not None:
|
||||
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
|
||||
bubble = f"지금은 {top.definition.name}!" if top.score.score >= 70 else "지금은 쉬어 가요"
|
||||
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
|
||||
return Hero(
|
||||
now_at=now, sky_mode=_SKY_MODE[slot],
|
||||
temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None,
|
||||
humidity=cur.humidity if cur else None,
|
||||
discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None,
|
||||
discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None,
|
||||
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,
|
||||
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
|
||||
top1=_top(top) if top else None, bubble=bubble,
|
||||
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
|
||||
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, f"{moon[0].name}, {moon[1]}" if moon else None))],
|
||||
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
|
||||
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -627,14 +632,13 @@ class FeedService:
|
||||
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)}",
|
||||
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=uv_label(float(r.uv_index)), level=uv_level(float(r.uv_index))) for r in c.uv]
|
||||
when = "점심때" if at.hour == 12 else f"{hour_label(at.hour)} 무렵"
|
||||
todo = "선크림·모자·선글라스 챙기고 그늘로 다녀요" if top >= UV_HIGH else "선크림·모자 챙겨요"
|
||||
line = f"오늘 자외선 지수 {label}\n{when} 나가면 {todo}"
|
||||
return PostData(**base, title=f"자외선 지수 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)}",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
|
||||
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
|
||||
share_messages=[f"오늘 자외선 지수 {label}, 선크림 챙겨!"])
|
||||
|
||||
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
|
||||
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
|
||||
@@ -646,11 +650,12 @@ class FeedService:
|
||||
return None
|
||||
worst = max(g for _, _, g in values)
|
||||
label = AIR_GRADE_LABEL[worst]
|
||||
rows = [Row(label=name, value=f"{v}㎍/㎥ · {AIR_GRADE_LABEL[g]}") for name, v, g in values]
|
||||
rows = [Row(label=name, value=AIR_GRADE_LABEL[g]) for name, _, g in values]
|
||||
if worst in _AIR_ADVICE:
|
||||
rows.append(Row(label="이렇게 해요", value=_AIR_ADVICE[worst]))
|
||||
line, tail = _AIR_LINE[worst]
|
||||
icon = "vent" if worst <= AirGrade.NORMAL else "cloud"
|
||||
raining = worst <= AirGrade.NORMAL and c.now_w.will_rain_2h
|
||||
line, tail = _AIR_RAIN_LINE if raining else _AIR_LINE[worst]
|
||||
icon = "umbrella" if raining else "vent" if worst <= AirGrade.NORMAL else "cloud"
|
||||
return PostData(**base, title=f"미세먼지 {label}", icon=icon, caption=f"{air.station_name} 측정소 · {air.measured_at.astimezone(KST).hour}시 기준",
|
||||
slides=[RowsSlide(kind="rows", eyebrow=f"지금 공기 · {c.region.short_name}", line=line, icon=icon, rows=rows)],
|
||||
share_messages=[f"{c.region.short_name} 지금 미세먼지 {label} {tail}"])
|
||||
|
||||
@@ -10,6 +10,9 @@ from services.air_service import GRADE_LABEL
|
||||
Tone = Literal["normal", "warn", "rain"]
|
||||
|
||||
UV_HIGH = 6.0
|
||||
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
|
||||
DISCOMFORT_MONTHS = range(6, 10) # 기상청처럼 6~9월에만. 더위 지표라 선선한 철엔 비 와도 '쾌적'으로 나온다
|
||||
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
|
||||
TEMP_SWING_C = 10.0
|
||||
WIND_CHILL_C = 3.0
|
||||
SHOWN = 1
|
||||
@@ -38,10 +41,43 @@ class HeroInput:
|
||||
temp: Optional[float] = None
|
||||
feels: Optional[float] = None
|
||||
moon: Optional[str] = None
|
||||
humidity: Optional[int] = None
|
||||
discomfort: Optional[int] = None
|
||||
after_dark: bool = False # 밤 구간(일몰 1시간 뒤~). night 는 저녁 구간까지 포함한다
|
||||
|
||||
|
||||
_UV_LABELS = ("낮음", "보통", "높음", "매우 높음", "위험")
|
||||
|
||||
|
||||
def uv_level(uv: float) -> int:
|
||||
"""기상청 자외선 단계 1 낮음 ~ 5 위험."""
|
||||
return 1 if uv < 3 else 2 if uv < 6 else 3 if uv < 8 else 4 if uv < 11 else 5
|
||||
|
||||
|
||||
def uv_label(uv: float) -> str:
|
||||
return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험"
|
||||
return _UV_LABELS[uv_level(uv) - 1]
|
||||
|
||||
|
||||
def discomfort_label(v: int) -> str:
|
||||
return "쾌적" if v < 68 else "보통" if v < MUGGY_DI else "불쾌" if v < 80 else "매우 불쾌"
|
||||
|
||||
|
||||
def humidity_label(h: int) -> str:
|
||||
return "건조" if h < HUMID_DRY else "보통" if h <= HUMID_WET else "습함"
|
||||
|
||||
|
||||
def hero_status(x: HeroInput) -> list[HeroStatItem]:
|
||||
"""히어로 상태 한 줄: 습도·불쾌지수(6~9월)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
|
||||
out: list[HeroStatItem] = []
|
||||
if x.humidity is not None:
|
||||
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
|
||||
if x.discomfort is not None and x.now.month in DISCOMFORT_MONTHS:
|
||||
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
|
||||
if not x.after_dark and x.uv is not None:
|
||||
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
|
||||
if x.air is not None:
|
||||
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal"))
|
||||
return out
|
||||
|
||||
|
||||
def _rain_value(now: datetime, at: datetime) -> str:
|
||||
|
||||
@@ -9,7 +9,7 @@ from fastapi import Depends
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import IndexDefinition, IndexScore, OpenMeteoHourly, Region, WeatherDaily, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky, SkyType, WarningType
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, now_kst
|
||||
from crud.index_crud import IndexCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
@@ -22,7 +22,7 @@ from services.calc.moon import night, up_ratio, view_line
|
||||
from services.calc.sun import sun_times
|
||||
from services.external.open_meteo import is_dark_slot
|
||||
from services.warning_service import WarningService
|
||||
from services.weather_service import WeatherService
|
||||
from services.weather_service import WeatherService, ultra_hours, with_ultra_rain
|
||||
|
||||
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
|
||||
DAYS = 3
|
||||
@@ -42,6 +42,26 @@ WEATHER_SCORE_DEF = SimpleNamespace(
|
||||
)
|
||||
|
||||
|
||||
SEASONS = ("겨울", "봄", "여름", "가을")
|
||||
|
||||
|
||||
def season_of(month: int) -> str:
|
||||
"""봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2."""
|
||||
return SEASONS[month % 12 // 3]
|
||||
|
||||
|
||||
def in_season(defn, month: int) -> bool:
|
||||
"""제철 달이 없으면 일 년 내내."""
|
||||
months = getattr(defn, "months", None)
|
||||
return not months or month in months
|
||||
|
||||
|
||||
def season_badge(defn, month: int) -> Optional[str]:
|
||||
"""제철이 정해진 각이 지금 제철이면 그 계절 이름. 일 년 내내인 각은 없음."""
|
||||
months = getattr(defn, "months", None)
|
||||
return season_of(month) if months and month in months else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class IndexItem:
|
||||
definition: IndexDefinition
|
||||
@@ -50,7 +70,10 @@ class IndexItem:
|
||||
trend: list[IndexScore]
|
||||
slot: Optional[str] = None
|
||||
slots: dict[str, int] = field(default_factory=dict)
|
||||
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
|
||||
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
|
||||
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
|
||||
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -59,6 +82,7 @@ class IndexBoard:
|
||||
day: date
|
||||
weather_score: Optional[int]
|
||||
items: list[IndexItem]
|
||||
weather_slots: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def ranked(self) -> list[IndexItem]:
|
||||
@@ -90,11 +114,12 @@ def slot_label(day: date, today: date) -> str:
|
||||
|
||||
|
||||
def window_hours(defn, day: date, region: Region) -> list[list[int]]:
|
||||
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각."""
|
||||
"""시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각. around 는 일몰·일출 시각 ±hours."""
|
||||
out = []
|
||||
for w in defn.windows:
|
||||
if w.get("around") == "sunset":
|
||||
h = sun_times(day, float(region.lat), float(region.lon)).sunset_at.astimezone(KST).hour
|
||||
if w.get("around") in ("sunset", "sunrise"):
|
||||
sun = sun_times(day, float(region.lat), float(region.lon))
|
||||
h = (sun.sunset_at if w["around"] == "sunset" else sun.sunrise_at).astimezone(KST).hour
|
||||
out.append(list(range(h - w.get("hours", 1), h + w.get("hours", 1) + 1)))
|
||||
else:
|
||||
out.append(list(range(w["from"], w["to"])))
|
||||
@@ -151,6 +176,7 @@ def windows_for(
|
||||
|
||||
|
||||
EARLY = "early" # 0~5시: 전날 밤 구간
|
||||
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
|
||||
|
||||
|
||||
def current_slot(now: datetime, sunset_at: datetime) -> str:
|
||||
@@ -161,20 +187,46 @@ def shown_slot(key: str) -> str:
|
||||
return "night" if key == EARLY else key
|
||||
|
||||
|
||||
def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
||||
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
|
||||
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
return {k: shown[k] for k in SLOTS if k in shown}
|
||||
|
||||
|
||||
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
|
||||
"""그날 비·눈 오는 시각(0~23)."""
|
||||
start = kst_midnight(day)
|
||||
return frozenset(h for h in range(24) if (r := by_at.get(start + timedelta(hours=h))) is not None and r.rain_type != RainType.NONE.value)
|
||||
|
||||
|
||||
def slot_results(
|
||||
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
|
||||
now: Optional[datetime] = None,
|
||||
) -> dict[str, Result]:
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다."""
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()}
|
||||
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다."""
|
||||
hours_by_slot = slot_hours(day, sunset_at)
|
||||
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
|
||||
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()}
|
||||
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
|
||||
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0))
|
||||
out = {}
|
||||
for key, windows in parts.items():
|
||||
result = evaluate(defn, windows, ctx)
|
||||
k_need = min(need, len(hours_by_slot[key])) if key == cur else need
|
||||
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx)
|
||||
if result is not None:
|
||||
out[key] = result
|
||||
return out
|
||||
|
||||
|
||||
def _trim_passed(hours_by_slot: dict[str, set[int]], day: date, sunset_at: datetime, now: datetime) -> Optional[str]:
|
||||
"""지금 구간에서 이미 지난 시각을 뺀다(지난 단기예보 비가 지금 점수에 남지 않게). 지금 구간 이름, 오늘이 아니면 None."""
|
||||
hour = int((now - kst_midnight(day)).total_seconds() // 3600)
|
||||
cur = next((k for k, hours in hours_by_slot.items() if hour in hours), None)
|
||||
if cur is not None:
|
||||
hours_by_slot[cur] = {h for h in hours_by_slot[cur] if h >= hour}
|
||||
return cur
|
||||
|
||||
|
||||
def _slot_json(r: Result) -> dict:
|
||||
return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes}
|
||||
|
||||
@@ -253,7 +305,7 @@ class IndexService:
|
||||
if region is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
now = now_kst()
|
||||
err, weather_score = await self.ensure(region, now)
|
||||
err, weather_parts = await self.ensure(region, now)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
today = now.date()
|
||||
@@ -264,6 +316,9 @@ class IndexService:
|
||||
if ErrorType.DB_ERROR in (err, err2):
|
||||
return ErrorType.DB_ERROR, None
|
||||
by_key = {(x.index_id, x.score_date): x for x in scores}
|
||||
month = today.month
|
||||
out_season = [d for d in defs if not in_season(d, month)]
|
||||
defs = [d for d in defs if in_season(d, month)]
|
||||
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다
|
||||
now_score: dict[int, IndexScore] = {}
|
||||
for d in defs:
|
||||
@@ -278,11 +333,11 @@ class IndexService:
|
||||
items = []
|
||||
for i, d in enumerate(ranked):
|
||||
row = by_key[(d.index_id, today)]
|
||||
parts = {shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}
|
||||
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur)
|
||||
items.append(IndexItem(
|
||||
definition=d, score=now_score[d.index_id], rank=i + 1,
|
||||
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slot=shown_slot(cur), slots={k: parts[k] for k in SLOTS if k in parts},
|
||||
slot=shown_slot(cur), slots=parts, season=season_badge(d, month),
|
||||
))
|
||||
off = sorted(
|
||||
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
|
||||
@@ -293,15 +348,28 @@ class IndexService:
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
|
||||
slots={shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False,
|
||||
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month),
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
|
||||
for k in SLOTS:
|
||||
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
|
||||
for n, i in enumerate(in_slot):
|
||||
i.slot_ranks[k] = n + 1
|
||||
# 제철이 아닌 각은 구간 순위 없이 맨 끝에
|
||||
for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order):
|
||||
row = by_key[(d.index_id, today)]
|
||||
items.append(IndexItem(
|
||||
definition=d, score=row, rank=len(items) + 1,
|
||||
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
|
||||
))
|
||||
return ErrorType.SUCCESS, IndexBoard(
|
||||
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
|
||||
)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings = await asyncio.gather(
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings, ultra = await asyncio.gather(
|
||||
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
|
||||
self.warning_service.for_region(region, now),
|
||||
self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True),
|
||||
)
|
||||
today = now.date()
|
||||
start = kst_midnight(today)
|
||||
@@ -320,31 +388,36 @@ class IndexService:
|
||||
)
|
||||
by_om = {r.forecast_at: r for r in om_rows} if om_err is ErrorType.SUCCESS else {}
|
||||
air = await self.air_service.nearest(region)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
base_ctx = dict(
|
||||
pm25=air.pm25 if air else None,
|
||||
air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
|
||||
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
|
||||
)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
weather_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at))
|
||||
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
|
||||
|
||||
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
|
||||
inputs_at = max(issued, air.measured_at) if air else issued
|
||||
if by_om:
|
||||
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
|
||||
if ultra is not None:
|
||||
inputs_at = max(inputs_at, latest_ultra_base(now) + ULTRA_DELAY)
|
||||
# 지금 구간은 지금 시각부터 보므로 정각마다 다시 계산
|
||||
inputs_at = max(inputs_at, now.replace(minute=0, second=0, microsecond=0))
|
||||
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
|
||||
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
|
||||
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
|
||||
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
|
||||
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False:
|
||||
return ErrorType.SUCCESS, weather_result.score if weather_result else None
|
||||
return ErrorType.SUCCESS, weather_parts
|
||||
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
|
||||
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
|
||||
_, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], today))
|
||||
sunset = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value}
|
||||
sunrise = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNRISE.value}
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
out = []
|
||||
@@ -352,13 +425,13 @@ class IndexService:
|
||||
m = night(day, float(region.lat), float(region.lon))
|
||||
ctx = Context(
|
||||
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
|
||||
sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx,
|
||||
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, rain_hours=rain_hours(by_at, day), **base_ctx,
|
||||
)
|
||||
for d in defs:
|
||||
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
|
||||
if result is None:
|
||||
continue
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {}
|
||||
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at, now) if day == today else {}
|
||||
out.append({
|
||||
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
|
||||
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
|
||||
@@ -366,4 +439,4 @@ class IndexService:
|
||||
"slots": {k: _slot_json(r) for k, r in parts.items()},
|
||||
})
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
|
||||
return err, weather_result.score if weather_result else None
|
||||
return err, weather_parts
|
||||
@@ -3,38 +3,23 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
import orjson
|
||||
from fastapi import Depends
|
||||
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 AirQuality, Region, WeatherHourly
|
||||
from common.enums import AirGrade, ErrorType, RainType, Sky
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, now_kst
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from common.utils.text import hour_label
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.air_service import GRADE_LABEL, AirService
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kma import fetch_ultra, parse_ultra
|
||||
from services.warning_service import WarningItem, WarningService
|
||||
from services.weather_service import WeatherService
|
||||
from services.weather_service import RainHour, WeatherService, ultra_hours
|
||||
|
||||
_FETCH_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
|
||||
_COMMUTE = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
|
||||
|
||||
|
||||
@dataclass
|
||||
class RainHour:
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class CommuteRow:
|
||||
label: str
|
||||
@@ -56,6 +41,7 @@ class NowWeather:
|
||||
air: Optional[AirQuality]
|
||||
air_text: Optional[str]
|
||||
warnings: Optional[list[WarningItem]] = field(default=None)
|
||||
thunder_2h: bool = False
|
||||
|
||||
|
||||
def _weather_word(rain: RainType, sky: Sky, rain_mm: float) -> tuple[str, str]:
|
||||
@@ -139,27 +125,8 @@ class NowService:
|
||||
return ErrorType.SUCCESS, NowWeather(
|
||||
region=region, will_rain_2h=will_rain, rain_2h_text=rain_text, rain_hours=hours,
|
||||
tomorrow_text=tomorrow_text, tomorrow_rain_from=rain_from, commute=commute, air=air, air_text=air_text, warnings=warnings,
|
||||
thunder_2h=any(h.lightning for h in hours),
|
||||
)
|
||||
|
||||
async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]:
|
||||
key = f"ultra:{region.code}"
|
||||
base = latest_ultra_base(now)
|
||||
try:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if cached:
|
||||
data = orjson.loads(cached)
|
||||
if data["base"] == base.isoformat():
|
||||
return [RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"]) for h in data["hours"]]
|
||||
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
return None
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"]) for p in parsed]
|
||||
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm} for h in hours]}
|
||||
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
||||
return hours
|
||||
except _FETCH_ERRORS as e:
|
||||
LOG.error(f"[now] ultra {region.code}: {e}")
|
||||
return None
|
||||
return await ultra_hours(region, now)
|
||||
@@ -0,0 +1,106 @@
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from html import escape
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from config.settings import settings
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.v1.feed.protocol import Res_Feed
|
||||
from services.calc.day_slot import SLOT_LABEL
|
||||
from services.calc.sun import sun_times
|
||||
from services.feed_service import FeedService
|
||||
|
||||
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||
_NAME = re.compile(r"<h1>(.+?) 오늘 날씨")
|
||||
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||
|
||||
|
||||
def _clock(at: datetime) -> str:
|
||||
at = at.astimezone(KST)
|
||||
h = at.hour % 12 or 12
|
||||
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
|
||||
|
||||
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
def day_summary(rows: list[WeatherHourly]) -> str:
|
||||
"""오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
|
||||
if not rows:
|
||||
return ""
|
||||
temps = [float(r.temp_c) for r in rows]
|
||||
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
|
||||
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
|
||||
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
|
||||
return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}."
|
||||
|
||||
|
||||
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
"""검색 결과 요약에 보일 오늘 한 줄: 하루 예보, 지금 기온·상태, 구간별 1위 각, 해 지는 시각."""
|
||||
parts = [day_summary(rows)] if rows else []
|
||||
h = feed.hero
|
||||
if h and h.temp_c is not None:
|
||||
status = "·".join(f"{s.label} {s.value}" for s in h.status)
|
||||
parts.append(f"지금 {round(h.temp_c)}°" + (f", {status}" if status else "") + ".")
|
||||
firsts = [f"{label}은 {s.name}" for slot, label in SLOT_LABEL.items() for s in feed.stories if s.slot_ranks.get(slot) == 1]
|
||||
if firsts:
|
||||
parts.append(", ".join(firsts) + ".")
|
||||
if sunset_at:
|
||||
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
line = today_line(feed, rows, sunset_at)
|
||||
if not line:
|
||||
return template
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
|
||||
|
||||
|
||||
class SeoService:
|
||||
def __init__(
|
||||
self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)
|
||||
) -> None:
|
||||
self.feed, self.regions, self.weather = feed, regions, weather
|
||||
|
||||
async def template(self, path: str) -> Optional[str]:
|
||||
"""프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html)."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
r = await client.get(f"{settings.frontend_internal_url}/{path}.html")
|
||||
except httpx.HTTPError as e:
|
||||
LOG.error(f"[seo] template {path}: {e}")
|
||||
return None
|
||||
return r.text if r.status_code == 200 and _CODE.search(r.text) else None
|
||||
|
||||
async def page(self, path: str) -> tuple[ErrorType, Optional[str]]:
|
||||
template = await self.template(path)
|
||||
if template is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
code = _CODE.search(template).group(1)
|
||||
err, feed = await self.feed.feed(code)
|
||||
if err is not ErrorType.SUCCESS or feed is None:
|
||||
LOG.error(f"[seo] feed {code}: {err}")
|
||||
return ErrorType.SUCCESS, template
|
||||
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
|
||||
today = now_kst().date()
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(today)
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
|
||||
name = _NAME.search(template)
|
||||
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||
@@ -5,6 +5,7 @@ from datetime import date, datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
import orjson
|
||||
from fastapi import Depends
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
@@ -14,23 +15,31 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Region, SunTime, WeatherHourly
|
||||
from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_vilage_base, now_kst
|
||||
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, latest_vilage_base, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.sky_crud import SkyCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from services.calc.sun import sun_times
|
||||
from services.calc.weather_calc import discomfort_index, feels_like_c
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.kma import day_start_base, fetch_mid, fetch_vilage, latest_mid_base, parse_mid, parse_vilage
|
||||
from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
|
||||
|
||||
SLOT_HOURS = range(0, 24, 3)
|
||||
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
|
||||
_WAIT_STEPS, _WAIT_SEC = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다
|
||||
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
|
||||
_MIN_DAY_HOURS = 8
|
||||
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
||||
_background: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
@dataclass
|
||||
class RainHour:
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
lightning: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class Slot:
|
||||
at: datetime
|
||||
@@ -49,6 +58,18 @@ class TodayWeather:
|
||||
slots: list[Slot]
|
||||
|
||||
|
||||
def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[RainHour]]) -> dict[datetime, WeatherHourly]:
|
||||
"""초단기예보가 닿는 시각은 비·비 없음 모두 초단기예보로 바꾼 사본. 단기예보는 3시간마다라 그 사이 바뀐 비를 놓친다."""
|
||||
out = dict(by_at)
|
||||
for h in ultra or []:
|
||||
r = out.get(h.at)
|
||||
if r is None or (h.rain_type.value, h.rain_mm) == (r.rain_type, float(r.rain_mm)):
|
||||
continue
|
||||
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
|
||||
out[h.at] = WeatherHourly(**{**cols, "rain_type": h.rain_type.value, "rain_mm": h.rain_mm})
|
||||
return out
|
||||
|
||||
|
||||
def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
|
||||
rows = []
|
||||
for at, v in hourly.items():
|
||||
@@ -138,7 +159,7 @@ class WeatherService:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
|
||||
now = now_kst()
|
||||
await self.ensure_vilage(region, now)
|
||||
_, ultra = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True))
|
||||
day = day or now.date()
|
||||
sun = await self._ensure_sun(region, day)
|
||||
start = kst_midnight(day)
|
||||
@@ -154,11 +175,13 @@ class WeatherService:
|
||||
sunset_score = next(
|
||||
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == day), None
|
||||
)
|
||||
by_at = {r.forecast_at: r for r in rows}
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
slots = []
|
||||
hour_now = now.replace(minute=0, second=0, microsecond=0)
|
||||
for h in SLOT_HOURS:
|
||||
at = start + timedelta(hours=h)
|
||||
row = by_at.get(at)
|
||||
# 지금이 든 칸은 칸 첫 시각 대신 지금 시각 예보 (이미 지난 시각의 비가 '지금'으로 보이지 않게)
|
||||
row = by_at.get(hour_now) if at <= now < at + timedelta(hours=3) and hour_now in by_at else by_at.get(at)
|
||||
icon, tone, note = _slot_view(at, row, sun)
|
||||
if note == "노을" and sunset_score is not None:
|
||||
note = f"노을 {sunset_score}"
|
||||
@@ -262,3 +285,45 @@ class WeatherService:
|
||||
}
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_sun(s, row)])
|
||||
return SunTime(**row)
|
||||
|
||||
|
||||
_ULTRA_WAIT_SEC, _ULTRA_WAIT_TRIES = 0.3, 30 # 다른 요청이 받아 오는 중이면 캐시가 찰 때까지 약 9초 기다린다
|
||||
|
||||
|
||||
async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
|
||||
cached = await REDIS.conn.get(key)
|
||||
if not cached:
|
||||
return None
|
||||
data = orjson.loads(cached)
|
||||
if data["base"] != base.isoformat():
|
||||
return None
|
||||
return [
|
||||
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
|
||||
for h in data["hours"]
|
||||
]
|
||||
|
||||
|
||||
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
|
||||
"""초단기예보(앞으로 6시간 비). 실패하면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다리고 아니면 None."""
|
||||
key = f"ultra:{region.code}"
|
||||
base = latest_ultra_base(now)
|
||||
try:
|
||||
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
|
||||
if attempt:
|
||||
await asyncio.sleep(_ULTRA_WAIT_SEC)
|
||||
if (hours := await _cached_ultra(key, base)) is not None:
|
||||
return hours
|
||||
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
|
||||
if not acquired:
|
||||
continue
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
|
||||
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
|
||||
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
||||
return hours
|
||||
return None
|
||||
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
|
||||
LOG.error(f"[now] ultra {region.code}: {e}")
|
||||
return None
|
||||
@@ -80,7 +80,6 @@ def offline(monkeypatch):
|
||||
|
||||
import scheduler.jobs as jobs
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
@@ -118,7 +117,7 @@ def offline(monkeypatch):
|
||||
|
||||
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "테스트", "dmX": "37.56", "dmY": "126.91"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "테스트", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1",
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.database.model.models import WeatherHourly
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight
|
||||
from services.calc.day_slot import slot_hours
|
||||
from services.calc.index_calc import Context
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, current_slot, slot_results
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results
|
||||
from services.weather_service import RainHour, with_ultra_rain
|
||||
|
||||
DAY = date(2026, 10, 8)
|
||||
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
|
||||
@@ -47,8 +49,10 @@ def test_current_slot_before_5_is_previous_night():
|
||||
|
||||
|
||||
def test_gak_hidden_in_slots_outside_its_window():
|
||||
parts = slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"evening", "night"}
|
||||
# 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다
|
||||
assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"}
|
||||
|
||||
|
||||
def test_rain_in_evening_lowers_only_later_slots():
|
||||
@@ -61,3 +65,63 @@ def test_rain_in_evening_lowers_only_later_slots():
|
||||
def test_weather_score_covers_every_slot():
|
||||
parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
|
||||
|
||||
|
||||
def test_shown_parts_uses_last_night_before_five():
|
||||
parts = {"morning": 1, "day": 2, "evening": 3, "night": 4, EARLY: 5}
|
||||
assert _shown_parts(parts, "day") == {"morning": 1, "day": 2, "evening": 3, "night": 4}
|
||||
assert _shown_parts(parts, EARLY) == {"morning": 1, "day": 2, "evening": 3, "night": 5}
|
||||
|
||||
|
||||
def _hourly(h: int, rain: RainType = RainType.NONE) -> WeatherHourly:
|
||||
at = kst_midnight(DAY) + timedelta(hours=h)
|
||||
return WeatherHourly(
|
||||
region_code="1", forecast_at=at, temp_c=21, feels_c=21, discomfort_index=60, sky=Sky.CLOUDY.value, rain_type=rain.value,
|
||||
rain_prob=30, rain_mm=0, humidity=60, wind_ms=1.0, issued_at=at,
|
||||
)
|
||||
|
||||
|
||||
def test_ultra_overrides_vilage_rain_both_ways():
|
||||
"""초단기예보가 닿는 시각은 초단기예보가 이긴다: 단기예보가 맑아도 비로, 단기예보가 비여도 비 없음으로."""
|
||||
by_at = {r.forecast_at: r for r in (_hourly(9), _hourly(10), _hourly(11, RainType.SHOWER), _hourly(12, RainType.RAIN))}
|
||||
at = lambda h: kst_midnight(DAY) + timedelta(hours=h) # noqa: E731
|
||||
ultra = [RainHour(at=at(10), rain_type=RainType.RAIN, rain_mm=1.5), RainHour(at=at(9), rain_type=RainType.NONE, rain_mm=0),
|
||||
RainHour(at=at(11), rain_type=RainType.NONE, rain_mm=0)]
|
||||
out = with_ultra_rain(by_at, ultra)
|
||||
assert (out[at(10)].rain_type, float(out[at(10)].rain_mm)) == (RainType.RAIN.value, 1.5)
|
||||
assert (out[at(11)].rain_type, float(out[at(11)].rain_mm)) == (RainType.NONE.value, 0)
|
||||
assert out[at(9)] is by_at[at(9)] and out[at(12)] is by_at[at(12)]
|
||||
assert by_at[at(10)].rain_type == RainType.NONE.value and by_at[at(11)].rain_type == RainType.SHOWER.value
|
||||
|
||||
|
||||
def test_ultra_rain_lowers_slot_score():
|
||||
defn = _defn([{"from": 9, "to": 17}])
|
||||
by_at = {r.forecast_at: r for r in (_hourly(h) for h in range(5, 30))}
|
||||
rainy = with_ultra_rain(by_at, [RainHour(at=kst_midnight(DAY) + timedelta(hours=10), rain_type=RainType.RAIN, rain_mm=2.0)])
|
||||
dry, wet = (slot_results(defn, DAY, REGION, b, {}, CTX, SUNSET)["morning"].score for b in (by_at, rainy))
|
||||
assert wet < dry
|
||||
|
||||
|
||||
def test_slot_needs_two_overlapping_hours():
|
||||
"""10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다."""
|
||||
by_at = _rows()
|
||||
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
|
||||
|
||||
def test_current_slot_skips_passed_hours():
|
||||
"""13:30이면 낮 구간(11~15시)은 13시부터 본다. 11~12시에만 온 비는 지금 점수를 깎지 않는다. 지난 아침 구간은 그대로."""
|
||||
defn = _defn([{"from": 5, "to": 24}])
|
||||
by_at = {r.forecast_at: r for r in (_hourly(h, RainType.RAIN if h in (11, 12) else RainType.NONE) for h in range(5, 30))}
|
||||
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
|
||||
with_now = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET, now)
|
||||
without = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert with_now["day"].score > without["day"].score
|
||||
assert with_now["morning"].score == without["morning"].score
|
||||
|
||||
|
||||
def test_current_slot_keeps_last_hour():
|
||||
"""구간 끝 한 시간만 남아도 지금 구간 점수를 낸다."""
|
||||
now = datetime(2026, 10, 8, 15, 10, tzinfo=KST)
|
||||
assert "day" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
|
||||
@@ -61,7 +61,9 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 34
|
||||
assert len(body["stories"]) == 40
|
||||
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
|
||||
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
@@ -70,7 +72,7 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
assert body["bands"]["events"][0]["image_credit"] == "ⓒ한국관광공사"
|
||||
assert "미세먼지" not in weather["caption"]
|
||||
air = next(p for p in body["posts"] if p["post_type"] == PostType.AIR.value)
|
||||
assert [(r["label"], r["value"]) for r in air["slides"][0]["rows"]] == [("초미세먼지", "10㎍/㎥ · 좋음"), ("미세먼지", "20㎍/㎥ · 좋음")]
|
||||
assert [(r["label"], r["value"]) for r in air["slides"][0]["rows"]] == [("초미세먼지", "좋음"), ("미세먼지", "좋음")]
|
||||
event = next(p for p in body["posts"] if p["post_type"] == PostType.EVENT.value)
|
||||
assert event["slides"][0]["eyebrow"].startswith("가까운 행사 · ")
|
||||
|
||||
@@ -87,6 +89,18 @@ def test_feed_cache_expires_when_time_slot_changes():
|
||||
assert feed_ttl_sec(now, sunset) <= 600
|
||||
|
||||
|
||||
def test_feed_cache_expires_when_ultra_forecast_arrives():
|
||||
"""초단기예보 비가 각 점수에 들어가니, 다음 초단기예보가 나오는 :45 에 캐시가 끝나야 한다."""
|
||||
from datetime import datetime
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import feed_ttl_sec
|
||||
|
||||
now = datetime(2026, 10, 2, 13, 20, tzinfo=KST)
|
||||
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
||||
assert feed_ttl_sec(now, sunset) == 25 * 60
|
||||
|
||||
|
||||
def _card(post_type, post_id=1):
|
||||
from datetime import datetime
|
||||
|
||||
@@ -190,7 +204,7 @@ def test_gak_key_handles_sunset_window():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
async def test_feed_missing_gak_is_not_cached(offline, monkeypatch):
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from services.index_service import IndexService
|
||||
@@ -202,8 +216,7 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]]
|
||||
keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")]
|
||||
assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60
|
||||
assert [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] == []
|
||||
|
||||
|
||||
def _alert_ctx(warnings=(), rain_prob=0):
|
||||
@@ -261,7 +274,7 @@ def test_text_helpers_short_day_and_compass():
|
||||
assert compass(263) == "서" and compass(247) == "서남서"
|
||||
|
||||
|
||||
def _air(pm25, pm10, measured_hours_ago=0):
|
||||
def _air(pm25, pm10, measured_hours_ago=0, rain=False):
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -271,7 +284,7 @@ def _air(pm25, pm10, measured_hours_ago=0):
|
||||
now = datetime(2026, 10, 2, 9, 30, tzinfo=KST)
|
||||
air = None if pm25 is None and pm10 is None else SimpleNamespace(
|
||||
station_name="테스트", pm25=pm25, pm10=pm10, measured_at=now.replace(minute=0) - timedelta(hours=measured_hours_ago))
|
||||
ctx = SimpleNamespace(now=now, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(air=air))
|
||||
ctx = SimpleNamespace(now=now, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(air=air, will_rain_2h=rain))
|
||||
return FeedService._air(None, _base() | {"post_type": PostType.AIR}, ctx)
|
||||
|
||||
|
||||
@@ -280,8 +293,11 @@ def test_air_post_shows_both_values_and_advice_only_when_bad():
|
||||
assert [r.label for r in good.slides[0].rows] == ["초미세먼지", "미세먼지"] and good.title == "미세먼지 좋음"
|
||||
bad = _air(40, 60)
|
||||
assert bad.title == "미세먼지 나쁨" and bad.slides[0].rows[-1].label == "이렇게 해요"
|
||||
wet = _air(10, 20, rain=True)
|
||||
assert "창문은 닫아" in wet.slides[0].line and wet.icon == "umbrella"
|
||||
assert "창문은 닫아" not in _air(40, 60, rain=True).slides[0].line
|
||||
very = _air(20, 160)
|
||||
assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "160㎍/㎥ · 매우나쁨"
|
||||
assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "매우나쁨"
|
||||
|
||||
|
||||
def test_air_post_off_without_fresh_data():
|
||||
@@ -367,6 +383,9 @@ def test_uv_post_only_when_moderate_or_higher():
|
||||
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 post.title == "자외선 지수 높음" and post.caption == "가장 셀 때 낮 12시"
|
||||
assert post.slides[0].line == "오늘 자외선 지수 높음\n점심때 나가면 선크림·모자·선글라스 챙기고 그늘로 다녀요"
|
||||
assert [(r.label, r.value, r.level) for r in post.slides[0].rows] == [("9시", "낮음", 1), ("12시", "높음", 3), ("15시", "보통", 2)]
|
||||
assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요"
|
||||
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
||||
assert FeedService._uv_post(None, base, ctx([])) is None
|
||||
@@ -2,7 +2,7 @@ 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
|
||||
from services.hero_stats import HeroInput, hero_stats, hero_status
|
||||
|
||||
NOW = datetime(2026, 10, 7, 14, 20, tzinfo=KST)
|
||||
|
||||
@@ -46,3 +46,28 @@ def test_one_coldwind_card_only():
|
||||
|
||||
def test_nothing_known_gives_nothing():
|
||||
assert hero_stats(HeroInput(now=NOW, night=False)) == []
|
||||
|
||||
|
||||
def _status(x: HeroInput) -> list[tuple[str, str, str]]:
|
||||
return [(s.label, s.value, s.tone) for s in hero_status(x)]
|
||||
|
||||
|
||||
def test_status_line_has_four_by_day_and_warns_only_caution():
|
||||
summer = datetime(2026, 7, 7, 14, 20, tzinfo=KST)
|
||||
x = HeroInput(now=summer, night=False, humidity=55, discomfort=75, uv=4.2, air=AirGrade.GOOD)
|
||||
assert _status(x) == [("습도", "보통", "normal"), ("불쾌지수", "불쾌", "warn"), ("자외선", "보통", "normal"), ("미세먼지", "좋음", "normal")]
|
||||
x = HeroInput(now=summer, night=False, humidity=72, discomfort=60, uv=6.0, air=AirGrade.BAD)
|
||||
assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")]
|
||||
|
||||
|
||||
def test_status_line_shows_discomfort_only_june_to_september():
|
||||
"""불쾌지수는 더위 지표라 10월 비 오는 날에도 '쾌적'이 나온다. 기상청처럼 6~9월에만."""
|
||||
x = HeroInput(now=NOW, night=False, humidity=95, discomfort=66, uv=1.0, air=AirGrade.GOOD)
|
||||
assert [s.label for s in hero_status(x)] == ["습도", "자외선", "미세먼지"]
|
||||
|
||||
|
||||
def test_status_line_drops_uv_at_night_and_missing_values():
|
||||
assert _status(HeroInput(now=NOW, night=True, after_dark=True, humidity=25, uv=3.0, air=AirGrade.NORMAL)) == [("습도", "건조", "normal"), ("미세먼지", "보통", "normal")]
|
||||
# 저녁 구간(night=True, 아직 해 있음)엔 자외선이 남는다
|
||||
assert _status(HeroInput(now=NOW, night=True, uv=0.6)) == [("자외선", "낮음", "normal")]
|
||||
assert _status(HeroInput(now=NOW, night=False)) == []
|
||||
@@ -15,7 +15,7 @@ from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -51,20 +51,23 @@ def fakes(monkeypatch):
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
seasons = [i["in_season"] for i in body["items"]]
|
||||
assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group]
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
@@ -75,10 +78,12 @@ async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_filters_core(fakes):
|
||||
async def test_index_list_filters_core_to_gak_in_season_now(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION, "core": True})).json()
|
||||
assert {i["code"] for i in body["items"]} == {"picnic", "hiking", "camping", "stars"}
|
||||
month = now_kst().month
|
||||
assert {i["code"] for i in body["items"]} == {d["code"] for d in _seed() if month in d["months"]}
|
||||
assert all(i["season"] == season_of(month) for i in body["items"])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -88,7 +93,7 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
|
||||
assert body["index"]["code"] == "yajang"
|
||||
assert [f["label"] for f in body["factors"]] == ["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"]
|
||||
assert sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["zero_rules"] == "비 소식이 있거나 비 확률 70% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
|
||||
|
||||
@@ -119,6 +124,33 @@ def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
def test_every_index_has_valid_months_and_weights():
|
||||
for d in _seed():
|
||||
assert isinstance(d["months"], list) and all(1 <= m <= 12 for m in d["months"]), d["code"]
|
||||
assert sum(d[f"weight_{a}"] for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")) == 100, d["code"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypatch):
|
||||
today = now_kst().date()
|
||||
other = [m for m in range(1, 13) if m != today.month]
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="always", priority=2, months=[], sort_order=1),
|
||||
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2),
|
||||
SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
_, board = await service.board(REGION)
|
||||
view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items]
|
||||
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
|
||||
assert view == [("now", True, True, season_of(today.month)), ("always", True, True, None), ("off", False, False, None)]
|
||||
assert [i.definition.code for i in board.ranked] == ["now", "always"]
|
||||
assert all(not i.slot_ranks for i in board.items if not i.in_season)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
@@ -130,13 +162,33 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
err, board = await service.board(REGION)
|
||||
assert err is ErrorType.SUCCESS
|
||||
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
|
||||
every = ("morning", "day", "evening", "night", "early")
|
||||
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
|
||||
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every})))
|
||||
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
|
||||
_, board = await service.board(REGION)
|
||||
ranks = {i.definition.code: i.slot_ranks for i in board.items}
|
||||
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
|
||||
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
|
||||
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
|
||||
assert "night" not in ranks["high"]
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
row = {
|
||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
||||
|
||||
@@ -259,6 +259,22 @@ def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("flower", dict(feels=19.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("blanket", dict(feels=22.0, wind=3.0, hum=35, sunshine_ratio=0.9), dict(feels=10.0, prob=70, rain=RainType.RAIN, hum=90, sunshine_ratio=0.1)),
|
||||
("bingsu", dict(feels=33.0, hum=75), dict(feels=18.0, hum=40)),
|
||||
("indoordry", dict(feels=27.0, prob=90, rain=RainType.RAIN, hum=55), dict(feels=14.0, hum=90)),
|
||||
("riverwind", dict(feels=24.0, wind=3.0, hum=55), dict(feels=20.0, prob=80, rain=RainType.RAIN, wind=0.5, hum=90)),
|
||||
("foliage", dict(feels=16.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("sweetpotato", dict(feels=2.0, wind=6.0), dict(feels=20.0, wind=1.0)),
|
||||
("bungeoppang", dict(feels=-5.0, wind=6.0), dict(feels=15.0, wind=1.0)),
|
||||
("tangerine", dict(feels=-5.0, wind=7.0, prob=80, rain=RainType.SNOW), dict(feels=15.0, wind=1.0)),
|
||||
])
|
||||
def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **good) >= 80
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
@@ -274,3 +290,31 @@ def test_weather_score_100_only_on_perfect_day():
|
||||
|
||||
good = [_h(h, feels=22.5, prob=10, wind=2.5, hum=62, sunshine_ratio=0.7) for h in range(9, 22)]
|
||||
assert evaluate(WEATHER_SCORE_DEF, [good], replace(perfect, pm25=15)).score < 95
|
||||
|
||||
|
||||
def test_raining_now_caps_even_with_low_rain_prob():
|
||||
"""초단기예보로 비가 들어온 시각은 예보 확률이 낮아도 '비 소식' 상한이 걸린다."""
|
||||
defn = _defn(zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}])
|
||||
r = evaluate(defn, [[_h(19, prob=30, rain=RainType.RAIN)]], CTX)
|
||||
assert r.score <= 20 and r.zero_reason == "비 소식이 있어 최대 20점"
|
||||
assert evaluate(defn, [[_h(19, prob=30)]], CTX).zero_reason is None
|
||||
|
||||
|
||||
def test_humidity_cap():
|
||||
defn = _defn(zero_rules=[{"field": "humidity", "op": ">=", "value": 85, "cap": 40}])
|
||||
assert evaluate(defn, [[_h(19, hum=92)]], CTX).zero_reason == "습도 85% 이상이라 최대 40점"
|
||||
assert zero_rules_text([{"field": "rain", "op": "==", "value": "yes"}]) == "비 소식이 있으면 0점"
|
||||
|
||||
|
||||
def test_axis_label_can_be_overridden():
|
||||
assert axis_label("temp", {"temp": {"type": "higher", "label": "덜 추움"}}) == "덜 추움"
|
||||
|
||||
|
||||
def test_umbrella_lost_needs_rain_that_stopped():
|
||||
"""우산분실각: 앞서 비가 왔다가 그친 시간대만 점수가 난다. 비가 안 온 날, 아직 비가 오는 시간대는 0점."""
|
||||
defn = _defn(weight_temp=0, weight_rain=80, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=20,
|
||||
zero_rules=[{"field": "rain_before", "op": "==", "value": "no"}, {"field": "rain", "op": "==", "value": "yes"}])
|
||||
after_rain = replace(CTX, rain_hours=frozenset({9, 10}))
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
|
||||
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.index_calc import Context, DayForecast, Hour, estimate, evaluate, time_score, zero_rules_text
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import in_season, season_badge, season_of, window_hours
|
||||
|
||||
CTX = Context(day=date(2027, 1, 9), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
SNOWMAN = SimpleNamespace(
|
||||
weight_temp=50, weight_rain=10, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=20,
|
||||
factor_rules={"temp": {"type": "range", "lo": -5, "hi": 2, "best": -1}, "rain": {"dir": "wet"}, "wind": {"type": "calm", "ok": 3, "limit": 10},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[{"field": "snow", "op": "==", "value": "no"}], windows=[{"from": 9, "to": 16}],
|
||||
)
|
||||
|
||||
|
||||
def _h(hour, rain=RainType.NONE, feels=-1.0):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=80 if rain is not RainType.NONE else 0, wind_ms=1.0, humidity=70, sky=Sky.CLOUDY)
|
||||
|
||||
|
||||
def test_season_names_and_in_season():
|
||||
assert [season_of(m) for m in (1, 3, 6, 9, 12)] == ["겨울", "봄", "여름", "가을", "겨울"]
|
||||
always, winter = SimpleNamespace(months=[]), SimpleNamespace(months=[12, 1, 2])
|
||||
assert in_season(always, 7) and in_season(winter, 1) and not in_season(winter, 7)
|
||||
# 일 년 내내인 각엔 계절 표시가 없다
|
||||
assert season_badge(always, 1) is None and season_badge(winter, 1) == "겨울" and season_badge(winter, 7) is None
|
||||
assert in_season(SimpleNamespace(), 5)
|
||||
|
||||
|
||||
def test_snowman_is_zero_without_snow_and_high_when_snowing_near_zero():
|
||||
dry = evaluate(SNOWMAN, [[_h(h) for h in range(9, 16)]], CTX)
|
||||
assert dry.score == 0 and dry.zero_reason == "눈 소식이 없어 0점"
|
||||
snowy = evaluate(SNOWMAN, [[_h(h, RainType.SNOW) for h in range(9, 16)]], CTX)
|
||||
assert snowy.score >= 80 and snowy.zero_reason is None
|
||||
assert zero_rules_text(SNOWMAN.zero_rules) == "눈 소식이 없으면 0점"
|
||||
|
||||
|
||||
def test_snowman_estimate_from_mid_forecast_is_zero():
|
||||
fc = DayForecast(temp_min_c=-4, temp_max_c=1, rain_prob_am=70, rain_prob_pm=70, sky=Sky.CLOUDY)
|
||||
assert estimate(SNOWMAN, fc, [list(range(9, 16))], CTX).score == 0
|
||||
|
||||
|
||||
def test_sunrise_score_time_rule():
|
||||
assert time_score({"type": "sunrise_score"}, Context(**{**CTX.__dict__, "sunrise_score": 72})) == (72, "일출 하늘 점수 72")
|
||||
assert time_score({"type": "sunrise_score"}, CTX)[0] == 70
|
||||
|
||||
|
||||
def test_window_around_sunrise_covers_sunrise_hour():
|
||||
region = SimpleNamespace(lat=37.56, lon=126.97)
|
||||
day = date(2027, 1, 1)
|
||||
h = sun_times(day, region.lat, region.lon).sunrise_at.astimezone(KST).hour
|
||||
assert window_hours(SimpleNamespace(windows=[{"around": "sunrise", "hours": 1}]), day, region) == [[h - 1, h, h + 1]]
|
||||
|
||||
@@ -18,7 +18,7 @@ def test_parse_ultra_reads_rain_and_temp():
|
||||
{"category": c, "fcstDate": "20261002", "fcstTime": "1000", "fcstValue": v}
|
||||
for c, v in [("PTY", "1"), ("RN1", "1mm 미만"), ("T1H", "17")]
|
||||
]
|
||||
assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0}]
|
||||
assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0, "lightning": False}]
|
||||
|
||||
|
||||
def _event(area, var, cmd, tm, seq=1, stress=0):
|
||||
@@ -72,3 +72,23 @@ def test_ieyo_particle():
|
||||
assert ieyo("환기") == "환기예요"
|
||||
assert ieyo("야장각") == "야장각이에요"
|
||||
assert ieyo("아아→뜨아") == "아아→뜨아예요"
|
||||
|
||||
|
||||
def test_parse_ultra_reads_drizzle_codes():
|
||||
"""초단기예보에만 있는 5 빗방울 · 6 빗방울눈날림 · 7 눈날림."""
|
||||
items = [
|
||||
{"fcstDate": "20261013", "fcstTime": f"{h:02d}00", "category": c, "fcstValue": v}
|
||||
for h, pty in ((10, "5"), (11, "6"), (12, "7"))
|
||||
for c, v in [("PTY", pty), ("RN1", "1mm 미만"), ("T1H", "17")]
|
||||
]
|
||||
assert [p["rain_type"] for p in parse_ultra(items)] == [RainType.RAIN, RainType.SLEET, RainType.SNOW]
|
||||
|
||||
|
||||
def test_parse_ultra_reads_lightning():
|
||||
"""LGT 는 낙뢰(kA). 0 이면 없음, 칸이 없어도 없음."""
|
||||
items = [
|
||||
{"fcstDate": "20261013", "fcstTime": f"{h:02d}00", "category": c, "fcstValue": v}
|
||||
for h, lgt in ((10, "0"), (11, "3"), (12, None))
|
||||
for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "17"), ("LGT", lgt)] if v is not None
|
||||
]
|
||||
assert [p["lightning"] for p in parse_ultra(items)] == [False, True, False]
|
||||
@@ -2,7 +2,6 @@ import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
@@ -16,7 +15,7 @@ REGION = "1114000000"
|
||||
ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1/week", "/v1/index/list", "/v1/season/week"]
|
||||
SOURCES = {
|
||||
"vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed),
|
||||
"ultra": (now_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"ultra": (weather_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"air": (air_service, "fetch_realtime", DataGoKrRequestFailed),
|
||||
"warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed),
|
||||
"clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from common.database.model.models import WeatherHourly
|
||||
from router.router import app
|
||||
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line
|
||||
|
||||
REGION = "1114000000"
|
||||
TEMPLATE = (
|
||||
'<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />'
|
||||
f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>'
|
||||
)
|
||||
|
||||
|
||||
def _top(name: str, score: int, ranks: dict[str, int]) -> TopIndex:
|
||||
return TopIndex(index_id=1, code="x", name=name, icon="x", score=score, rank=1, slot_ranks=ranks)
|
||||
|
||||
|
||||
def _feed() -> Res_Feed:
|
||||
stories = [_top("러닝각", 80, {"morning": 1, "day": 2}), _top("빨래각", 77, {"day": 1}), _top("별보기각", 70, {"night": 1})]
|
||||
hero = Hero(now_at=datetime(2026, 10, 14, 9), sky_mode="morning", temp_c=13.4,
|
||||
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal"), HeroStat(icon="m", label="미세먼지", value="좋음", tone="normal")])
|
||||
return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2]))
|
||||
|
||||
|
||||
def _hour(h: int, temp: float, sky: int = 1, rain: int = 1, prob: int = 0) -> WeatherHourly:
|
||||
return WeatherHourly(forecast_at=datetime(2026, 10, 14, h, tzinfo=KST), temp_c=temp, sky=sky, rain_type=rain, rain_prob=prob)
|
||||
|
||||
|
||||
def test_day_summary_min_max_prob_and_daytime_sky():
|
||||
rows = [_hour(3, 8.6, sky=4), _hour(9, 12, sky=3), _hour(12, 19.5, sky=1, prob=10), _hour(15, 20.2, sky=1), _hour(21, 14)]
|
||||
assert day_summary(rows) == "최저 9°·최고 20°, 강수확률 10%, 맑음."
|
||||
assert day_summary([_hour(12, 15, rain=2, prob=70)]) == "최저 15°·최고 15°, 강수확률 70%, 비."
|
||||
|
||||
|
||||
def test_today_line_has_day_now_slot_firsts_and_sunset():
|
||||
line = today_line(_feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
|
||||
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
|
||||
|
||||
|
||||
def test_fill_puts_today_into_description_and_body():
|
||||
html = fill(TEMPLATE, _feed(), [], "서울 중구", None)
|
||||
assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2
|
||||
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>지금 13°" in html
|
||||
assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html
|
||||
|
||||
|
||||
def test_fill_keeps_template_when_no_weather():
|
||||
assert fill(TEMPLATE, Res_Feed(), [], "서울 중구", None) == TEMPLATE
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_page_fills_real_feed(offline, monkeypatch):
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/seoul/jung" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/seoul/jung")
|
||||
missing = await client.get("/v1/seo/today/seoul/nowhere")
|
||||
assert page.status_code == 200 and "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text and "지금 20°" in page.text
|
||||
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang")
|
||||
assert page.status_code == 200 and "지금 20°" in page.text
|
||||
@@ -81,3 +81,18 @@ async def test_drop_known_skips_same_festival_from_another_source():
|
||||
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
|
||||
]
|
||||
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_upsert_events_stores_names_without_html_entities():
|
||||
from sqlalchemy import select
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Event
|
||||
from crud.week_crud import WeekCRUD
|
||||
|
||||
# 문화정보원 목록은 두 번 인코딩돼 와서 한 번 풀어도 "<" 가 남는다
|
||||
row = {**_row("kcis:1", "김상희 2인전 &lt;안녕을 빌었다&gt;", date(2026, 10, 1), date(2026, 10, 24)), "place_name": "갤러리 &middot; 1층"}
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [row])])
|
||||
_, saved = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(select(Event).where(Event.source_id == "kcis:1")))
|
||||
assert (saved.name, saved.place_name) == ("김상희 2인전 <안녕을 빌었다>", "갤러리 · 1층")
|
||||
@@ -4,7 +4,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.router import app
|
||||
from router.v1.watch.watch import timeline
|
||||
@@ -83,3 +85,18 @@ async def test_watch_summary_unknown_region_fails(offline):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": "0000000000"})).json()
|
||||
assert body["result"]["success"] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_watch_summary_flags_thunder_within_2_hours(offline, monkeypatch):
|
||||
start = now_kst().replace(minute=0, second=0, microsecond=0)
|
||||
items = [
|
||||
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
|
||||
for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")]
|
||||
]
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(items))
|
||||
# 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다
|
||||
await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": REGION})).json()
|
||||
assert body["now"]["rain_2h"] is True and body["now"]["thunder"] is True
|
||||
@@ -5,7 +5,6 @@ from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.cache.redis_client import REDIS
|
||||
@@ -63,7 +62,7 @@ async def clean():
|
||||
async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean):
|
||||
now = now_kst()
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "마포구", "dmX": "37.5555", "dmY": "126.9055"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "1",
|
||||
@@ -92,7 +91,7 @@ async def test_now_warning_failure_is_unknown_not_none(monkeypatch, clean):
|
||||
raise DataGoKrRequestFailed("HTTP 504")
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", fail)
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", fail)
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", fail)
|
||||
|
||||
@@ -19,6 +19,8 @@ docker compose up -d --wait postgres redis
|
||||
docker compose exec -T postgres psql -q -v ON_ERROR_STOP=1 -U "$DB_USER" -d "$DB_NAME" < backend/postgres-init/init.sql
|
||||
docker compose up -d --build backend worker frontend
|
||||
docker compose exec -T backend python scripts/load_seed.py
|
||||
# 피드 캐시는 최대 1시간이라, 각 규칙이 바뀌어도 오늘 탭만 옛 순위로 남는다
|
||||
docker compose exec -T redis sh -c "redis-cli --scan --pattern 'feed:*' | xargs -r redis-cli del" >/dev/null
|
||||
|
||||
if [ "${1:-}" = "--restore-db" ]; then
|
||||
dump="${2:?덤프 파일 경로가 필요합니다}"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 기능 QA 체크리스트 (휴대폰)
|
||||
|
||||
아이폰 Safari와 안드로이드 Chrome에서 http://<킹서버>:30040 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다.
|
||||
아이폰 Safari와 안드로이드 Chrome에서 테스트 서버(:30040) 에 들어가 위에서부터 따라 하며 체크합니다. 기대 결과는 `frontend/src/b/` 코드 기준이고, 확실하지 않은 동작은 "(확인)"을 붙였습니다.
|
||||
|
||||
## 0. 처음 들어가기
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
## 2. 오늘 탭: 히어로
|
||||
|
||||
- [ ] 시간대 버튼 지금 · 아침 · 낮 · 저녁 · 밤, 처음엔 "지금", 날짜 줄은 "M월 D일 요일 · HH:MM"
|
||||
- [ ] 해 안에 "지금 날씨 점수"와 큰 숫자, 아래 한 줄 네 칸: "지금 + 기온·하늘" · "습도 N%" · "불쾌지수 N 쾌적"(75 이상이면 경고 색) · 챙길 것 한 칸(비·미세먼지 등). 폰 너비에서 넘치지 않는다
|
||||
- [ ] 해 안에 "오늘 날씨 점수"와 큰 숫자, 아래 칩 한 줄: 첫 칸 "지금 + 기온·하늘", 나머지는 챙길 것(비·미세먼지 등)
|
||||
- [ ] "아침" → 시계 07:40, 첫 칩 이름 "아침", 기온이 7시 예보 값 (낮 13:20 · 저녁 18:25 · 밤 22:10도 같은 방식)
|
||||
- [ ] 저녁·밤 → 해 동그라미가 오늘 밤 달 모양으로 가려진다(달 정보가 있을 때), 밤은 캐릭터가 곰
|
||||
- [ ] 말풍선 누름 → 1위 각의 계산 근거 시트
|
||||
@@ -34,7 +34,6 @@
|
||||
## 4. 오늘 탭: 각 줄·띠
|
||||
|
||||
- [ ] "오늘의 각" 동그라미 줄이 옆으로 밀리고, 1~3위 메달, 50점 미만은 회색 테두리, 누르면 계산 근거 시트
|
||||
- [ ] 지금 구간에 안 맞는 각(예: 아침의 야장각)은 줄 뒤쪽에 흐리게 "지금 아님", 메달 없음
|
||||
- [ ] "전체 보기" → 각 탭
|
||||
- [ ] 3번째 글 뒤 "이번 주 가까운 행사"(카드 → 주말·행사 탭), 6번째 뒤 "지금 뜨는 각 TOP 5"(카드 → 계산 근거), 9번째 뒤 "이번 주 계절 이야기"(카드 → 읽을거리)
|
||||
- [ ] 글이 9개보다 적으면 남은 띠가 피드 맨 끝에 붙는다
|
||||
@@ -46,8 +45,7 @@
|
||||
- [ ] 2장 이상이면 오른쪽 위 "1/N", 밀면 숫자가 바뀐다. 1장짜리는 밀리지 않는다
|
||||
- [ ] 오늘 날씨: 시간별 4칸(주황 막대 높이가 기온 비례), 저녁 칸 살구색·밤 칸 보라색
|
||||
- [ ] 각: "오늘의 각 · N위", 큰 점수, "계산 근거 보기" → 계산 근거 시트
|
||||
- [ ] 노을: 노을 점수와 시각 칸들 (해 뜨기 전·밤엔 "내일 일출"/"오늘 일출", 명소 장 없음) / 주말 예보: 토·일 칸("비 N% · 일교차 N°") + 검은 팁 줄
|
||||
- [ ] 오늘 밤 달: "오늘 밤은 (모양), (잘 보이는지)"(예: 흐려서 구름에 가려요 · 새벽 2시에 떠요 · 밤 11시까지 보여요 · 해와 같은 쪽에 있어 안 보여요), 안 보일 땐 늘 이유가 붙는다, 달 뜸·짐 시각 줄, "밝기 %"는 어디에도 없다
|
||||
- [ ] 노을: 노을 점수와 시각 칸들 / 주말 예보: 토·일 칸("비 N% · 일교차 N°") + 검은 팁 줄
|
||||
- [ ] 주말 플랜: 시간·아이콘·제목·설명 줄, 사진이 있으면 작은 사진과 맨 아래 "사진 출처"
|
||||
- [ ] 행사·당일치기 사진 슬라이드: 사진 위 글자, 오른쪽 위 출처
|
||||
- [ ] 점선 밑줄 장소 이름 → 네이버 지도 검색이 새 탭으로
|
||||
@@ -89,19 +87,18 @@
|
||||
|
||||
## 9. 노을 탭
|
||||
|
||||
- [ ] 히어로 "오늘 노을 · 지역"(해 뜨기 전·블루아워 뒤엔 "… 일출"), 큰 점수 + "점 · 등급", 그 아래 "HH:MM 해 져요(떠요) · 하늘 상황", 상황에 따라 색이 다르고 아래 동네 실루엣
|
||||
- [ ] 흰 카드: 결론 + 이유, "예보 모델 N개 중 M개가 같은 예보"
|
||||
- [ ] "언제 보면 좋을까" 세 시각(해 짐·뜸 점만 주황) + 아래 골든아워·블루아워 뜻 두 줄(일출이면 일출 기준 설명), 더 나은 날이 있을 때만 분홍 안내 상자
|
||||
- [ ] 일출일 땐 가까운 노을 명소가 안 나온다
|
||||
- [ ] 히어로 "오늘 노을 · 지역", 큰 해 지는 시각, 하늘 상황 한 줄, 상황에 따라 색이 다르고 아래 동네 실루엣
|
||||
- [ ] 흰 카드: 결론 + 이유, "예보 모델 N개 중 M개가 같은 예보 · 노을 점수 N"
|
||||
- [ ] "언제 보면 좋을까" 세 시각(해 짐 점만 주황), 더 나은 날이 있을 때만 분홍 안내 상자
|
||||
- [ ] 가까운 노을 명소 최대 3곳("방향쪽" · "Nkm", 이름 → 네이버 지도), 전국 노을 순위 8곳(내 지역 흰 바탕 + "내 지역")
|
||||
|
||||
## 10. 각 탭
|
||||
|
||||
- [ ] "오늘 1~3위"(지금 구간 기준, 안 맞는 각 제외) 부제 "M월 D일 기준 · 지역", 받침대 2위 · 1위(가장 크고 노란 바탕) · 3위, 누르면 계산 근거
|
||||
- [ ] "오늘 1~3위" 부제 "M월 D일 기준 · 지역", 받침대 2위 · 1위(가장 크고 노란 바탕) · 3위, 누르면 계산 근거
|
||||
- [ ] 분야 칩 전체 · 밖에서 놀기 · 먹고 마시기 · 집안일 · 생활 고민 · 가을 각 → 3열 목록이 바뀐다
|
||||
- [ ] 목록 칸: 왼쪽 위 순위, 가을 핵심 각은 초록 "가을", 50점 미만 점수 회색, 지금 구간에 안 맞는 각은 맨 뒤 흐리게 "지금 아님"(순위 없음)
|
||||
- [ ] 목록 칸: 왼쪽 위 순위, 가을 핵심 각은 초록 "가을", 50점 미만 점수 회색
|
||||
- [ ] 맨 아래 "각 점수는 어떻게 매길까?" → 읽을거리 시트
|
||||
- [ ] 계산 근거 시트: 제목 "N위 이름", 지금 구간 설명, 레이더(요소 3개 이상), 오늘 아침·낮·저녁·밤 4칸(지금 칸 강조, 안 겹치는 구간 '–'), 날짜별 추이("예상" 표시), 구간 목록, 요소별 막대·비중, 계산 방법
|
||||
- [ ] 계산 근거 시트: 제목 "N위 이름", 지금 구간 설명, 레이더(요소 3개 이상), 날짜별 추이("예상" 표시), 구간 목록, 요소별 막대·비중, 계산 방법
|
||||
|
||||
## 11. 주말·행사 탭
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@
|
||||
|
||||
**조건 (0점·최대 N점)**
|
||||
- 각마다 "이 조건이면 0점" 또는 "이 조건이면 최대 N점"이 있습니다. 위 식으로 낸 점수와 상한 중 작은 값을 씁니다.
|
||||
- 조건에 쓰는 값: 비 올 확률(16개 각), 체감온도(4개, 구간 안 최저 또는 최고), 초미세먼지, 흐린 하늘 비율, 돌풍, 땅 표면 온도, 강풍 특보.
|
||||
- 조건에 쓰는 값과 쓰는 각 수: 비 올 확률 18, 바람 6, 체감온도 5(구간 안 최저 또는 최고), 초미세먼지 3, 강풍 특보 3, 돌풍 3, 흐린 하늘 비율 1, 땅 표면 온도 1. 조건이 있는 각은 34개 중 22개입니다.
|
||||
- 각별 조건은 `docs/각_계산기준.md`에 있습니다.
|
||||
|
||||
### 2-5. 하루를 네 구간으로 나눕니다
|
||||
@@ -178,6 +178,7 @@
|
||||
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시간만 골라 계산합니다. 예: 오후 5시(저녁 구간)의 야장각(18~24시)은 18시대만 봅니다.
|
||||
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) 순위, 피드 카드, 맨 위 1위에서 빠집니다. 각 탭 전체 목록에는 맨 뒤에 '지금 아님'으로, 하루 점수와 함께 남습니다.
|
||||
- **하루 점수**(내일·토·일 칸, '지금 아님' 각): 각의 시간대 전체로 계산한 점수입니다.
|
||||
- **햇빛·자외선·가시거리:** 10개 각(피크닉, 등산, 세차, 별보기, 빨래, 자전거, 가드닝, 사진산책, 드라이브, 물놀이)은 이 요소도 봅니다. 모두 2-3의 ② 방식입니다.
|
||||
- **'시간' 요소**는 날씨가 아닌 것을 넣는 칸입니다.
|
||||
|
||||
| 종류 | 식 | 쓰는 각 |
|
||||
@@ -216,7 +217,7 @@
|
||||
| 항목 | 식 | 뜻 |
|
||||
|---|---|---|
|
||||
| 물들 구름 | 20km 지점의 중간 구름과 높은 구름 중 큰 값 | 햇빛을 받아 붉게 물드는 구름 |
|
||||
| 물들 정도 | 물들 구름 0%면 0.2 → 50%에서 1.0까지 곧게 → 100%에서 0까지 곧게 | 반쯤 덮였을 때 가장 좋음 |
|
||||
| 물들 정도 | 물들 구름 0%면 0.4 → 50%에서 1.0까지 곧게 → 100%에서 0까지 곧게 | 반쯤 덮였을 때 가장 좋음. 구름 없는 맑은 하늘은 55점 안팎(은은함) |
|
||||
| 머리 위 막힘 | 1 − 0.8 × 20km 낮은 구름 ÷ 100 | 낮은 구름은 하늘을 가림 |
|
||||
| 빛 들어옴 | 1 − min(100km 낮은 구름 + 0.5 × 100km 중간 구름, 100) ÷ 100 | 먼 하늘이 막히면 햇빛이 못 들어옴 |
|
||||
|
||||
@@ -224,22 +225,25 @@
|
||||
|
||||
예보 모델 2개(일본 JMA, 독일 ICON)로 각각 계산해 평균을 냅니다.
|
||||
|
||||
**② 공기 보정 (곱하는 값)**
|
||||
**② 공기·장소 보정 (곱하는 값)**
|
||||
|
||||
| 조건 | 식 |
|
||||
평소 공기(가시거리 20km, 습도 60%)를 1.0으로 두고, 맑으면 올리고 뿌옇거나 습하면 내립니다. 기준점 사이는 곧게 잇고, 양 끝 밖은 끝 값 그대로입니다.
|
||||
|
||||
| 조건 | 기준점 |
|
||||
|---|---|
|
||||
| 가시거리 | 40km 이상 1.0 → 5km 이하 0.6, 사이는 곧게 |
|
||||
| 습도 | 50% 이하 1.0 → 90% 이상 0.75, 사이는 곧게 |
|
||||
| 가시거리 | 5km 0.8 · 20km 1.0 · 40km 1.12 |
|
||||
| 습도 | 40% 1.06 · 60% 1.0 · 90% 0.85 |
|
||||
| 비 갠 직후 | 해 지기 2~6시간 전 비 확률이 60% 이상이었고 그 시각 40% 미만이면 × 1.15 |
|
||||
| 서쪽이 트인 명소 | 구 중심 20km 안에 서쪽이 바다·강·전망대로 트인 노을 명소가 있으면 × 1.1 (노을만) |
|
||||
|
||||
값이 없는 조건은 건너뜁니다.
|
||||
|
||||
> **노을 점수** = min(100, 구름 점수 모델 평균 × 공기 보정)
|
||||
> **노을 점수** = min(100, 구름 점수 모델 평균 × 공기·장소 보정)
|
||||
|
||||
**예시: 분당구 10/12 노을**
|
||||
- 구름 점수 57 (구름은 알맞음)
|
||||
- 공기 보정 = 가시거리 6.5km → 0.62, 습도 80% → 0.81, 곱하면 0.50
|
||||
- 노을 점수 = 57 × 0.50 = **29점 → 잿빛** ("하늘이 뿌예서 색이 바래요")
|
||||
**예시**
|
||||
- 구름 점수 57 (구름은 알맞음), 가시거리 6.5km, 습도 80%, 근처에 서쪽 트인 명소 없음
|
||||
- 보정 = 가시거리 0.82 × 습도 0.90 = 0.74
|
||||
- 노을 점수 = 57 × 0.74 = **42점 → 은은함**
|
||||
|
||||
**③ 등급과 화면 문구**
|
||||
|
||||
@@ -258,7 +262,7 @@
|
||||
| 20km 낮은 구름 ≥ 60 | 구름이 낮게 깔려 있어요 |
|
||||
| 물들 구름 < 25 | 구름이 거의 없어요 |
|
||||
| 물들 구름 > 75 | 구름이 너무 두꺼워요 |
|
||||
| 공기 보정 < 0.7 | 하늘이 뿌예서 색이 바래요 |
|
||||
| 공기·장소 보정 < 0.7 (아주 뿌옇고 습한 날) | 하늘이 뿌예서 색이 바래요 |
|
||||
|
||||
- 큰 글씨 아래에는 오늘·내일·모레 세 칸을 그날 등급 색으로 칠해 보여 주고, 칸을 누르면 그날로 바뀝니다.
|
||||
- **무엇을 보여 주나:** 다음에 올 것입니다. 해 뜨기 전엔 오늘 일출, 블루아워가 끝나기 전엔 오늘 노을, 그 뒤엔 내일 일출. 일출도 같은 식이고 구름은 해 뜨는 쪽을 봅니다.
|
||||
@@ -382,27 +386,27 @@
|
||||
| 각 | 분류 | 하기 좋은 시간대 | 가장 크게 보는 요소 |
|
||||
|---|---|---|---|
|
||||
| 야장각 | 먹고 마시기 | 18~24시 | 기온 30% · 비 25% |
|
||||
| 피크닉각 | 밖에서 놀기 | 11~16시 | 비 25% · 기온 25% |
|
||||
| 피크닉각 | 밖에서 놀기 | 11~16시 | 비 20% · 기온 20% |
|
||||
| 치맥각 | 먹고 마시기 | 18~23시 | 기온 30% · 비 20% |
|
||||
| 산책각 | 밖에서 놀기 | 18~22시 | 기온 30% · 비 25% |
|
||||
| 환기각 | 집안일 | 10~18시 (2시간씩) | 미세먼지 45% · 비 15% |
|
||||
| 등산각 | 밖에서 놀기 | 7~12시 | 비 25% · 기온 25% |
|
||||
| 세차각 | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 비 60% · 습도 10% |
|
||||
| 등산각 | 밖에서 놀기 | 7~12시 | 비 20% · 기온 20% |
|
||||
| 세차각 | 집안일 | 9~18시 (비는 2일 뒤까지 봄) | 비 40% · 햇빛 10% |
|
||||
| 캠핑각 | 밖에서 놀기 | 18시~다음 날 8시 | 기온 30% · 비 25% |
|
||||
| 러닝각 | 밖에서 놀기 | 6~8시 / 19~22시 | 기온 35% · 비 20% |
|
||||
| 별보기각 | 밖에서 놀기 | 21시~다음 날 2시 | 달·시간 45% · 미세먼지 15% |
|
||||
| 짬뽕각 | 먹고 마시기 | 11~14시 / 17~20시 | 기온 40% · 비 25% |
|
||||
| 막걸리각 | 먹고 마시기 | 17~22시 | 비 50% · 습도 15% |
|
||||
| 뜨아각 | 먹고 마시기 | 7~10시 | 기온 50% · 바람 15% |
|
||||
| 빨래각 | 집안일 | 9~16시 | 비 30% · 바람 15% |
|
||||
| 자전거각 | 밖에서 놀기 | 9~19시 | 비 25% · 바람 25% |
|
||||
| 멍뭉산책각 | 밖에서 놀기 | 7~9시 / 17~20시 | 기온 35% · 비 25% |
|
||||
| 빨래각 | 집안일 | 9~16시 | 비 30% · 햇빛 25% |
|
||||
| 자전거각 | 밖에서 놀기 | 9~19시 | 비 20% · 바람 20% |
|
||||
| 멍뭉산책각 | 밖에서 놀기 | 7~9시 / 17~20시 | 기온 40% · 비 25% |
|
||||
| 김서림각 | 생활 고민 | 7~9시 | 기온 50% · 습도 30% |
|
||||
| 화장붕괴각 | 생활 고민 | 10~18시 | 기온 40% · 습도 35% |
|
||||
| 냉면각 | 먹고 마시기 | 11~14시 | 기온 55% · 습도 15% |
|
||||
| 택시대란각 | 생활 고민 | 22시~다음 날 2시 | 비 55% · 시간 15% |
|
||||
| 배달폭주각 | 생활 고민 | 17~21시 | 비 50% · 기온 20% |
|
||||
| 가드닝각 | 집안일 | 7~10시 | 비 30% · 기온 25% |
|
||||
| 가드닝각 | 집안일 | 7~10시 | 비 25% · 기온 20% |
|
||||
| 사진산책각 | 밖에서 놀기 | 해 지기 앞뒤 1시간 | 시간 30% · 비 25% |
|
||||
| 야구각 | 밖에서 놀기 | 18~22시 | 비 40% · 기온 25% |
|
||||
| 공부각 | 집안일 | 13~18시 | 비 35% · 기온 35% |
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
| twitter:card | summary_large_image | ○ |
|
||||
| twitter:title / description / image | og 값과 같음 | △ |
|
||||
| 구글 소유 확인 | google-site-verification | ○ |
|
||||
| 네이버 소유 확인 | naver-site-verification | ○ (배포 전) |
|
||||
| 네이버 소유 확인 | naver-site-verification | ○ |
|
||||
| theme-color | #d6ebff | ○ |
|
||||
| manifest | 이름 '날씨각', 색 #d6ebff | △ |
|
||||
|
||||
|
||||
@@ -15,14 +15,14 @@
|
||||
<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="theme-color" content="#d6ebff" />
|
||||
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||
<meta name="description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" />
|
||||
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<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:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
||||
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
||||
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
||||
@@ -31,7 +31,7 @@
|
||||
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
|
||||
<meta name="twitter:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
|
||||
<meta name="twitter:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
|
||||
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
|
||||
<meta property="og:locale" content="ko_KR" />
|
||||
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
||||
@@ -44,6 +44,7 @@
|
||||
"@type": "WebSite",
|
||||
"@id": "%VITE_SITE_URL%/#website",
|
||||
"name": "날씨각",
|
||||
"alternateName": ["날씨 각", "Nalssigak"],
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"inLanguage": "ko-KR",
|
||||
"publisher": { "@id": "%VITE_SITE_URL%/#organization" }
|
||||
@@ -59,7 +60,7 @@
|
||||
"@type": "WebApplication",
|
||||
"name": "날씨각",
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"description": "세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요.",
|
||||
"description": "날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요.",
|
||||
"applicationCategory": "WeatherApplication",
|
||||
"operatingSystem": "All",
|
||||
"inLanguage": "ko-KR",
|
||||
@@ -96,12 +97,18 @@
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root">
|
||||
<!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 -->
|
||||
<div id="boot" data-nosnippet role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif">
|
||||
<img src="/icons/rabbit.png" alt="" width="88" height="88" />
|
||||
<p style="margin:0">날씨 불러오는 중…</p>
|
||||
</div>
|
||||
<!-- 검색 결과 요약은 화면 글 대신 description 을 쓰게 한다 (지역 페이지는 서버가 오늘 날씨로 채움) -->
|
||||
<div id="root" data-nosnippet>
|
||||
<main>
|
||||
<h1>날씨각</h1>
|
||||
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
|
||||
<h2><a href="/gak">오늘의 각</a></h2>
|
||||
<p>세차각, 빨래각, 러닝각 등 34가지 일을 지금 동네 날씨로 점수 매겨요. 아침, 낮, 저녁, 밤마다 따로 알려 드려요.</p>
|
||||
<p>세차각, 빨래각, 러닝각, 우산각, 파전각처럼 오늘 하고 싶은 일을 지금 동네 날씨로 점수 매겨요. 아침, 낮, 저녁, 밤마다 따로 알려 드려요.</p>
|
||||
<h2><a href="/sky">노을</a></h2>
|
||||
<p>오늘 노을이 얼마나 붉게 물들지, 몇 시에 가장 붉은지, 가까운 노을 명소는 어디인지 알려 드려요. 사흘 치를 미리 볼 수 있어요.</p>
|
||||
<h2><a href="/week">주말·행사</a></h2>
|
||||
|
||||
@@ -31,9 +31,26 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# SPA: /indices, /sky 같은 주소로 새로고침해도 index.html을 돌려준다
|
||||
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
|
||||
location ~ ^/today/[a-z]+/[a-z]+(/[a-z]+)?$ {
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api http://backend:9800;
|
||||
proxy_pass $api/v1/seo$uri;
|
||||
proxy_set_header Host $host;
|
||||
proxy_connect_timeout 3s;
|
||||
proxy_read_timeout 20s;
|
||||
proxy_intercept_errors on;
|
||||
error_page 404 500 502 503 504 = @static;
|
||||
}
|
||||
|
||||
location @static {
|
||||
add_header Cache-Control "no-cache";
|
||||
try_files $uri.html /index.html;
|
||||
}
|
||||
|
||||
# SPA: /gak 처럼 빌드 때 만든 페이지별 HTML(gak.html)이 있으면 그것을, 없으면 index.html. 폴더는 안 찾는다 (/season 이 이미지 폴더 public/season 과 겹쳐 403)
|
||||
location / {
|
||||
add_header Cache-Control "no-cache";
|
||||
try_files $uri $uri/ /index.html;
|
||||
try_files $uri $uri.html /index.html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
5d75f7cb25f648da8cd5dc1c71f1af66
|
||||
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,60 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>개인정보처리방침 - 날씨각</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<style>
|
||||
body { margin: 0; padding: 32px 20px 64px; font: 15px/1.7 -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif; color: #28304a; background: #f1f8ff; }
|
||||
main { max-width: 720px; margin: 0 auto; }
|
||||
h1 { font-size: 26px; margin: 0 0 4px; }
|
||||
h2 { font-size: 18px; margin: 32px 0 8px; }
|
||||
table { width: 100%; border-collapse: collapse; background: #fff; font-size: 14px; }
|
||||
th, td { border: 1px solid #d9e5f4; padding: 8px 10px; text-align: left; vertical-align: top; }
|
||||
th { background: #e6f1ff; }
|
||||
.muted { color: #5a6380; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>개인정보처리방침</h1>
|
||||
<p class="muted">시행일: 2026년 10월 13일</p>
|
||||
|
||||
<p>AIO2O(이하 "회사")는 날씨각 웹 서비스(이하 "웹")와 날씨각 Wear OS 앱(이하 "워치 앱")을 운영하며, 「개인정보 보호법」에 따라 이용자의 개인정보를 다음과 같이 처리합니다.</p>
|
||||
|
||||
<h2>1. 수집하는 개인정보와 목적</h2>
|
||||
<table>
|
||||
<tr><th>구분</th><th>항목</th><th>목적</th></tr>
|
||||
<tr><td>웹 회원가입·로그인</td><td>아이디, 비밀번호(암호화 저장), 닉네임 / Google 로그인 시 Google 계정 고유 식별자</td><td>회원 식별, 좋아요·저장·댓글 기능 제공</td></tr>
|
||||
<tr><td>웹·워치 앱 위치</td><td>대략적인 위치(위도·경도)</td><td>가장 가까운 지역(구)의 날씨와 주변 축제를 보여주기 위해 사용합니다. 위치 좌표는 지역을 찾는 데만 쓰고 서버에 저장하지 않습니다.</td></tr>
|
||||
<tr><td>서비스 이용</td><td>접속 기록(IP 주소, 접속 시각, 브라우저 정보), 선택한 지역</td><td>서비스 운영, 오류 확인, 이용 통계</td></tr>
|
||||
</table>
|
||||
<p>위치 권한은 선택 사항입니다. 허용하지 않아도 지역을 직접 골라 이용할 수 있습니다. 워치 앱은 회원가입이나 로그인 없이 이용할 수 있습니다.</p>
|
||||
|
||||
<h2>2. 보유 및 이용 기간</h2>
|
||||
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
|
||||
|
||||
<h2>3. 제3자 제공 및 처리 위탁</h2>
|
||||
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
|
||||
|
||||
<h2>4. 파기 절차 및 방법</h2>
|
||||
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
|
||||
|
||||
<h2>5. 이용자의 권리</h2>
|
||||
<p>이용자는 언제든지 자신의 개인정보 열람, 정정, 삭제, 처리 정지와 회원 탈퇴를 요청할 수 있습니다. 아래 연락처로 요청하시면 지체 없이 처리합니다. 워치 앱의 위치 권한은 기기 설정에서 언제든지 끌 수 있습니다.</p>
|
||||
|
||||
<h2>6. 안전성 확보 조치</h2>
|
||||
<p>비밀번호는 암호화하여 저장하고, 개인정보에 접근할 수 있는 인원을 최소한으로 제한합니다.</p>
|
||||
|
||||
<h2>7. 아동의 개인정보</h2>
|
||||
<p>회사는 만 14세 미만 아동의 개인정보를 알면서 수집하지 않습니다.</p>
|
||||
|
||||
<h2>8. 개인정보 보호책임자</h2>
|
||||
<p>운영자: AIO2O<br />이메일: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></p>
|
||||
|
||||
<h2>9. 변경 안내</h2>
|
||||
<p>이 방침이 바뀌면 시행 7일 전부터 이 페이지에 알립니다.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url><loc>https://weather.o2o.kr/</loc></url>
|
||||
</urlset>
|
||||
@@ -0,0 +1,214 @@
|
||||
[
|
||||
{
|
||||
"name": "야장각",
|
||||
"description": "바깥 자리에 앉기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "피크닉각",
|
||||
"description": "낮 동안 돗자리 펴고 쉬기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "치맥각",
|
||||
"description": "저녁에 바깥에서 치킨과 맥주가 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "산책각",
|
||||
"description": "걷기 좋은 정도 (해 진 뒤 기준)"
|
||||
},
|
||||
{
|
||||
"name": "환기각",
|
||||
"description": "창문 열어 공기 바꾸기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "등산각",
|
||||
"description": "산에 오르기 좋은 정도 (오전 기준)"
|
||||
},
|
||||
{
|
||||
"name": "세차각",
|
||||
"description": "세차한 뒤 깨끗함이 오래가는 정도"
|
||||
},
|
||||
{
|
||||
"name": "캠핑각",
|
||||
"description": "하룻밤 캠핑하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "러닝각",
|
||||
"description": "뛰기 좋은 정도 (아침·저녁 중 좋은 쪽)"
|
||||
},
|
||||
{
|
||||
"name": "별보기각",
|
||||
"description": "밤하늘 별이 잘 보이는 정도"
|
||||
},
|
||||
{
|
||||
"name": "짬뽕각",
|
||||
"description": "뜨끈한 국물이 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "막걸리각",
|
||||
"description": "비 오는 날 파전에 막걸리가 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "뜨아각",
|
||||
"description": "아이스 대신 따뜻한 커피로 바꿀 때가 된 정도"
|
||||
},
|
||||
{
|
||||
"name": "빨래각",
|
||||
"description": "빨래가 잘 마르는 정도"
|
||||
},
|
||||
{
|
||||
"name": "자전거각",
|
||||
"description": "자전거 타기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "멍뭉산책각",
|
||||
"description": "반려견과 산책하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "김서림각",
|
||||
"description": "안경에 김이 서리기 쉬운 정도"
|
||||
},
|
||||
{
|
||||
"name": "화장붕괴각",
|
||||
"description": "화장이 무너지기 쉬운 정도"
|
||||
},
|
||||
{
|
||||
"name": "냉면각",
|
||||
"description": "시원한 냉면이 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "택시대란각",
|
||||
"description": "밤늦게 택시 잡기 어려운 정도"
|
||||
},
|
||||
{
|
||||
"name": "배달폭주각",
|
||||
"description": "배달 주문이 몰리는 정도"
|
||||
},
|
||||
{
|
||||
"name": "가드닝각",
|
||||
"description": "화분 돌보고 물 주기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "사진산책각",
|
||||
"description": "노을 무렵 사진 찍으며 걷기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "야구각",
|
||||
"description": "야구장 직관하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "공부각",
|
||||
"description": "밖에 나가기 싫어서 공부가 잘되는 정도"
|
||||
},
|
||||
{
|
||||
"name": "넷플릭스각",
|
||||
"description": "집에서 영화 보기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "군밤각",
|
||||
"description": "길거리 군밤이 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "골프각",
|
||||
"description": "필드에서 라운딩하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "집콕각",
|
||||
"description": "나가기 싫어 집에 있고 싶은 정도"
|
||||
},
|
||||
{
|
||||
"name": "낚시각",
|
||||
"description": "물가에서 낚시하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "드라이브각",
|
||||
"description": "창문 열고 드라이브하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "연날리기각",
|
||||
"description": "연 날리기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "물놀이각",
|
||||
"description": "바다·계곡에서 물놀이하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "김장각",
|
||||
"description": "김장하기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "꽃구경각",
|
||||
"description": "꽃 보러 나들이 가기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "이불빨래각",
|
||||
"description": "이불처럼 두꺼운 빨래가 하루 만에 마르는 정도"
|
||||
},
|
||||
{
|
||||
"name": "빙수각",
|
||||
"description": "시원한 빙수가 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "실내건조각",
|
||||
"description": "밖에 못 너는 날, 집 안에서 빨래 말리기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "한강밤바람각",
|
||||
"description": "강가에서 밤바람 쐬기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "단풍각",
|
||||
"description": "단풍 구경 가기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "억새각",
|
||||
"description": "해 지기 전후, 억새밭 걷기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "군고구마각",
|
||||
"description": "따끈한 군고구마가 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "해돋이각",
|
||||
"description": "해 뜰 무렵, 해돋이 보러 가기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "눈사람각",
|
||||
"description": "눈 온 날 낮, 눈사람 만들기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "붕어빵각",
|
||||
"description": "붕어빵이 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "귤까먹기각",
|
||||
"description": "이불 속에서 귤 까먹고 싶은 정도"
|
||||
},
|
||||
{
|
||||
"name": "우산각",
|
||||
"description": "밖에 나갈 때 우산을 챙겨야 하는 정도"
|
||||
},
|
||||
{
|
||||
"name": "파전각",
|
||||
"description": "비 오는 날 파전이 당기는 정도"
|
||||
},
|
||||
{
|
||||
"name": "감성노래각",
|
||||
"description": "비 오는 날 감성 노래 듣기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "트로트각",
|
||||
"description": "나들이 가며 트로트 크게 틀고 싶은 정도"
|
||||
},
|
||||
{
|
||||
"name": "싱잉인더레인각",
|
||||
"description": "비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "우산분실각",
|
||||
"description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도"
|
||||
},
|
||||
{
|
||||
"name": "교통체증각",
|
||||
"description": "출퇴근길 비·눈·추위로 차가 막히는 정도"
|
||||
}
|
||||
]
|
||||
@@ -12,6 +12,7 @@ export default function App() {
|
||||
<Routes>
|
||||
<Route element={<BLayout />}>
|
||||
<Route index element={<TodayPage />} />
|
||||
<Route path="today/:sido/:place" element={<TodayPage />} />
|
||||
<Route path="gak" element={<GakPage />} />
|
||||
<Route path="sky" element={<SkyPage />} />
|
||||
<Route path="week" element={<WeekPage />} />
|
||||
|
||||
@@ -595,6 +595,14 @@ export type Hero = {
|
||||
* Weather Score
|
||||
*/
|
||||
weather_score?: number | null;
|
||||
/**
|
||||
* Weather Slots
|
||||
*
|
||||
* 오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}
|
||||
*/
|
||||
weather_slots?: {
|
||||
[key: string]: number;
|
||||
};
|
||||
top1?: TopIndex | null;
|
||||
/**
|
||||
* Bubble
|
||||
@@ -618,6 +626,12 @@ export type Hero = {
|
||||
* 히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저
|
||||
*/
|
||||
stats?: Array<HeroStat>;
|
||||
/**
|
||||
* Status
|
||||
*
|
||||
* 히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)
|
||||
*/
|
||||
status?: Array<HeroStat>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -741,6 +755,18 @@ export type IndexSummary = {
|
||||
* Is Core
|
||||
*/
|
||||
is_core: boolean;
|
||||
/**
|
||||
* Season
|
||||
*
|
||||
* 지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음
|
||||
*/
|
||||
season?: string | null;
|
||||
/**
|
||||
* In Season
|
||||
*
|
||||
* false 면 제철이 아니라 순위 밖, 목록 맨 끝
|
||||
*/
|
||||
in_season?: boolean;
|
||||
/**
|
||||
* Score
|
||||
*/
|
||||
@@ -2409,6 +2435,22 @@ export type TopIndex = {
|
||||
* 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수
|
||||
*/
|
||||
active?: boolean;
|
||||
/**
|
||||
* Slots
|
||||
*
|
||||
* 오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음
|
||||
*/
|
||||
slots?: {
|
||||
[key: string]: number;
|
||||
};
|
||||
/**
|
||||
* Slot Ranks
|
||||
*
|
||||
* 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음
|
||||
*/
|
||||
slot_ranks?: {
|
||||
[key: string]: number;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -3047,7 +3089,7 @@ export type ListIndicesData = {
|
||||
/**
|
||||
* Core
|
||||
*
|
||||
* 이번 계절 핵심 지수만
|
||||
* 지금 제철인 각만
|
||||
*/
|
||||
core?: boolean;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { NavLink, Outlet, useLocation } from 'react-router'
|
||||
import { useIsFetching, useQuery } from '@tanstack/react-query'
|
||||
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { kindOfHour, kst, type TimeKind } from './lib'
|
||||
import { kindOfHour, kst, seasonOf, type TimeKind } from './lib'
|
||||
import './b.css'
|
||||
import { AuthProvider } from './auth'
|
||||
import { RegionProvider } from './region'
|
||||
@@ -11,7 +13,7 @@ import { useSheet } from './sheetContext'
|
||||
import { SheetProvider } from './Sheets'
|
||||
import { SkyContext, useSky } from './skyContext'
|
||||
import { PinIcon, TabIcon } from './svg'
|
||||
import { Avatar, Skel } from './ui'
|
||||
import { Avatar, Ic, Skel } from './ui'
|
||||
|
||||
const TABS = [
|
||||
{ to: '/sky', key: 'sky', label: '노을', title: '노을' },
|
||||
@@ -22,6 +24,22 @@ const TABS = [
|
||||
{ to: '/season', key: 'season', label: '계절·상식', title: '계절·상식' },
|
||||
] as const
|
||||
|
||||
/** 로고 옆 계절 칩: 계절 이름과 지금 절기. 누르면 이번 주 절기 창. 좁은 화면에선 절기를 뺀다 */
|
||||
function SeasonChip() {
|
||||
const { open } = useSheet()
|
||||
const week = useQuery(getSeasonWeekOptions())
|
||||
const [month] = useState(() => kst(new Date()).mo)
|
||||
const [name, icon] = seasonOf(month)
|
||||
const term = week.data?.term_now?.name
|
||||
return (
|
||||
<button type="button" onClick={() => open({ type: 'seasonWeek' })} aria-label={`지금 ${name}${term ? `, ${term}` : ''}. 이번 주 절기 보기`} className="flex shrink-0 cursor-pointer items-center gap-1 rounded-full bg-white/70 py-1 pr-2.5 pl-1.5 text-[13px] font-extrabold whitespace-nowrap shadow-[0_4px_10px_rgb(40_48_74/0.06)]">
|
||||
<Ic name={icon} className="size-[18px]" />
|
||||
{name}
|
||||
{term && <span className="hidden font-bold opacity-70 min-[400px]:inline">· {term}</span>}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function TopBar() {
|
||||
const { pathname } = useLocation()
|
||||
const { region, locateStatus } = useRegion()
|
||||
@@ -30,16 +48,17 @@ function TopBar() {
|
||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2.5 px-4 pt-[env(safe-area-inset-top,0px)]">
|
||||
{tab?.title ? <h1 className="font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
|
||||
{tab?.title ? <h1 className="shrink-0 font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="shrink-0 font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||
<SeasonChip />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'region' })}
|
||||
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
||||
className="ml-auto flex cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
||||
className="ml-auto flex shrink-0 cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
||||
>
|
||||
<PinIcon className="size-3.5" />
|
||||
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : region.name}
|
||||
<PinIcon className="size-3.5 shrink-0" />
|
||||
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>}
|
||||
</button>
|
||||
{mePending ? (
|
||||
<Skel shape className="size-9 shrink-0 rounded-full" />
|
||||
@@ -151,12 +170,48 @@ const NOTCH_BG: Record<TimeKind, string> = {
|
||||
night: '#0e1433',
|
||||
}
|
||||
|
||||
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */
|
||||
function FirstLoad() {
|
||||
const fetching = useIsFetching()
|
||||
const { kind } = useSky()
|
||||
const [started, setStarted] = useState(false)
|
||||
const [done, setDone] = useState(false)
|
||||
const [gone, setGone] = useState(false)
|
||||
// 받기 시작했다가 받는 게 없어지면 끝 (렌더 중에 바로 맞춘다)
|
||||
if (fetching > 0 && !started) setStarted(true)
|
||||
if (fetching === 0 && started && !done) setDone(true)
|
||||
// 앱이 떴으니 index.html 의 첫 화면은 걷는다 (이 덮개가 이어받는다)
|
||||
useEffect(() => document.getElementById('boot')?.remove(), [])
|
||||
// 느린 망에서도 10초 넘게 막지 않는다 (그 뒤는 화면 안 스켈레톤이 맡는다)
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => setDone(true), 10000)
|
||||
return () => clearTimeout(id)
|
||||
}, [])
|
||||
if (gone) return null
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
onTransitionEnd={() => done && setGone(true)}
|
||||
className={cx('fixed inset-0 z-50 flex flex-col items-center justify-center gap-3 backdrop-blur-[6px] transition-opacity duration-400', done && 'pointer-events-none opacity-0')}
|
||||
style={{ backgroundColor: `color-mix(in srgb, ${NOTCH_BG[kind]} 72%, transparent)` }}
|
||||
>
|
||||
<Ic name={kind === 'night' ? 'bear' : 'rabbit'} className="b-hop w-[88px]" />
|
||||
<p className="m-0 font-jua text-[19px]">날씨 불러오는 중…</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { pathname } = useLocation()
|
||||
const { kind } = useSky()
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [pathname])
|
||||
// 지금 보고 있는 탭을 다시 누르면 맨 위로
|
||||
const toTopIfHere = (to: string) => () => {
|
||||
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
useEffect(() => {
|
||||
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
|
||||
}, [kind])
|
||||
@@ -164,6 +219,7 @@ function Shell() {
|
||||
return (
|
||||
<div className="min-h-dvh text-(--ink)">
|
||||
<SkyBg />
|
||||
<FirstLoad />
|
||||
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
|
||||
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
|
||||
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
|
||||
@@ -176,14 +232,14 @@ function Shell() {
|
||||
{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]">
|
||||
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}>
|
||||
<span className="b-keep-bg 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]')}>
|
||||
<NavLink key={t.key} to={t.to} onClick={toTopIfHere(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>
|
||||
|
||||
@@ -3,21 +3,22 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { loadOf, MEDALS } from './lib'
|
||||
import { kst, loadOf, MEDALS, seasonOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
||||
|
||||
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core'
|
||||
|
||||
const CATS = [
|
||||
// 마지막 칩은 지금 계절의 제철 각 (예: 가을 각)
|
||||
const CATS: readonly (readonly [Cat, string])[] = [
|
||||
['all', '전체'],
|
||||
['out', '밖에서 놀기'],
|
||||
['food', '먹고 마시기'],
|
||||
['home', '집안일'],
|
||||
['life', '생활 고민'],
|
||||
['core', '가을 각'],
|
||||
] as const
|
||||
['core', `${seasonOf(kst(new Date()).mo)[0]} 각`],
|
||||
]
|
||||
|
||||
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE }
|
||||
|
||||
@@ -26,11 +27,11 @@ const GRID_SKELS = Array.from({ length: 9 }, (_, i) => i)
|
||||
/** 1~3위 받침대와 같은 칸(가운데가 높은 3칸)의 스켈레톤 */
|
||||
function PodiumSkel() {
|
||||
return (
|
||||
<div className="grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3" aria-hidden="true">
|
||||
<div className="grid grid-cols-[1fr_1.15fr_1fr] gap-1.5 px-3 pt-3" aria-hidden="true">
|
||||
{[1, 0, 2].map((k) => (
|
||||
<span key={k} className={cx('flex flex-col items-center rounded-3xl bg-white px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'py-4' : 'py-3')}>
|
||||
<span key={k} className={cx('flex flex-col items-center rounded-3xl bg-white px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'py-4' : 'mt-6 py-3')}>
|
||||
<Skel shape className={cx('aspect-square rounded-full', k === 0 ? 'w-20' : 'w-[62px]')} />
|
||||
<b className="mt-1.5 font-jua text-base font-normal">
|
||||
<b className="mt-1.5 flex flex-1 items-center font-jua text-base font-normal">
|
||||
<Skel className="w-16" />
|
||||
</b>
|
||||
<em className="font-bagel text-[30px] leading-[1.05] not-italic">
|
||||
@@ -90,7 +91,7 @@ export function GakPage() {
|
||||
<StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} className="inset-x-3 top-3 bottom-0" />
|
||||
)
|
||||
) : (
|
||||
<div className={cx('grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
||||
<div className={cx('grid grid-cols-[1fr_1.15fr_1fr] gap-1.5 px-3 pt-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
||||
{[1, 0, 2].map((k) => {
|
||||
const g = top[k]
|
||||
return (
|
||||
@@ -98,13 +99,13 @@ export function GakPage() {
|
||||
key={g.index_id}
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: g.index_id })}
|
||||
className={cx('flex cursor-pointer flex-col items-center rounded-3xl px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'bg-[linear-gradient(180deg,#fff1c4,#fff)] py-4' : 'bg-white py-3')}
|
||||
className={cx('flex cursor-pointer flex-col items-center rounded-3xl px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'bg-[linear-gradient(180deg,#fff1c4,#fff)] py-4' : 'mt-6 bg-white py-3')}
|
||||
>
|
||||
<span className="relative">
|
||||
<Ic name={g.icon} className={cx('drop-shadow-[0_10px_12px_rgb(40_48_74/0.15)]', k === 0 ? 'w-20' : 'w-[62px]')} />
|
||||
<Ic name={MEDALS[k]} className="absolute -top-1.5 -left-3 w-7" />
|
||||
</span>
|
||||
<b className="mt-1.5 font-jua text-base font-normal">
|
||||
<b className="mt-1.5 flex flex-1 items-center font-jua text-base font-normal">
|
||||
{k + 1}위 {g.name}
|
||||
</b>
|
||||
<em className="font-bagel text-[30px] leading-[1.05] text-(--orange) not-italic">{g.score}</em>
|
||||
@@ -124,15 +125,15 @@ export function GakPage() {
|
||||
<div className={cx('grid grid-cols-3 gap-2 p-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
|
||||
{items.map((g) => {
|
||||
return (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]', !g.active && 'opacity-55')}>
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, ${g.in_season === false ? '제철 아님' : '지금 시간대 아님'}`} className={cx('relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]', !g.active && 'opacity-55')}>
|
||||
{g.active && <span className="absolute top-[7px] left-[9px] font-jua text-[13px] text-(--ink3)">{g.rank}</span>}
|
||||
{g.is_core && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">가을</span>}
|
||||
{g.season && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</span>}
|
||||
<Ic name={g.icon} className="w-[50px]" />
|
||||
<b className="mt-1 font-jua text-[15px] font-normal">{g.name}</b>
|
||||
{g.active ? (
|
||||
<em className={cx('font-bagel text-[22px] leading-[1.1] not-italic', g.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{g.score}</em>
|
||||
) : (
|
||||
<small className="py-1 text-[12px] leading-[1.1] font-extrabold text-(--ink3)">지금 아님</small>
|
||||
<small className="py-1 text-[12px] leading-[1.1] font-extrabold text-(--ink3)">{g.in_season === false ? '제철 아님' : '지금 아님'}</small>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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 regionPages from '../../seo/region.json'
|
||||
import { setTokens, subscribeAuth } from '../api/auth'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import {
|
||||
@@ -24,7 +25,7 @@ import { track } from '../lib/analytics'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { ownPage, useRegion } from './regionContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
@@ -133,6 +134,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
</div>
|
||||
)}
|
||||
{!state && <RegionLinks />}
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
@@ -405,7 +407,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
<div key={f.axis} className="grid grid-cols-[84px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||
<span>{f.label}</span>
|
||||
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${f.value}%` }} />
|
||||
<s className="b-keep-bg block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${f.value}%` }} />
|
||||
</i>
|
||||
<em className="text-right text-xs text-(--ink2) not-italic">비중 {f.weight}%</em>
|
||||
<p className="col-start-2 col-end-4 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{f.note}</p>
|
||||
@@ -987,6 +989,27 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
/* ---------- 지역 ---------- */
|
||||
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
|
||||
|
||||
/** 구 코드 → 그 구의 지역 페이지 주소 */
|
||||
const pageHref = (code: string) => {
|
||||
const p = ownPage(code)
|
||||
return p ? `/today/${p.path}` : '/'
|
||||
}
|
||||
|
||||
/** 지역 바꾸기가 닫혀 있을 때도 지역 페이지 링크를 HTML에 둔다 (검색 로봇이 링크를 따라가게) */
|
||||
function RegionLinks() {
|
||||
return (
|
||||
<nav aria-label="지역별 오늘 날씨">
|
||||
<ul>
|
||||
{regionPages.map((p) => (
|
||||
<li key={p.path}>
|
||||
<a href={`/today/${p.path}`}>{p.name} 오늘 날씨</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||
const { me, logout } = useAuth()
|
||||
@@ -1018,10 +1041,11 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
<ul className={cx('mt-2 flex flex-col transition-opacity', list.isPlaceholderData && 'opacity-60')}>
|
||||
{regions.map((r) => (
|
||||
<li key={r.code}>
|
||||
<button
|
||||
type="button"
|
||||
<a
|
||||
href={pageHref(r.code)}
|
||||
aria-current={r.code === region.code ? 'true' : undefined}
|
||||
onClick={() => {
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'list' })
|
||||
onDone()
|
||||
@@ -1030,7 +1054,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
>
|
||||
{r.name}
|
||||
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
||||
</button>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -34,12 +34,12 @@ const THREE = [0, 1, 2]
|
||||
const FOUR = [0, 1, 2, 3]
|
||||
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i)
|
||||
|
||||
/** 점수 등급별 하늘색: 히어로 배경과 3일 타일이 같은 색 */
|
||||
/** 점수 등급별 하늘색: 히어로 배경과 3일 타일이 같은 색. b-keep-bg 는 밤 화면에서도 이 색을 지킨다 */
|
||||
const GRADE_SKY: Record<string, { hero: string; tile: string }> = {
|
||||
잿빛: { hero: 'bg-[linear-gradient(180deg,#6f7690,#9aa0b4_55%,#b9b4c0)]', tile: 'bg-[linear-gradient(160deg,#8f8aa5,#b9b0bf)]' },
|
||||
은은함: { hero: 'bg-[linear-gradient(180deg,#4b5aa8,#7f86c6_40%,#e9b9a8_78%,#ffb27a)]', tile: 'bg-[linear-gradient(160deg,#7f86c6,#e9b9a8_70%,#f6b07a)]' },
|
||||
고움: { hero: 'bg-[linear-gradient(180deg,#5b3f9e,#c2559a_45%,#ff7a6a_78%,#ffb35c)]', tile: 'bg-[linear-gradient(160deg,#5b3f9e,#c2559a_55%,#ff7a6a)]' },
|
||||
붉음: { hero: 'bg-[linear-gradient(180deg,#4a2a8a,#b0306a_40%,#ff4a3a_72%,#ff9a3c)]', tile: 'bg-[linear-gradient(160deg,#4a2a8a,#b0306a_50%,#ff4a3a)]' },
|
||||
잿빛: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#6f7690,#9aa0b4_55%,#b9b4c0)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#8f8aa5,#b9b0bf)]' },
|
||||
은은함: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#4b5aa8,#7f86c6_40%,#e9b9a8_78%,#ffb27a)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#7f86c6,#e9b9a8_70%,#f6b07a)]' },
|
||||
고움: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#5b3f9e,#c2559a_45%,#ff7a6a_78%,#ffb35c)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#5b3f9e,#c2559a_55%,#ff7a6a)]' },
|
||||
붉음: { hero: 'b-keep-bg bg-[linear-gradient(180deg,#4a2a8a,#b0306a_40%,#ff4a3a_72%,#ff9a3c)]', tile: 'b-keep-bg bg-[linear-gradient(160deg,#4a2a8a,#b0306a_50%,#ff4a3a)]' },
|
||||
}
|
||||
const skyOf = (p?: SkyPlanData) => GRADE_SKY[p?.grade_label ?? ''] ?? GRADE_SKY['은은함']
|
||||
|
||||
|
||||
@@ -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, HeroStat as HeroStatData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
|
||||
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } 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'
|
||||
@@ -10,29 +10,22 @@ import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { deg, skyText, slotAt } from './weatherText'
|
||||
import { deg, slotAt } from './weatherText'
|
||||
|
||||
type Mode = 'now' | TimeKind
|
||||
|
||||
const MODES: [Mode, string][] = [
|
||||
['now', '지금'],
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['sunset', '저녁'],
|
||||
['night', '밤'],
|
||||
]
|
||||
|
||||
// 미리보기 시간대마다 보여 줄 시계와 그 시각의 예보 칸
|
||||
const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }> = {
|
||||
morning: { label: '아침', clock: '07:40', hour: 7 },
|
||||
day: { label: '낮', clock: '13:20', hour: 13 },
|
||||
sunset: { label: '저녁', clock: '18:25', hour: 18 },
|
||||
night: { label: '밤', clock: '22:10', hour: 22 },
|
||||
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
|
||||
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
|
||||
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
|
||||
morning: { label: '아침', hour: 7 },
|
||||
day: { label: '낮', hour: 13 },
|
||||
sunset: { label: '저녁', hour: 18 },
|
||||
night: { label: '밤', hour: 22 },
|
||||
}
|
||||
|
||||
// 히어로 칸을 받아 오는 동안 자리만 잡아 둔다
|
||||
const STAT_HOLD = ['a']
|
||||
const MUGGY = 75 // 불쾌지수 이 이상이면 경고 색
|
||||
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
|
||||
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` }))
|
||||
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` }))
|
||||
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
|
||||
@@ -71,33 +64,82 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
|
||||
|
||||
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Load; todayLoad: Load }
|
||||
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
|
||||
const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
|
||||
|
||||
function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
|
||||
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
|
||||
const k = kind && SLOT_KEY[kind]
|
||||
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
|
||||
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
|
||||
return [
|
||||
...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank),
|
||||
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
|
||||
]
|
||||
}
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }
|
||||
|
||||
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
|
||||
|
||||
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
|
||||
function weatherOf(slot?: WeatherSlot): Weather {
|
||||
const r = slot?.rain_type
|
||||
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
|
||||
if (r === RainType.SNOW) return 'snow'
|
||||
if (r === RainType.SLEET) return 'sleet'
|
||||
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
|
||||
}
|
||||
|
||||
const WEATHER_ICON: Record<Weather, string> = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' }
|
||||
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
|
||||
const CLOUDS = [
|
||||
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
|
||||
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
|
||||
{ cls: 'top-[30px] left-[72%] h-7 w-[64px]', d: '.4s', f: '5.4s' },
|
||||
]
|
||||
const CLOUD_N: Record<Weather, number> = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 }
|
||||
|
||||
function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||
const { open } = useSheet()
|
||||
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 nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)
|
||||
const kind = mode === 'now' ? nowKind : mode
|
||||
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
|
||||
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
|
||||
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 top1 = hero?.top1
|
||||
const who = kind === 'night' ? 'bear' : 'rabbit'
|
||||
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
||||
// 지금은 가장 가까운 3시간 칸(17시면 18시 칸). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
||||
const slotOf = (k: TimeKind | 'now') => {
|
||||
if (k === 'now') {
|
||||
const known = slots.filter((x) => x.temp_c != null)
|
||||
const at = t.h + t.mi / 60
|
||||
return known.length ? known.reduce((a, b) => (Math.abs(kst(b.at).h - at) < Math.abs(kst(a.at).h - at) ? b : a)) : undefined
|
||||
}
|
||||
const h = PREVIEW[k].hour
|
||||
const s = slots.length ? slotAt(slots, h) : undefined
|
||||
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s)
|
||||
}
|
||||
const weather = weatherOf(slotOf(mode))
|
||||
const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]]
|
||||
const score = slotScore ?? hero?.weather_score
|
||||
const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active)
|
||||
const top1 = slotTop ?? hero?.top1
|
||||
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
|
||||
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 tempChip = temp != null ? `${deg(temp)}${slot ? ` ${skyText(slot)}` : ''}` : null
|
||||
const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
// 말풍선 머리말은 칸 이름 그대로: 지금은 / 아침은 / 낮은 / 저녁은 / 밤은
|
||||
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
|
||||
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
const status = hero?.status ?? []
|
||||
const rain = weather === 'rain' || weather === 'sleet'
|
||||
const snow = weather === 'snow' || weather === 'sleet'
|
||||
|
||||
// 시안 A: 점수 해가 주인공. 위에 시간대 탭과 날짜, 가운데 큰 해, 아래 칩 한 줄과 캐릭터 말풍선(1위 각)
|
||||
// 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로)
|
||||
return (
|
||||
<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-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind} data-sky={weather}>
|
||||
<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} />
|
||||
@@ -106,19 +148,20 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
<span key={i} className="b-shoot" style={s} />
|
||||
))}
|
||||
</div>
|
||||
<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" 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>
|
||||
<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>
|
||||
{(rain || snow) && (
|
||||
<div className="pointer-events-none absolute inset-0 z-[2]" aria-hidden="true">
|
||||
{rain && DROPS.map((s, i) => <i key={i} className="b-drop" style={s} />)}
|
||||
{snow && FLAKES.map((s, i) => <i key={i} className="b-flake" style={s} />)}
|
||||
</div>
|
||||
)}
|
||||
<p className="relative z-[3] m-0 text-[14px] font-bold opacity-80">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
|
||||
</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')}>
|
||||
<div className="relative h-[146px]">
|
||||
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
|
||||
<span key={c.cls} className={cx('b-cloud b-fall z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true" />
|
||||
))}
|
||||
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-16 grid aspect-square w-32 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">
|
||||
@@ -126,53 +169,52 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
|
||||
</svg>
|
||||
)}
|
||||
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
|
||||
<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>
|
||||
<small className="block font-jua text-[12px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}</small>
|
||||
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
|
||||
</span>
|
||||
</div>
|
||||
<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>
|
||||
<Stat label="습도">{heroVal(feedLoad, hero?.humidity != null ? `${hero.humidity}%` : null, 'w-10')}</Stat>
|
||||
<Stat label="불쾌지수" tone={hero?.discomfort != null && hero.discomfort >= MUGGY ? 'warn' : 'normal'}>
|
||||
{heroVal(feedLoad, hero?.discomfort != null ? `${hero.discomfort} ${hero.discomfort_label ?? ''}`.trim() : null, 'w-10')}
|
||||
</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)]" />
|
||||
<div className="relative z-[3] text-center">
|
||||
{top1 ? (
|
||||
<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 type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="cursor-pointer font-jua text-[24px] leading-tight">
|
||||
{bubble}
|
||||
</button>
|
||||
) : (
|
||||
<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>
|
||||
<p className="m-0 font-jua text-[24px] leading-tight">{bubble ?? <Skel className="w-[160px]" />}</p>
|
||||
)}
|
||||
<p className="m-0 mt-0.5 text-[15px] font-bold opacity-80">{top1?.summary ?? (feedLoad === 'loading' ? <Skel className="w-[140px]" /> : null)}</p>
|
||||
{/* 상태 한 줄: 습도·불쾌지수·자외선·미세먼지 단계 이름. 조심할 것만 색 */}
|
||||
{status.length > 0 && (
|
||||
<p className="m-0 mt-1.5 flex flex-wrap justify-center gap-x-1.5 font-jua text-[14px]">
|
||||
{status.map((x, i) => (
|
||||
<Fragment key={x.label}>
|
||||
{i > 0 && <span className="opacity-30" aria-hidden="true">·</span>}
|
||||
<span className={cx('whitespace-nowrap', x.tone === 'warn' && 'b-warn')}>
|
||||
<span className={cx(x.tone !== 'warn' && 'opacity-75')}>{x.label}</span> <b className="font-normal">{x.value}</b>
|
||||
</span>
|
||||
</Fragment>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="b-strip relative z-[3] mt-2.5 grid grid-cols-4 gap-1 rounded-[18px] p-[3px]" role="tablist" aria-label="하루 흐름, 누르면 그 시간대 하늘로">
|
||||
{KINDS.map((k) => {
|
||||
const isNow = k === nowKind
|
||||
const s = slotOf(isNow ? 'now' : k)
|
||||
const on = k === kind
|
||||
return (
|
||||
<button key={k} type="button" role="tab" aria-selected={on} onClick={() => setPreview(isNow ? null : k)} className={cx('flex cursor-pointer flex-col items-center rounded-[14px] py-1.5', on && 'b-strip-on')}>
|
||||
<span className={cx('text-[13px] font-bold', on ? 'text-(--orange-deep)' : 'opacity-75')}>{isNow ? '지금' : PREVIEW[k].label}</span>
|
||||
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} className="my-0.5 h-[22px] w-[22px] object-contain" />
|
||||
<b className="font-jua text-[15px] font-normal">{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</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 = ['기우는 달', '하현달', '그믐달']
|
||||
|
||||
/**
|
||||
@@ -309,9 +351,11 @@ export function TodayPage() {
|
||||
const { region } = useRegion()
|
||||
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
||||
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
||||
const { preview } = useSky()
|
||||
const f = feed.data
|
||||
const posts = f?.posts ?? []
|
||||
const stories = f?.stories ?? []
|
||||
const stories = atSlot(f?.stories ?? [], preview)
|
||||
const sloted = preview != null && stories !== f?.stories
|
||||
const bands = f?.bands
|
||||
const nowAt = f?.hero?.now_at
|
||||
const load = loadOf(feed)
|
||||
@@ -323,14 +367,14 @@ export function TodayPage() {
|
||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [
|
||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
||||
[6, bands?.top5?.length ? <TopBand key="top5" items={bands.top5} sub={nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
||||
[6, bands?.top5?.length ? <TopBand key="top5" items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
||||
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
|
||||
]
|
||||
|
||||
return (
|
||||
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
|
||||
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
||||
<Hero hero={f?.hero} today={today.data} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
||||
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
|
||||
|
||||
@@ -292,7 +292,7 @@ export function WeekPage() {
|
||||
{r.estimated && ' · 예상'}
|
||||
</small>
|
||||
<span className="mt-[5px] block h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#9be7c4,#1f9d62)]" style={{ width: `${r.score}%` }} />
|
||||
<s className="b-keep-bg block h-full bg-[linear-gradient(90deg,#9be7c4,#1f9d62)]" style={{ width: `${r.score}%` }} />
|
||||
</span>
|
||||
</span>
|
||||
<em className="flex items-center gap-1 font-jua text-base not-italic">
|
||||
|
||||
@@ -129,7 +129,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* 처음 불러오는 동안 캐릭터가 통통 뛴다 */
|
||||
.b-hop {
|
||||
animation: b-hop 0.9s cubic-bezier(0.3, 0, 0.4, 1) infinite;
|
||||
transform-origin: 50% 100%;
|
||||
}
|
||||
@keyframes b-hop {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0) scale(1.06, 0.94);
|
||||
}
|
||||
45% {
|
||||
transform: translateY(-22px) scale(0.97, 1.03);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.b-hop,
|
||||
.b-fall,
|
||||
.b-heart-pop,
|
||||
.b-like-bit,
|
||||
@@ -170,39 +186,72 @@
|
||||
.b-stars i {
|
||||
background: #fff;
|
||||
}
|
||||
.b-stat {
|
||||
background: rgb(255 255 255 / 0.72);
|
||||
color: var(--ink);
|
||||
box-shadow: inset 0 -5px 0 rgb(217 229 244 / 0.9);
|
||||
/* 히어로 하루 흐름 칸: 한 판 위에 고른 칸만 흰 바탕 */
|
||||
.b-strip {
|
||||
background: rgb(255 255 255 / 0.42);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-stat,
|
||||
.b-hero[data-t='sunset'] .b-stat {
|
||||
background: rgb(255 255 255 / 0.18);
|
||||
color: #fff;
|
||||
box-shadow: inset 0 -5px 0 rgb(255 255 255 / 0.12);
|
||||
.b-hero[data-t='sunset'] .b-strip,
|
||||
.b-hero[data-t='night'] .b-strip {
|
||||
background: rgb(255 255 255 / 0.14);
|
||||
}
|
||||
.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 {
|
||||
.b-strip-on {
|
||||
background: #fff;
|
||||
color: var(--ink);
|
||||
box-shadow: 0 8px 16px rgb(40 48 74 / 0.1);
|
||||
color: #28304a; /* 밤엔 --ink 가 밝은 색이라 고정 */
|
||||
box-shadow: 0 4px 12px rgb(40 48 74 / 0.1);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-bubble {
|
||||
background: rgb(30 34 70 / 0.85);
|
||||
color: #fff;
|
||||
/* 상태 한 줄에서 조심할 것. 밤·노을 배경에선 밝은 주황 */
|
||||
.b-warn {
|
||||
color: var(--orange-deep);
|
||||
}
|
||||
.b-hero[data-t='sunset'] .b-warn,
|
||||
.b-hero[data-t='night'] .b-warn {
|
||||
color: #ffb38a;
|
||||
}
|
||||
/* 흐리거나 비·눈 오는 아침·낮은 하늘을 잿빛으로 */
|
||||
.b-hero[data-t='morning']:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']),
|
||||
.b-hero[data-t='day']:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']) {
|
||||
background: linear-gradient(180deg, #a9bbd0, #cbd7e4 55%, #eef2f7);
|
||||
}
|
||||
.b-hero:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']) .b-sun {
|
||||
filter: saturate(0.7) brightness(0.96);
|
||||
}
|
||||
.b-drop,
|
||||
.b-flake {
|
||||
position: absolute;
|
||||
top: -24px;
|
||||
animation: b-fallsky var(--dur) linear var(--dl) infinite;
|
||||
}
|
||||
.b-drop {
|
||||
width: 2px;
|
||||
height: 18px;
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(transparent, rgb(80 130 200 / 0.7));
|
||||
}
|
||||
.b-hero[data-t='sunset'] .b-drop,
|
||||
.b-hero[data-t='night'] .b-drop {
|
||||
background: linear-gradient(transparent, rgb(220 230 255 / 0.7));
|
||||
}
|
||||
.b-flake {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 4px rgb(120 150 200 / 0.5);
|
||||
}
|
||||
@keyframes b-fallsky {
|
||||
to {
|
||||
transform: translate(var(--drift, -8px), 440px);
|
||||
}
|
||||
}
|
||||
.b-flake {
|
||||
--drift: 18px;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.b-drop,
|
||||
.b-flake {
|
||||
animation: none;
|
||||
top: var(--top);
|
||||
}
|
||||
}
|
||||
.b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
|
||||
@@ -536,7 +585,7 @@
|
||||
.b-app[data-t='night'] [class*='bg-white/'] {
|
||||
background-color: rgb(34 42 92 / 0.85);
|
||||
}
|
||||
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']) {
|
||||
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']):not(.b-keep-bg) {
|
||||
background: var(--chip);
|
||||
}
|
||||
.b-app[data-t='night'] [class*='border-[#dfe5ee]'] {
|
||||
@@ -595,6 +644,10 @@
|
||||
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
|
||||
}
|
||||
|
||||
.b-app[data-t='night'] img[data-dark] {
|
||||
filter: drop-shadow(0 0 1px rgb(255 255 255 / 0.9)) drop-shadow(0 0 6px rgb(255 255 255 / 0.3));
|
||||
}
|
||||
|
||||
/* 밤엔 메인 탭 동그라미 테두리를 막대 색에 맞춘다 */
|
||||
.b-app[data-t='night'] .b-tab-main > span {
|
||||
--tw-ring-color: rgb(18 24 60 / 0.9);
|
||||
|
||||
@@ -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', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay'])
|
||||
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', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
@@ -43,6 +43,10 @@ export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f':
|
||||
|
||||
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
|
||||
|
||||
// 달(1~12) → 계절 이름과 아이콘. 봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2 (서버 각 제철 기준과 같다)
|
||||
const SEASONS: [string, string][] = [['겨울', 'snow'], ['봄', 'garden'], ['여름', 'sun'], ['가을', 'maple']]
|
||||
export const seasonOf = (month: number) => SEASONS[Math.floor((month % 12) / 3)]
|
||||
|
||||
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
|
||||
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router'
|
||||
import regionPages from '../../seo/region.json'
|
||||
import { nearestRegion } from '../api/client/sdk.gen'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||
import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
|
||||
type RegionPage = (typeof regionPages)[number]
|
||||
|
||||
/** /today/gyeonggi/seongnam, /today/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
|
||||
function pageOf(pathname: string): RegionPage | undefined {
|
||||
const path = pathname.match(/^\/today\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
|
||||
return path ? regionPages.find((p) => p.path === path) : undefined
|
||||
}
|
||||
|
||||
/** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */
|
||||
function regionIn(page: RegionPage, r?: RegionData | null): RegionData {
|
||||
return page.regions.find((g) => g.code === r?.code) ?? page.regions.find((g) => g.code === page.main)!
|
||||
}
|
||||
|
||||
function readStored(): RegionData | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY)
|
||||
@@ -26,33 +41,45 @@ function writeStored(r: RegionData) {
|
||||
}
|
||||
|
||||
export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const { pathname } = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const page = pageOf(pathname)
|
||||
const pageRef = useRef(page)
|
||||
useEffect(() => {
|
||||
pageRef.current = page
|
||||
}, [page])
|
||||
const [stored] = useState(readStored)
|
||||
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION)
|
||||
const [landing] = useState(page)
|
||||
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
|
||||
// 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로
|
||||
const region = page && !page.regions.some((g) => g.code === chosen.code) ? regionIn(page, stored) : chosen
|
||||
const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!stored && canLocate ? 'locating' : 'idle')
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && !stored && canLocate ? 'locating' : 'idle')
|
||||
|
||||
// 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
}, [])
|
||||
const next = ownPage(r.code)
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`)
|
||||
}, [navigate])
|
||||
|
||||
const findNearest = useCallback((onFound?: () => void) => {
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
|
||||
const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false) => {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||
.then(({ data: res }) => {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setRegion(res.region)
|
||||
setLocateStatus('idle')
|
||||
track('region_change', { region_name: res.region.name, method: 'location' })
|
||||
onFound?.()
|
||||
apply(res.region)
|
||||
})
|
||||
.catch(() => setLocateStatus('error'))
|
||||
.catch(() => !quiet && setLocateStatus('error'))
|
||||
},
|
||||
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
(err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
{ timeout: 10000, maximumAge: 600000 },
|
||||
)
|
||||
}, [setRegion])
|
||||
}, [])
|
||||
|
||||
const locate = useCallback((onFound?: () => void) => {
|
||||
if (!canLocate) {
|
||||
@@ -60,13 +87,36 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest(onFound)
|
||||
}, [canLocate, findNearest])
|
||||
findNearest((r) => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
onFound?.()
|
||||
})
|
||||
}, [canLocate, findNearest, setRegion])
|
||||
|
||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||
useEffect(() => {
|
||||
if (!stored && canLocate) findNearest()
|
||||
}, [stored, canLocate, findNearest])
|
||||
if (!canLocate) return
|
||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||
if (!landing) {
|
||||
if (!stored) {
|
||||
findNearest((r) => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
// 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로
|
||||
if (landing.regions.length < 2) return
|
||||
navigator.permissions?.query({ name: 'geolocation' })
|
||||
.then((s) => {
|
||||
if (s.state !== 'granted') return
|
||||
findNearest((r) => {
|
||||
if (pageRef.current === landing && landing.regions.some((g) => g.code === r.code)) setRegionState(r)
|
||||
}, true)
|
||||
})
|
||||
.catch((e) => console.warn('위치 권한 상태를 읽지 못함', e))
|
||||
}, [canLocate, landing, stored, findNearest, setRegion])
|
||||
|
||||
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
||||
return <RegionContext value={api}>{children}</RegionContext>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createContext, use } from 'react'
|
||||
import regionPages from '../../seo/region.json'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
|
||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||
@@ -7,6 +8,9 @@ export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void
|
||||
|
||||
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
||||
|
||||
/** 구 하나만 보여 주는 지역 페이지: 일반 시군구, 또는 구로 나뉜 시의 구 페이지 */
|
||||
export const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code)
|
||||
|
||||
export const RegionContext = createContext<RegionApi | null>(null)
|
||||
|
||||
export function useRegion() {
|
||||
|
||||
@@ -6,10 +6,13 @@ import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
|
||||
|
||||
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
||||
|
||||
// 거의 검은 아이콘. 밤 화면에선 테두리 빛을 둘러 보이게 한다
|
||||
const DARK_ICONS = new Set(['walk', 'dog'])
|
||||
|
||||
export function Ic({ name, className, alt = '', style }: IcProps) {
|
||||
const src = iconSrc(name)
|
||||
if (!src) return <span aria-hidden className={cx('block', className)} style={style} />
|
||||
return <img src={src} alt={alt} className={cx('block', className)} style={style} decoding="async" />
|
||||
return <img src={src} alt={alt} className={cx('block', className)} style={style} decoding="async" data-dark={DARK_ICONS.has(name) || undefined} />
|
||||
}
|
||||
|
||||
/** 사진 출처 표기 (공공누리 조건). 사진 위에서도 읽히게 반투명 배경. 위치는 className 으로 */
|
||||
@@ -206,13 +209,20 @@ export function MapLink({ place, children, className }: { place: string; childre
|
||||
)
|
||||
}
|
||||
|
||||
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null }[]; dark?: boolean }) {
|
||||
/** 자외선 단계(1 낮음 ~ 5 위험) 칩 색 */
|
||||
const LEVEL_CHIP = ['bg-[#1f9d62] text-white', 'bg-[#ffc21a] text-[#3a2a00]', 'bg-[#f0700a] text-white', 'bg-[#e03131] text-white', 'bg-[#8e3bc4] text-white']
|
||||
|
||||
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null; level?: number | null }[]; dark?: boolean }) {
|
||||
return (
|
||||
<div className="mt-auto flex flex-col">
|
||||
{rows.map((r) => (
|
||||
<div key={r.label} className={cx('flex justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
|
||||
<div key={r.label} className={cx('flex items-center justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
|
||||
<span>{r.label}</span>
|
||||
<b className="text-right font-jua text-[17px] font-normal">{r.place ? <MapLink place={r.place}>{r.value}</MapLink> : r.value}</b>
|
||||
{r.level ? (
|
||||
<b className={cx('rounded-full px-2.5 py-[3px] font-jua text-[15px] font-normal', LEVEL_CHIP[r.level - 1])}>{r.value}</b>
|
||||
) : (
|
||||
<b className="text-right font-jua text-[17px] font-normal">{r.place ? <MapLink place={r.place}>{r.value}</MapLink> : r.value}</b>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
|
||||
@@ -1,8 +1,109 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig } from 'vite'
|
||||
import { defineConfig, type Plugin } from 'vite'
|
||||
|
||||
type Gak = { name: string; description: string }
|
||||
type RegionPage = { path: string; name: string; main: string; regions: { code: string; name: string }[] }
|
||||
|
||||
const gaks: Gak[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/gak.json'), 'utf8'))
|
||||
const gakList = `<ul>${gaks.map((g) => `<li><b>${g.name}</b>: ${g.description}</li>`).join('')}</ul>`
|
||||
const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8'))
|
||||
|
||||
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
|
||||
const PAGES: { path: string; title: string; description: string; body: string; code?: string; keywords?: string }[] = [
|
||||
{
|
||||
path: 'gak',
|
||||
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
|
||||
description: `세차각, 빨래각, 러닝각, 피크닉각처럼 오늘 하고 싶은 일 ${gaks.length}가지가 우리 동네 날씨에 맞는지 아침·낮·저녁·밤 점수로 알려 드려요.`,
|
||||
body: `<h1>날씨각 · 오늘의 각</h1><p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 기상청 예보와 미세먼지로 아침, 낮, 저녁, 밤마다 따로 계산해요. 비 오는 날엔 우산각·파전각·감성노래각이, 맑은 날엔 세차각·빨래각·피크닉각이 올라가요.</p>${gakList}`,
|
||||
},
|
||||
{
|
||||
path: 'sky',
|
||||
title: '오늘 노을 · 노을 시간과 노을 명소 | 날씨각',
|
||||
description: '오늘 우리 동네 노을이 얼마나 붉게 물들지, 몇 시에 가장 붉은지, 가까운 노을 명소는 어디인지 날씨각에서 확인하세요. 해돋이와 달도 함께 알려 드려요.',
|
||||
body: '<h1>날씨각 · 오늘 노을</h1><p>구름의 높이와 양, 공기의 맑기로 오늘 노을이 얼마나 붉게 물들지 점수로 알려 드려요. 보통 해 진 뒤 10~20분이 가장 붉어요.</p><p>가까운 노을 명소와 해 지는 방향, 사흘 치 노을 예보, 해돋이와 오늘 밤 달 모양도 볼 수 있어요.</p>',
|
||||
},
|
||||
{
|
||||
path: 'week',
|
||||
title: '이번 주말 날씨 · 나들이와 축제 | 날씨각',
|
||||
description: '이번 주말 날씨와 나들이하기 좋은 곳, 가까운 축제·전시·공연·팝업을 날씨각에서 한 번에 확인하세요.',
|
||||
body: '<h1>날씨각 · 주말과 행사</h1><p>토요일과 일요일 날씨로 나들이하기 좋은 정도를 점수로 알려 드려요. 비 소식이 있으면 실내에서 즐길 거리를 먼저 보여 드려요.</p><p>우리 동네와 가까운 지역의 축제, 전시, 공연, 팝업 스토어를 모아 드려요.</p>',
|
||||
},
|
||||
{
|
||||
path: 'season',
|
||||
title: '계절 소식과 날씨 상식 | 날씨각',
|
||||
description: '지금 계절에 볼 만한 단풍·꽃·제철 소식과 알아 두면 좋은 날씨 상식을 날씨각에서 읽어 보세요.',
|
||||
body: '<h1>날씨각 · 계절과 상식</h1><p>이번 주 절기와 제철 풍경, 지금 계절에 하기 좋은 일을 알려 드려요.</p><p>불쾌지수, 체감온도, 미세먼지 등급처럼 알아 두면 좋은 날씨 상식도 읽을 수 있어요.</p>',
|
||||
},
|
||||
]
|
||||
|
||||
/** 제목 앞자리: 검색어처럼 시군구 이름부터 (경기 성남시 → 성남시) */
|
||||
const headName = (name: string) => name.split(' ').at(-1)!
|
||||
/** 검색어로 많이 치는 꼴: 성남시 → 성남. 중구처럼 두 글자는 그대로 */
|
||||
const bareName = (name: string) => (name.length > 2 ? name.slice(0, -1) : name)
|
||||
|
||||
/** 지역마다 한 장: /today/gyeonggi/seongnam, 구로 나뉜 시의 구는 /today/gyeonggi/seongnam/bundang. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */
|
||||
for (const r of regionPages) {
|
||||
const sido = r.path.split('/')[0]
|
||||
const city = r.path.split('/').slice(0, 2).join('/')
|
||||
const isGu = r.path !== city
|
||||
const gus = regionPages.filter((o) => o.path.startsWith(`${r.path}/`))
|
||||
// 시도의 다른 시군구 + 같은 시의 다른 구
|
||||
const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`) && (o.path.split('/').length === 2 || (isGu && o.path.startsWith(`${city}/`))))
|
||||
const parts = gus.length ? `<p>${r.name}는 ${gus.map((g) => `<a href="/today/${g.path}">${headName(g.name)}</a>`).join(', ')}별로 따로 계산해요.</p>` : ''
|
||||
const head = headName(r.name)
|
||||
const bare = bareName(head)
|
||||
const guNames = r.regions.length > 1 ? r.regions.map((g) => g.name.split(' ').at(-1)!) : []
|
||||
const keywords = [...new Set([`${bare} 날씨`, `${head} 날씨`, `${bare} 오늘 날씨`, `${r.name} 날씨`, ...guNames.flatMap((g) => [`${g} 날씨`, `${bareName(g)} 날씨`]), '날씨각'])].join(', ')
|
||||
PAGES.push({
|
||||
path: `today/${r.path}`,
|
||||
code: r.main,
|
||||
keywords,
|
||||
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[isGu ? 1 : 0]}` : ''} | 날씨각`,
|
||||
description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`,
|
||||
body: `<h1>${r.name} 오늘 날씨, 뭐 할까?</h1><p>${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
|
||||
})
|
||||
}
|
||||
|
||||
const attr = (s: string) => s.replace(/&/g, '&').replace(/"/g, '"')
|
||||
|
||||
function seoPages(): Plugin {
|
||||
let outDir = 'dist'
|
||||
return {
|
||||
name: 'seo-pages',
|
||||
apply: 'build',
|
||||
configResolved(c) {
|
||||
outDir = resolve(c.root, c.build.outDir)
|
||||
},
|
||||
closeBundle() {
|
||||
const base = readFileSync(resolve(outDir, 'index.html'), 'utf8')
|
||||
const site = process.env.VITE_SITE_URL || 'https://weather.o2o.kr'
|
||||
for (const p of PAGES) {
|
||||
const url = `${site}/${p.path}`
|
||||
const html = base
|
||||
.replace(/<title>[^<]*<\/title>/, `<title>${p.title}</title>`)
|
||||
.replace(/(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"/g, `$1${attr(p.description)}"`)
|
||||
.replace(/(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"/g, `$1${attr(p.title)}"`)
|
||||
.replace(/(<meta name="keywords" content=")[^"]*"/, (m, head) => (p.keywords ? `${head}${attr(p.keywords)}"` : m))
|
||||
.replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`)
|
||||
.replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`)
|
||||
.replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`)
|
||||
// 서버가 오늘 날씨를 채울 때 이 페이지의 구를 알아보는 표시
|
||||
.replace('</head>', p.code ? `<meta name="region-code" content="${p.code}" />\n </head>` : '</head>')
|
||||
const file = resolve(outDir, `${p.path}.html`)
|
||||
mkdirSync(dirname(file), { recursive: true })
|
||||
writeFileSync(file, html)
|
||||
}
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const urls = ['', ...PAGES.map((p) => p.path)].map((path) => ` <url><loc>${site}/${path}</loc><lastmod>${today}</lastmod></url>`)
|
||||
writeFileSync(resolve(outDir, 'sitemap.xml'), `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('\n')}\n</urlset>\n`)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
plugins: [react(), tailwindcss(), seoPages()],
|
||||
})
|
||||
@@ -1,3 +1,15 @@
|
||||
import com.google.android.wearable.watchface.validator.client.DwfValidatorFactory
|
||||
|
||||
// 스킨 APK 검증·토큰 발급기 (Watch Face Push). 의존성 하나가 jitpack 에만 있다
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
maven("https://jitpack.io") { content { includeGroup("com.github.xgouchet") } }
|
||||
}
|
||||
dependencies { classpath("com.google.android.wearable.watchface.validator:validator-push:1.0.0-alpha09") }
|
||||
}
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
@@ -9,10 +21,13 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "kr.o2o.nalssigak"
|
||||
minSdk = 30
|
||||
targetSdk = 34
|
||||
// Wear OS 6+ 만. 앱 설치 때 스킨을 같이 깔고 시계 화면으로 바꾸는 Watch Face Push 가 API 36 부터다
|
||||
minSdk = 36
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "0.1"
|
||||
// 앱에 실은 스킨 버전. 워치에 깔린 스킨이 이보다 낮으면 앱이 바꿔 끼운다 (MainActivity.useSkin)
|
||||
buildConfigField("int", "SKIN_VERSION", providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get())
|
||||
}
|
||||
buildTypes {
|
||||
// 에뮬레이터에서 본 맥의 로컬 백엔드 (compose 포트 9810)
|
||||
@@ -38,4 +53,36 @@ dependencies {
|
||||
implementation("androidx.wear.tiles:tiles:1.6.2")
|
||||
implementation("androidx.concurrent:concurrent-futures:1.3.0")
|
||||
implementation("androidx.wear.watchface:watchface-complications-data-source-ktx:1.3.0")
|
||||
implementation("androidx.wear.watchfacepush:watchfacepush:1.0.0")
|
||||
}
|
||||
|
||||
// 앱을 깔면 스킨(:watchface)도 같이 깔리게 한다 (Wear OS 6+ 기본 워치 페이스).
|
||||
// 같은 빌드 타입의 스킨 APK 를 assets/default_watchface.apk 로 싣고, 검증 토큰을 문자열 리소스로 만든다
|
||||
androidComponents.onVariants { variant ->
|
||||
val name = variant.name.replaceFirstChar(Char::titlecase)
|
||||
val skinApks = project(":watchface").layout.buildDirectory.dir("outputs/apk/${variant.name}")
|
||||
val assetsDir = layout.buildDirectory.dir("generated/skinAssets/${variant.name}")
|
||||
val resDir = layout.buildDirectory.dir("generated/skinToken/${variant.name}")
|
||||
val appId = variant.applicationId
|
||||
variant.sources.assets?.addStaticSourceDirectory(assetsDir.get().asFile.path)
|
||||
variant.sources.res?.addStaticSourceDirectory(resDir.get().asFile.path)
|
||||
val bundle = tasks.register("bundleSkin$name") {
|
||||
dependsOn(":watchface:assemble$name")
|
||||
inputs.dir(skinApks)
|
||||
outputs.dirs(assetsDir, resDir)
|
||||
doLast {
|
||||
val apk = skinApks.get().asFile.listFiles { f -> f.extension == "apk" }!!.single()
|
||||
// 서명 없는 스킨은 워치가 설치를 거부한다. 업로드 키 설정은 루트 build.gradle.kts 참고
|
||||
if (apk.name.endsWith("-unsigned.apk")) throw GradleException("스킨 APK 가 서명되지 않았습니다. ~/.gradle/gradle.properties 에 NALSSIGAK_STORE_* 를 넣고 다시 빌드하세요")
|
||||
val result = DwfValidatorFactory.create().validate(apk, appId.get())
|
||||
if (result.failures().isNotEmpty()) throw GradleException("스킨 검증 실패: ${result.failures()}")
|
||||
apk.copyTo(assetsDir.get().file("default_watchface.apk").asFile, overwrite = true)
|
||||
resDir.get().file("values/skin_token.xml").asFile.apply { parentFile.mkdirs() }
|
||||
.writeText(
|
||||
"""<resources xmlns:tools="http://schemas.android.com/tools">""" +
|
||||
"""<string name="default_wf_token" translatable="false" tools:ignore="Typos">${result.validationToken()}</string></resources>""" + "\n"
|
||||
)
|
||||
}
|
||||
}
|
||||
afterEvaluate { tasks.named("pre${name}Build") { dependsOn(bundle) } }
|
||||
}
|
||||
@@ -4,6 +4,9 @@
|
||||
<uses-feature android:name="android.hardware.type.watch" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<!-- 앱과 같이 깔리는 날씨각 스킨을 시계 화면으로 바꾸는 권한 (Watch Face Push) -->
|
||||
<uses-permission android:name="com.google.wear.permission.PUSH_WATCH_FACES" />
|
||||
<uses-permission android:name="com.google.wear.permission.SET_PUSHED_WATCH_FACE_AS_ACTIVE" />
|
||||
|
||||
<application
|
||||
android:icon="@drawable/ic_gak"
|
||||
@@ -13,6 +16,11 @@
|
||||
<!-- 폰 앱 없이 워치에서 단독으로 동작 -->
|
||||
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
|
||||
|
||||
<!-- 앱 설치 때 assets/default_watchface.apk(스킨)도 같이 설치된다. 토큰은 빌드가 만든다 (build.gradle.kts) -->
|
||||
<meta-data
|
||||
android:name="com.google.android.wearable.marketplace.DEFAULT_WATCHFACE_VALIDATION_TOKEN"
|
||||
android:value="@string/default_wf_token" />
|
||||
|
||||
<activity android:name=".MainActivity" android:exported="true" android:taskAffinity="">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -126,7 +134,7 @@
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
<!-- 워치 스킨 숨은 칸용: 비·눈 여부 -->
|
||||
<!-- 워치 스킨 숨은 칸용: 날씨(비·눈·천둥)·기온·가운데 1위 -->
|
||||
<service
|
||||
android:name=".RainComplicationService"
|
||||
android:exported="true"
|
||||
@@ -136,7 +144,7 @@
|
||||
<intent-filter>
|
||||
<action android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="SHORT_TEXT" />
|
||||
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="RANGED_VALUE" />
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package kr.o2o.nalssigak
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Bundle
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -16,29 +18,85 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.wear.compose.foundation.pager.VerticalPager
|
||||
import androidx.wear.compose.foundation.pager.rememberPagerState
|
||||
import androidx.wear.compose.material3.MaterialTheme
|
||||
import androidx.wear.compose.material3.VerticalPageIndicator
|
||||
import androidx.wear.watchfacepush.WatchFacePushManager
|
||||
import androidx.wear.watchfacepush.WatchFacePushManagerFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
/** 컴플리케이션 탭이 실어 보내는 각 코드 */
|
||||
const val EXTRA_GAK = "gak"
|
||||
|
||||
/** 앱과 같이 깔린 스킨을 시계 화면으로 바꾸는 권한. 사용자가 한 번 거절하면 다시 묻지 못한다 */
|
||||
private const val SET_SKIN = "com.google.wear.permission.SET_PUSHED_WATCH_FACE_AS_ACTIVE"
|
||||
private const val TAG = "MainActivity"
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private var summary by mutableStateOf<Summary?>(null)
|
||||
private var loading by mutableStateOf(true)
|
||||
|
||||
private val askLocation = registerForActivityResult(ActivityResultContracts.RequestPermission()) { load() }
|
||||
private val askPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
load()
|
||||
useSkin()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val opened = intent.getStringExtra(EXTRA_GAK)
|
||||
setContent { MaterialTheme { App(summary, loading, opened) { load(force = true) } } }
|
||||
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) load()
|
||||
else askLocation.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
// 위치와 스킨 적용을 한 번에 묻는다
|
||||
val missing = listOf(Manifest.permission.ACCESS_COARSE_LOCATION, SET_SKIN).filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (missing.isEmpty()) {
|
||||
load()
|
||||
useSkin()
|
||||
} else askPermissions.launch(missing.toTypedArray())
|
||||
}
|
||||
|
||||
/**
|
||||
* 앱 설치 때 같이 깔린 날씨각 스킨을 챙긴다.
|
||||
* 앱 업데이트로 새 스킨이 실려 왔으면 바꿔 끼우고(기본 스킨은 처음 설치 때만 깔린다), 허락받았으면 시계 화면으로 바꾼다(시스템이 앱마다 한 번만 허락한다).
|
||||
*/
|
||||
private fun useSkin() {
|
||||
lifecycleScope.launch {
|
||||
val push = WatchFacePushManagerFactory.createWatchFacePushManager(this@MainActivity)
|
||||
try {
|
||||
// 기본 스킨 설치가 아직 안 끝났으면 다음 실행 때 다시 본다
|
||||
val skin = push.listWatchFaces().installedWatchFaceDetails.firstOrNull() ?: return@launch
|
||||
if (skin.versionCode < BuildConfig.SKIN_VERSION) updateSkin(push, skin.slotId)
|
||||
if (checkSelfPermission(SET_SKIN) == PackageManager.PERMISSION_GRANTED && !push.isWatchFaceActive(skin.packageName)) {
|
||||
push.setWatchFaceAsActive(skin.slotId)
|
||||
}
|
||||
} catch (e: WatchFacePushManager.ListWatchFacesException) {
|
||||
Log.w(TAG, "스킨 목록을 못 읽음", e)
|
||||
} catch (e: WatchFacePushManager.UpdateWatchFaceException) {
|
||||
Log.w(TAG, "스킨을 새 버전으로 못 바꿈", e)
|
||||
} catch (e: WatchFacePushManager.IsWatchFaceActiveException) {
|
||||
Log.w(TAG, "스킨 사용 여부를 못 읽음", e)
|
||||
} catch (e: WatchFacePushManager.SetWatchFaceAsActiveException) {
|
||||
// 이미 한 번 바꾼 뒤 사용자가 다른 화면으로 옮긴 경우. 다시 바꾸지 않는다
|
||||
Log.i(TAG, "스킨을 시계 화면으로 바꾸지 않음", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 앱에 실은 스킨(assets/default_watchface.apk)으로 바꿔 끼운다. 검증 토큰은 빌드가 만든 것 (build.gradle.kts) */
|
||||
private suspend fun updateSkin(push: WatchFacePushManager, slotId: String) {
|
||||
val apk = File(cacheDir, "skin.apk")
|
||||
try {
|
||||
withContext(Dispatchers.IO) { assets.open("default_watchface.apk").use { input -> apk.outputStream().use { input.copyTo(it) } } }
|
||||
ParcelFileDescriptor.open(apk, ParcelFileDescriptor.MODE_READ_ONLY).use { push.updateWatchFace(slotId, it, getString(R.string.default_wf_token)) }
|
||||
} finally {
|
||||
apk.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun load(force: Boolean = false) {
|
||||
@@ -50,7 +108,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class Page { DETAIL, SKY, TOP, PICKS, EVENTS, SUNSET, HOURS }
|
||||
private enum class Page { DETAIL, HOURS, EVENTS, TOP, PICKS, SUNSET }
|
||||
|
||||
@Composable
|
||||
private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> Unit) {
|
||||
@@ -65,32 +123,30 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U
|
||||
StatePage(loading, onRetry)
|
||||
return
|
||||
}
|
||||
// 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 하늘 장부터
|
||||
// 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 오늘 남은 시간 → 주변 축제 → 각 순서
|
||||
val detail = opened?.let { c -> (s.top + s.picks).firstOrNull { it.code == c } }
|
||||
val pages = buildList {
|
||||
if (detail != null) add(Page.DETAIL)
|
||||
add(Page.SKY)
|
||||
if (s.slots.isNotEmpty()) add(Page.HOURS)
|
||||
if (s.events.isNotEmpty()) add(Page.EVENTS)
|
||||
if (s.top.isNotEmpty()) add(Page.TOP)
|
||||
if (s.picks.isNotEmpty()) add(Page.PICKS)
|
||||
if (s.events.isNotEmpty()) add(Page.EVENTS)
|
||||
if (s.sunset != null) add(Page.SUNSET)
|
||||
if (s.slots.isNotEmpty()) add(Page.HOURS)
|
||||
}
|
||||
val state = rememberPagerState { pages.size }
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
VerticalPager(state = state, modifier = Modifier.fillMaxSize()) { i ->
|
||||
when (pages[i]) {
|
||||
Page.DETAIL -> DetailPage(detail!!, now)
|
||||
Page.SKY -> SkyPage(s, now)
|
||||
Page.EVENTS -> EventsPage(s.events, now)
|
||||
Page.TOP -> GakListPage("오늘의 각", s.top.take(3), bgButter, medals = true, now)
|
||||
Page.PICKS -> GakListPage("내 각", s.picks, bgMint, medals = false, now)
|
||||
Page.EVENTS -> EventsPage(s.events, now)
|
||||
Page.SUNSET -> SunsetPage(s.sunset!!, now)
|
||||
Page.HOURS -> HoursPage(s, now)
|
||||
}
|
||||
}
|
||||
val page = pages[state.currentPage]
|
||||
val dot = if (page == Page.SUNSET || (page == Page.SKY && isDark(s.mode))) Color.White else Tok.ink
|
||||
val dot = if (page == Page.SUNSET) Color.White else Tok.ink
|
||||
VerticalPageIndicator(pagerState = state, selectedColor = dot, unselectedColor = dot.copy(alpha = 0.35f), backgroundColor = Color.Transparent)
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,45 @@
|
||||
package kr.o2o.nalssigak
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import androidx.wear.watchface.complications.data.ComplicationData
|
||||
import androidx.wear.watchface.complications.data.ComplicationType
|
||||
import androidx.wear.watchface.complications.data.PlainComplicationText
|
||||
import androidx.wear.watchface.complications.data.ShortTextComplicationData
|
||||
import androidx.wear.watchface.complications.data.RangedValueComplicationData
|
||||
import androidx.wear.watchface.complications.datasource.ComplicationRequest
|
||||
import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"눈 와요")을 보고 빗줄기·눈송이도 그린다. */
|
||||
/**
|
||||
* 워치 스킨 날씨 칸 + 가운데 1위. 스킨 칸이 8개까지라 한 칸에 몰아 준다.
|
||||
* 값 = 날씨 코드(0 맑음·1 비·2 천둥·3 눈) × 1000 + 1위 점수, 글자 = 지금 기온, 제목 = 1위 이름(없으면 빈 글자).
|
||||
*/
|
||||
class RainComplicationService : SuspendingComplicationDataSourceService() {
|
||||
|
||||
override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? {
|
||||
val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@RainComplicationService) } ?: return null
|
||||
return data(s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", s.rainLabel)
|
||||
val code = when (s.rainLabel) {
|
||||
"비 와요", "곧 비" -> 1
|
||||
"천둥 쳐요" -> 2
|
||||
"눈 와요" -> 3
|
||||
else -> 0
|
||||
}
|
||||
val top = s.top.firstOrNull()
|
||||
return data(code, top?.score ?: 0, s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", top?.name ?: "")
|
||||
}
|
||||
|
||||
override fun getPreviewData(type: ComplicationType): ComplicationData = data("20°", "비 없음")
|
||||
override fun getPreviewData(type: ComplicationType): ComplicationData = data(0, 88, "20°", "산책각")
|
||||
|
||||
private fun data(temp: String, rain: String) = ShortTextComplicationData.Builder(
|
||||
PlainComplicationText.Builder(temp).build(),
|
||||
PlainComplicationText.Builder("$temp $rain").build(),
|
||||
).setTitle(PlainComplicationText.Builder(rain).build()).build()
|
||||
private fun data(code: Int, score: Int, temp: String, name: String): ComplicationData {
|
||||
// 가운데 구슬을 누르면 앱 첫 장
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return RangedValueComplicationData.Builder(code * 1000f + score, 0f, 3100f, PlainComplicationText.Builder("$name $score, $temp").build())
|
||||
.setText(PlainComplicationText.Builder(temp).build())
|
||||
.setTitle(PlainComplicationText.Builder(name).build())
|
||||
.setTapAction(open)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
@@ -56,17 +56,6 @@ import androidx.wear.compose.material3.Text
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import kotlin.math.roundToInt
|
||||
import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import java.time.format.TextStyle as DateTextStyle
|
||||
import java.util.Locale
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
// 시안 크기는 큰 원형(227dp) 기준. 작은 원형(192dp)에서도 넘치지 않게 비율과 여백으로 잡는다.
|
||||
|
||||
@@ -102,153 +91,6 @@ fun Clock(now: Instant, color: Color) {
|
||||
T(hhmm(now), 15.sp, FontFamily.Default, color.copy(alpha = 0.85f), Modifier.fillMaxWidth().padding(top = 6.dp), weight = FontWeight.Bold)
|
||||
}
|
||||
|
||||
// ───────────── 하늘 (앱 첫 장: 스킨은 초당 10장 안팎이라, 빠르게 흐르는 하늘은 여기서 60장으로) ─────────────
|
||||
|
||||
private val STARS = listOf(0.22f to 0.20f, 0.70f to 0.14f, 0.84f to 0.40f, 0.14f to 0.52f, 0.48f to 0.10f, 0.30f to 0.78f, 0.76f to 0.70f)
|
||||
|
||||
@Composable
|
||||
fun SkyPage(s: Summary, now: Instant) {
|
||||
val precip = s.precip
|
||||
val dark = isDark(s.mode)
|
||||
val night = s.mode == "night"
|
||||
val fg = if (dark) Color.White else Tok.ink
|
||||
val top = s.top.firstOrNull()
|
||||
BoxWithConstraints(Modifier.fillMaxSize().background(if (precip != null) precipBrush(precip, s.mode) else skyBrush(s.mode))) {
|
||||
val w = maxWidth
|
||||
if (night && precip == null) Canvas(Modifier.fillMaxSize()) {
|
||||
STARS.forEach { (x, y) -> drawCircle(Color.White, 1.4.dp.toPx(), Offset(size.width * x, size.height * y)) }
|
||||
}
|
||||
val cloudColor = when { precip == "rain" -> Color(0xFFDCE2EB); night -> Color(0xFFC9CDF0); else -> Color.White }
|
||||
SKY_CLOUDS.forEach { Cloud(cloudColor, it, w) }
|
||||
precip?.let { Precip(it, Modifier.fillMaxSize()) }
|
||||
Clock(now, fg)
|
||||
val day = now.atZone(KST).dayOfWeek.getDisplayName(DateTextStyle.FULL, Locale.KOREAN)
|
||||
T("$day · ${s.regionName.substringAfterLast(' ')}", 12.sp, color = fg, modifier = Modifier.fillMaxWidth().padding(top = 32.dp))
|
||||
if (!night) SunRays(Modifier.align(Alignment.Center).offset(y = (-6).dp).size(w * 0.62f))
|
||||
Orb(night, Modifier.align(Alignment.Center).offset(y = (-6).dp).size(w * 0.44f)) {
|
||||
T(top?.score?.toString() ?: "-", 38.sp, Tok.bagel, if (night) Color(0xFF2B2A5C) else Color.White)
|
||||
T(top?.name ?: "날씨각", 12.sp, color = if (night) Color(0xFF2B2A5C) else Color.White)
|
||||
}
|
||||
Row(Modifier.align(Alignment.BottomCenter).padding(bottom = w * 0.1f), horizontalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Stat("thermo", s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", dark)
|
||||
Stat("umbrella", s.rainLabel, dark)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 구슬 둘레의 끝이 둥근 햇살 12개. 1분에 한 바퀴 천천히 돈다 */
|
||||
@Composable
|
||||
private fun SunRays(modifier: Modifier) {
|
||||
val t = rememberInfiniteTransition(label = "rays")
|
||||
val turn by t.animateFloat(0f, 360f, infiniteRepeatable(tween(60_000, easing = LinearEasing)), label = "turn")
|
||||
Canvas(modifier.graphicsLayer { rotationZ = turn }) {
|
||||
val c = Offset(size.width / 2, size.height / 2)
|
||||
val r1 = size.width * 0.4f
|
||||
val r2 = size.width * 0.462f
|
||||
repeat(12) { i ->
|
||||
val a = Math.toRadians(i * 30.0)
|
||||
val dir = Offset(cos(a).toFloat(), sin(a).toFloat())
|
||||
drawLine(Color(0xFFFFB347), c + dir * r1, c + dir * r2, size.width * 0.044f, StrokeCap.Round)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 말랑 3D 해 구슬 (웹 .b-sun). 밤에는 달빛 보라 */
|
||||
@Composable
|
||||
private fun Orb(night: Boolean, modifier: Modifier, content: @Composable () -> Unit) {
|
||||
val stops = if (night) arrayOf(0f to Color.White, 0.35f to Color(0xFFE7E3FF), 0.72f to Color(0xFFB9B0F2), 1f to Color(0xFF8F86D9))
|
||||
else arrayOf(0f to Color(0xFFFFF5CF), 0.3f to Color(0xFFFFC86E), 0.68f to Color(0xFFFF8E4E), 1f to Color(0xFFEE6436))
|
||||
val glow = if (night) Color(0xFFBEB4FF) else Color(0xFFF06A3A)
|
||||
Box(
|
||||
modifier
|
||||
.shadow(18.dp, CircleShape, ambientColor = glow, spotColor = glow)
|
||||
.drawBehind {
|
||||
val c = Offset(size.width * 0.34f, size.height * 0.30f)
|
||||
drawCircle(Brush.radialGradient(*stops, center = c, radius = size.width * 0.96f))
|
||||
// 오른쪽 아래 그늘, 왼쪽 위 빛 (웹 inset 그림자 두 개)
|
||||
drawCircle(Brush.linearGradient(listOf(Color.Transparent, Color(if (night) 0x4D3C328C else 0x57AA3214)), Offset(size.width * 0.45f, size.height * 0.45f), Offset(size.width, size.height)))
|
||||
drawCircle(Brush.radialGradient(listOf(Color.White.copy(alpha = 0.45f), Color.Transparent), Offset(size.width * 0.28f, size.height * 0.25f), size.width * 0.35f))
|
||||
// 해에만 볼터치
|
||||
if (!night) listOf(0.18f, 0.82f).forEach { x ->
|
||||
drawOval(Color(0x73FF7A8A), Offset(size.width * x - size.width * 0.07f, size.height * 0.68f), Size(size.width * 0.14f, size.width * 0.08f))
|
||||
}
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) { Column(horizontalAlignment = Alignment.CenterHorizontally) { content() } }
|
||||
}
|
||||
|
||||
/** 구름 한 줄: 세로 위치·너비·높이(화면 비율), 한 번 가로지르는 초, 시작 위상 */
|
||||
private class SkyCloud(val y: Float, val w: Float, val h: Float, val sec: Int, val phase: Float)
|
||||
|
||||
// 위상을 엇갈려, 한쪽으로 빠질 때 다른 줄에서 새 구름이 들어온다
|
||||
private val SKY_CLOUDS = listOf(
|
||||
SkyCloud(0.30f, 0.19f, 0.07f, 9, 0f), SkyCloud(0.30f, 0.14f, 0.05f, 9, 0.5f),
|
||||
SkyCloud(0.56f, 0.13f, 0.05f, 6, 0.8f), SkyCloud(0.74f, 0.22f, 0.075f, 7, 0.45f),
|
||||
)
|
||||
|
||||
/** 왼쪽 밖에서 들어와 오른쪽 밖으로 빠지고 다시 왼쪽에서 (끝없이 흐르는 하늘) */
|
||||
@Composable
|
||||
private fun Cloud(c: Color, cl: SkyCloud, screen: Dp) {
|
||||
val t = rememberInfiniteTransition(label = "cloud")
|
||||
val p by t.animateFloat(0f, 1f, infiniteRepeatable(tween(cl.sec * 1000, easing = LinearEasing)), label = "drift")
|
||||
val w = screen * cl.w
|
||||
Canvas(Modifier.offset(y = screen * cl.y).size(w, screen * cl.h).graphicsLayer { translationX = ((p + cl.phase) % 1f) * (screen + w).toPx() - w.toPx() }) {
|
||||
drawCircle(c, size.height * 0.95f, Offset(size.width * 0.38f, size.height * 0.1f))
|
||||
drawRoundRect(c, cornerRadius = CornerRadius(size.height / 2))
|
||||
drawRoundRect(Color(0x33A0BEE6), Offset(0f, size.height * 0.55f), Size(size.width, size.height * 0.45f), CornerRadius(size.height / 2))
|
||||
}
|
||||
}
|
||||
|
||||
// 빗줄기·눈송이 하나: 가로 위치, 시작 위상, 한 번 떨어지는 데 걸리는 초, 크기 (모두 고정값이라 매번 같은 자리)
|
||||
private class Drop(val x: Float, val phase: Float, val sec: Float, val size: Float)
|
||||
|
||||
private val DROPS = java.util.Random(7).let { r -> List(42) { Drop(r.nextFloat(), r.nextFloat(), 0.7f + r.nextFloat() * 0.5f, 0.6f + r.nextFloat() * 0.4f) } }
|
||||
|
||||
/** 비는 추적추적 비스듬히, 눈은 천천히 흔들리며. 화면이 켜져 있는 동안만 그린다 */
|
||||
@Composable
|
||||
private fun Precip(kind: String, modifier: Modifier) {
|
||||
var time by remember { mutableFloatStateOf(0f) }
|
||||
LaunchedEffect(Unit) {
|
||||
val start = withFrameNanos { it }
|
||||
while (true) withFrameNanos { time = (it - start) / 1e9f }
|
||||
}
|
||||
val snow = kind == "snow"
|
||||
Canvas(modifier) {
|
||||
val h = size.height
|
||||
DROPS.forEachIndexed { i, d ->
|
||||
val period = if (snow) d.sec * 7f else d.sec
|
||||
val p = (time / period + d.phase) % 1f
|
||||
val y = p * (h + 40.dp.toPx()) - 20.dp.toPx()
|
||||
if (snow) {
|
||||
val x = d.x * size.width + sin((time / 2f + d.phase) * 2f * Math.PI.toFloat()) * 6.dp.toPx()
|
||||
drawCircle(Color.White.copy(alpha = 0.9f), (1.5f + 2f * d.size).dp.toPx(), Offset(x, y))
|
||||
} else {
|
||||
val len = 14.dp.toPx() * d.size
|
||||
val x = d.x * size.width + y * 0.12f
|
||||
drawLine(Color(0xCCEAF2FF), Offset(x, y), Offset(x - len * 0.12f, y - len), 1.5.dp.toPx(), StrokeCap.Round)
|
||||
// 셋 중 하나는 바닥에서 톡 튄다
|
||||
if (i % 3 == 0 && p > 0.86f) {
|
||||
val k = (p - 0.86f) / 0.14f
|
||||
drawCircle(Color(0x99EAF2FF), (2f + 6f * k).dp.toPx(), Offset(x, h * (0.8f + 0.12f * d.x)), style = Stroke(1.dp.toPx()), alpha = 1f - k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Stat(icon: String, text: String, dark: Boolean) {
|
||||
Row(
|
||||
Modifier.mallang(if (dark) Tok.statDark else Tok.stat, if (dark) Color.White.copy(alpha = 0.12f) else Tok.shade.copy(alpha = 0.9f), 14.dp)
|
||||
.padding(start = 5.dp, end = 9.dp, top = 3.dp, bottom = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Ic(icon, 16.dp)
|
||||
T(text, 12.sp, color = if (dark) Color.White else Tok.ink)
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────── 워치 스킨에서 누른 각 ─────────────
|
||||
|
||||
@Composable
|
||||
@@ -344,7 +186,7 @@ fun EventsPage(events: List<Event>, now: Instant) {
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
T("근처 축제", 14.sp, color = Tok.ink)
|
||||
T("주변 축제", 14.sp, color = Tok.ink)
|
||||
events.forEach { e ->
|
||||
Column(Modifier.fillMaxWidth().mallang().padding(start = 10.dp, end = 10.dp, top = 5.dp, bottom = 8.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
|
||||
@@ -40,6 +40,8 @@ data class Summary(
|
||||
val nowIcon: String?,
|
||||
val rainText: String?,
|
||||
val rain2h: Boolean?,
|
||||
/** 2시간 안에 낙뢰 예보 */
|
||||
val thunder: Boolean?,
|
||||
val warning: String?,
|
||||
val top: List<Gak>,
|
||||
val picks: List<Gak>,
|
||||
@@ -51,16 +53,17 @@ data class Summary(
|
||||
/** 컴플리케이션·타일에 올릴 각: 내 각 첫 번째, 없으면 오늘 1위 */
|
||||
val myGak: Gak? get() = picks.firstOrNull() ?: top.firstOrNull()
|
||||
|
||||
/** 비·눈 화면: "rain" | "snow" | null. 지금 칸이 눈이면 눈, 지금 칸이 비거나 2시간 안에 비 소식이면 비 */
|
||||
/** 비·눈: "rain" | "snow" | null. 지금 칸이 눈이면 눈, 지금 칸이 비거나 2시간 안에 비 소식이면 비 */
|
||||
val precip: String? get() = when {
|
||||
nowIcon == "snow" -> "snow"
|
||||
nowIcon == "rain" || rain2h == true -> "rain"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** 스킨 칩의 비 소식. 비·눈 화면과 어긋나지 않게 precip 을 따른다 */
|
||||
/** 비 소식. 스킨 날씨 칸(RainComplicationService)이 이 글자로 날씨 코드를 정한다 */
|
||||
val rainLabel: String get() = when {
|
||||
precip == "snow" -> "눈 와요"
|
||||
thunder == true -> "천둥 쳐요"
|
||||
nowIcon == "rain" -> "비 와요"
|
||||
precip == "rain" -> "곧 비"
|
||||
rain2h == false -> "비 없음"
|
||||
@@ -95,6 +98,7 @@ fun parseSummary(json: String): Summary {
|
||||
nowIcon = now?.str("icon"),
|
||||
rainText = now?.str("text"),
|
||||
rain2h = now?.takeIf { it.has("rain_2h") }?.getBoolean("rain_2h"),
|
||||
thunder = now?.takeIf { it.has("thunder") }?.getBoolean("thunder"),
|
||||
warning = o.str("warning"),
|
||||
top = o.list("top", ::gak),
|
||||
picks = o.list("picks", ::gak),
|
||||
@@ -117,9 +121,9 @@ object SummaryRepo {
|
||||
|
||||
/** 캐시가 refresh_at 전이면 캐시, 아니면 새로 받는다. 받기 실패하면 지난 캐시라도. 네트워크를 쓰니 메인 스레드에서 부르지 않는다. */
|
||||
fun load(context: Context, force: Boolean = false): Summary? = fetch(context, force)?.let { s ->
|
||||
// 디버그 빌드 확인용: shared_prefs/debug.xml 의 precip(rain|snow)로 비·눈 화면을 강제로 띄운다
|
||||
// 디버그 빌드 확인용: shared_prefs/debug.xml 의 precip(rain|snow|thunder)로 스킨의 비·눈·천둥을 강제로 띄운다
|
||||
val forced = if (BuildConfig.DEBUG) context.getSharedPreferences("debug", Context.MODE_PRIVATE).getString("precip", null) else null
|
||||
if (forced == null) s else s.copy(nowIcon = forced, rain2h = forced == "rain")
|
||||
if (forced == null) s else s.copy(nowIcon = if (forced == "thunder") "rain" else forced, rain2h = forced != "snow", thunder = forced == "thunder")
|
||||
}
|
||||
|
||||
private fun fetch(context: Context, force: Boolean): Summary? {
|
||||
|
||||
@@ -18,7 +18,6 @@ object Tok {
|
||||
val navyTop = Color(0xFF2B3577)
|
||||
val card = Color.White.copy(alpha = 0.78f)
|
||||
val stat = Color.White.copy(alpha = 0.72f)
|
||||
val statDark = Color.White.copy(alpha = 0.18f)
|
||||
|
||||
val jua = FontFamily(Font(R.font.jua))
|
||||
val bagel = FontFamily(Font(R.font.bagel_fat_one))
|
||||
@@ -34,16 +33,6 @@ fun skyBrush(mode: String): Brush = when (mode) {
|
||||
else -> v(0f to 0xFF9FD3FF, 0.55f to 0xFFCFE9FF, 1f to 0xFFF1F8FF)
|
||||
}
|
||||
|
||||
/** 비·눈 오는 날 하늘. 밤에는 어두운 회청색 */
|
||||
fun precipBrush(kind: String, mode: String): Brush = when {
|
||||
mode == "night" -> v(0f to 0xFF1C2238, 0.6f to 0xFF2E3650, 1f to 0xFF434B66)
|
||||
kind == "snow" -> v(0f to 0xFFB8C4D6, 0.55f to 0xFFDFE6F0, 1f to 0xFFF4F7FB)
|
||||
else -> v(0f to 0xFF7F93AD, 0.55f to 0xFFA9B7C9, 1f to 0xFFD5DDE8)
|
||||
}
|
||||
|
||||
/** 하늘 위 글자가 흰색이어야 하는 시간대 */
|
||||
fun isDark(mode: String) = mode == "evening" || mode == "night"
|
||||
|
||||
// 카드·장 배경 (.b-bg-*)
|
||||
val bgButter = v(0f to 0xFFFFE7A0, 1f to 0xFFFFF6D8)
|
||||
val bgMint = v(0f to 0xFFBFECD6, 1f to 0xFFEFFAF4)
|
||||
@@ -59,6 +48,9 @@ private val ICONS = mapOf(
|
||||
"glasses" to R.drawable.e_glasses, "makeup" to R.drawable.e_makeup, "naengmyeon" to R.drawable.e_naengmyeon, "taxi" to R.drawable.e_taxi,
|
||||
"delivery" to R.drawable.e_delivery, "garden" to R.drawable.e_garden, "photo" to R.drawable.e_photo, "baseball" to R.drawable.e_baseball,
|
||||
"study" to R.drawable.e_study, "netflix" to R.drawable.e_netflix, "chestnut" to R.drawable.e_chestnut,
|
||||
"drive" to R.drawable.e_drive, "fishing" to R.drawable.e_fishing, "golf" to R.drawable.e_golf, "jipkok" to R.drawable.e_jipkok,
|
||||
"kimchi" to R.drawable.e_kimchi, "kite" to R.drawable.e_kite, "maple" to R.drawable.e_maple, "sheaf" to R.drawable.e_sheaf,
|
||||
"sweet_potato" to R.drawable.e_sweet_potato, "tangerine" to R.drawable.e_tangerine, "waterplay" to R.drawable.e_waterplay,
|
||||
"sun" to R.drawable.e_sun, "sun_cloud" to R.drawable.e_sun_cloud, "cloud" to R.drawable.e_cloud, "rain" to R.drawable.e_rain,
|
||||
"snow" to R.drawable.e_snow, "sunset" to R.drawable.e_sunset, "moon" to R.drawable.e_moon,
|
||||
"gold" to R.drawable.e_gold, "silver" to R.drawable.e_silver, "bronze" to R.drawable.e_bronze,
|
||||
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 16 KiB |
@@ -1,2 +1,4 @@
|
||||
org.gradle.jvmargs=-Xmx2g
|
||||
android.useAndroidX=true
|
||||
# 워치 스킨 버전. 스킨(watchface.xml·리소스)을 바꾸면 1 올린다. 앱은 깔린 스킨이 이보다 낮으면 앱에 실은 스킨으로 바꿔 끼운다
|
||||
NALSSIGAK_SKIN_VERSION=2
|
||||
@@ -9,15 +9,16 @@ android {
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "kr.o2o.nalssigak.watchface"
|
||||
// 앱(:app)이 Watch Face Push 로 같이 설치하려면 "<앱 패키지>.watchfacepush.<이름>" 이어야 한다
|
||||
applicationId = "kr.o2o.nalssigak.watchfacepush.skin"
|
||||
// WFF 버전 2 는 Wear OS 5(API 34)부터
|
||||
minSdk = 34
|
||||
targetSdk = 34
|
||||
versionCode = 1
|
||||
versionCode = providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get().toInt()
|
||||
versionName = "0.1"
|
||||
}
|
||||
buildTypes.getByName("release") {
|
||||
// 스킨 번들엔 dex 가 없어야 한다. R8 이 R 클래스까지 다 걷어내게
|
||||
// 스킨 APK 엔 dex 가 없어야 한다 (Play 번들, 앱에 싣는 Watch Face Push 둘 다). R8 이 R 클래스까지 다 걷어내게
|
||||
buildTypes.all {
|
||||
isMinifyEnabled = true
|
||||
// 스킨 XML 이 이름으로만 부르는 아이콘·글꼴을 안 쓰는 걸로 보고 지운다. 켜지 말 것
|
||||
isShrinkResources = false
|
||||
|
||||
@@ -77,6 +77,33 @@ def sun_rays():
|
||||
<Transform target="angle" value="360 * fract([SECOND_MILLISECOND] / 60)"/>
|
||||
</PartDraw>'''
|
||||
|
||||
# 비·눈·천둥 때 해 대신 가운데 구름: 몸통, 아래 그늘. 점수가 흰 글씨라 눈구름도 너무 밝지 않게
|
||||
CLOUD_ORB = {"rain": ("#FF8796B0", "#4D394A66"), "thunder": ("#FF5F6684", "#66232A45"), "snow": ("#FF9FB2D3", "#40394A66")}
|
||||
|
||||
def cloud_orb(kind):
|
||||
"""해 구슬 자리에 몽실한 구름 하나 (봉우리 셋 + 둥근 바닥). 천둥이면 오른쪽 아래로 번개, 5초에 한 번 화면이 번쩍"""
|
||||
body, shade = CLOUD_ORB[kind]
|
||||
k = ORB / 136
|
||||
puffs = [(10, 34, 60), (36, 8, 80), (80, 44, 52)]
|
||||
shapes = "".join(f'<Ellipse x="{int(x * k)}" y="{int(y * k)}" width="{int(d * k)}" height="{int(d * k)}"><Fill color="{body}"/></Ellipse>' for x, y, d in puffs)
|
||||
shapes += f'<RoundRectangle x="{int(4 * k)}" y="{int(64 * k)}" width="{int(128 * k)}" height="{int(56 * k)}" cornerRadiusX="{int(28 * k)}" cornerRadiusY="{int(28 * k)}"><Fill color="{body}"/></RoundRectangle>'
|
||||
shapes += f'<RoundRectangle x="{int(4 * k)}" y="{int(96 * k)}" width="{int(128 * k)}" height="{int(24 * k)}" cornerRadiusX="{int(12 * k)}" cornerRadiusY="{int(12 * k)}"><Fill color="{shade}"/></RoundRectangle>'
|
||||
shapes += f'<Ellipse x="{int(48 * k)}" y="{int(16 * k)}" width="{int(34 * k)}" height="{int(22 * k)}"><Fill color="#59FFFFFF"/></Ellipse>'
|
||||
out = f'<PartDraw x="{CX - ORB // 2}" y="{CY - ORB // 2}" width="{ORB}" height="{ORB}">{AMB0}{shapes}</PartDraw>'
|
||||
if kind == "thunder":
|
||||
bolt = [(26, 2), (12, 28), (28, 28), (14, 54)]
|
||||
lines = "".join(f'<Line startX="{a[0]}" startY="{a[1]}" endX="{b[0]}" endY="{b[1]}"><Stroke thickness="7" color="#FFFFD23F" cap="ROUND"/></Line>' for a, b in zip(bolt, bolt[1:]))
|
||||
out += f'<PartDraw x="{CX + 20}" y="{CY + ORB // 2 - 26}" width="40" height="56">{AMB0}{lines}</PartDraw>'
|
||||
out += (f'<PartDraw x="0" y="0" width="{W}" height="{W}" alpha="0">{AMB0}<Rectangle x="0" y="0" width="{W}" height="{W}"><Fill color="#FFFFFFFF"/></Rectangle>'
|
||||
f'<Transform target="alpha" value="fract([SECOND_MILLISECOND] / 5) < 0.04 ? 110 : 0"/></PartDraw>')
|
||||
return out
|
||||
|
||||
NIGHT_EXPR = "[HOUR_0_23] < 5 || [HOUR_0_23] >= 21"
|
||||
|
||||
def sun_or_moon():
|
||||
"""맑을 때(또는 앱 값이 아직 없을 때) 가운데: 밤엔 달빛 구슬, 낮엔 햇살 두른 해"""
|
||||
return f'<Compare expression="night">{orb_fill(MOON)}</Compare><Default>{sun_rays()}{orb_fill(SUN)}</Default>'
|
||||
|
||||
def mode_block(colors, pos, ink, night=False):
|
||||
parts = [sky(colors, pos)]
|
||||
if night:
|
||||
@@ -90,21 +117,19 @@ def text(x, y, w, h, family, size, color, expr, amb=False):
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="{family}" size="{size}" color="{color}"><Template><![CDATA[%s]]><Parameter expression="{expr}"/></Template></Font></Text>
|
||||
</PartText>'''
|
||||
|
||||
def orb_slot():
|
||||
def orb_text():
|
||||
"""해 구슬 위 1위 점수·이름. 날씨 칸 값: 값 = 날씨 코드 × 1000 + 1위 점수, 제목 = 1위 이름 (1위가 없으면 빈 제목)"""
|
||||
x, y = CX - ORB // 2, CY - ORB // 2
|
||||
body = text(0, int(ORB * .19), ORB, int(ORB * .45), "bagel_fat_one", 50, "#FFFFFFFF", "[COMPLICATION.TEXT]") + text(14, int(ORB * .62), ORB - 28, 28, "jua", 19, "#FFFFFFFF", "[COMPLICATION.TITLE]")
|
||||
return f'''<ComplicationSlot slotId="0" x="{x}" y="{y}" width="{ORB}" height="{ORB}" displayName="slot_rank1" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.Rank1ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="{ORB}" height="{ORB}"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
body = (text(x, y + int(ORB * .19), ORB, int(ORB * .45), "bagel_fat_one", 50, "#FFFFFFFF", f"round({VALUE} % 1000)")
|
||||
+ text(x + 14, y + int(ORB * .62), ORB - 28, 28, "jua", 19, "#FFFFFFFF", "[COMPLICATION.TITLE]"))
|
||||
return f'''<Condition>
|
||||
<Expressions><Expression name="ranked"><![CDATA[[COMPLICATION.TITLE] != ""]]></Expression></Expressions>
|
||||
<Compare expression="ranked">
|
||||
{body}
|
||||
</Complication>
|
||||
<Complication type="SHORT_TEXT">
|
||||
{body}
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>'''
|
||||
</Compare>
|
||||
</Condition>'''
|
||||
|
||||
VALUE = "[COMPLICATION.RANGED_VALUE_VALUE]"
|
||||
PROGRESS = "clamp([COMPLICATION.RANGED_VALUE_VALUE], [COMPLICATION.RANGED_VALUE_MIN], [COMPLICATION.RANGED_VALUE_MAX]) / ([COMPLICATION.RANGED_VALUE_MAX] - [COMPLICATION.RANGED_VALUE_MIN]) * 360"
|
||||
|
||||
def icon_by_title(x, y, size):
|
||||
@@ -155,9 +180,11 @@ def chip(x, w, icon, expr):
|
||||
{text(x + 32, CHIP_Y + 5, w - 38, 30, "jua", 21, INK, expr, amb=True)}'''
|
||||
|
||||
def precip_slot():
|
||||
"""화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면
|
||||
아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기, "눈 와요"면 눈송이를 그린다.
|
||||
터치는 막지 않게 BoundingOval 을 1px 로 둔다. 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다."""
|
||||
"""화면 전체를 덮는 숨은 칸. WFF 는 칸이 8개까지라 날씨와 1위를 이 칸 하나로 받는다.
|
||||
날씨각 앱(RainComplicationService)이 값 = 날씨 코드 × 1000 + 1위 점수, 글자 = 기온, 제목 = 1위 이름을 준다.
|
||||
날씨 코드 1(비·곧 비)이면 빗줄기와 비구름, 2(천둥)면 빗줄기와 번개 구름, 3(눈)이면 눈송이와 눈구름을 가운데 해 자리에 그리고,
|
||||
그 위에 1위 점수·이름, 아래에 기온 칩을 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다.
|
||||
터치는 가운데 구슬만 받는다(누르면 앱). 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다."""
|
||||
import random
|
||||
r = random.Random(7)
|
||||
drops, flakes = [], []
|
||||
@@ -179,28 +206,44 @@ def precip_slot():
|
||||
<Transform target="x" value="{x} + 9 * sin(rad(360 * fract([SECOND_MILLISECOND] / 3 + {ph:.2f})))"/>
|
||||
</PartDraw>''')
|
||||
shade = lambda c: f'<PartDraw x="0" y="0" width="{W}" height="{W}">{AMB0}<Rectangle x="0" y="0" width="{W}" height="{W}"><Fill color="{c}"/></Rectangle></PartDraw>'
|
||||
return f'''<ComplicationSlot slotId="7" x="0" y="0" width="{W}" height="{W}" displayName="slot_precip" supportedTypes="SHORT_TEXT EMPTY" isCustomizable="FALSE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.RainComplicationService" primaryProviderType="SHORT_TEXT"/>
|
||||
<BoundingOval x="0" y="0" width="1" height="1"/>
|
||||
<Complication type="SHORT_TEXT">
|
||||
mode = f"floor({VALUE} / 1000)"
|
||||
return f'''<ComplicationSlot slotId="7" x="0" y="0" width="{W}" height="{W}" displayName="slot_precip" supportedTypes="RANGED_VALUE EMPTY" isCustomizable="FALSE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.RainComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="{W}" height="{W}"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
<Condition>
|
||||
<Expressions>
|
||||
<Expression name="rain"><![CDATA[[COMPLICATION.TITLE] == "비 와요" || [COMPLICATION.TITLE] == "곧 비"]]></Expression>
|
||||
<Expression name="snow"><![CDATA[[COMPLICATION.TITLE] == "눈 와요"]]></Expression>
|
||||
<Expression name="thunder"><![CDATA[{mode} == 2]]></Expression>
|
||||
<Expression name="rain"><![CDATA[{mode} == 1]]></Expression>
|
||||
<Expression name="snow"><![CDATA[{mode} == 3]]></Expression>
|
||||
<Expression name="night"><![CDATA[{NIGHT_EXPR}]]></Expression>
|
||||
</Expressions>
|
||||
<Compare expression="thunder">
|
||||
{shade("#80394766")}
|
||||
{"".join(drops)}
|
||||
{cloud_orb("thunder")}
|
||||
</Compare>
|
||||
<Compare expression="rain">
|
||||
{shade("#66485A78")}
|
||||
{"".join(drops)}
|
||||
{cloud_orb("rain")}
|
||||
</Compare>
|
||||
<Compare expression="snow">
|
||||
{shade("#40A0AEC4")}
|
||||
{"".join(flakes)}
|
||||
{cloud_orb("snow")}
|
||||
</Compare>
|
||||
{sun_or_moon()}
|
||||
</Condition>
|
||||
{chip(CX - 52, 104, "thermo", "[COMPLICATION.TEXT]")}
|
||||
{orb_text()}
|
||||
</Complication>
|
||||
<Complication type="EMPTY">
|
||||
<Condition>
|
||||
<Expressions><Expression name="night"><![CDATA[{NIGHT_EXPR}]]></Expression></Expressions>
|
||||
{sun_or_moon()}
|
||||
</Condition>
|
||||
{chip(108, 104, "thermo", "[COMPLICATION.TEXT]")}
|
||||
{chip(220, 122, "umbrella", "[COMPLICATION.TITLE]")}
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>'''
|
||||
|
||||
def event_slot():
|
||||
@@ -215,7 +258,7 @@ def event_slot():
|
||||
<RoundRectangle x="0" y="0" width="{w}" height="{h}" cornerRadiusX="{h // 2}" cornerRadiusY="{h // 2}"><Fill color="{CARD}"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartText x="8" y="2" width="{w - 16}" height="{h - 4}">{AMB0}
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="{INK}"><Template><![CDATA[🎉 주변 축제 · %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="{INK}"><Template><![CDATA[🎉 주변 축제: %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
@@ -230,7 +273,7 @@ exprs = "\n ".join(f'<Expression name="{k}"><![CDATA[{v[0].replace(">
|
||||
compares = "\n ".join(f'<Compare expression="{k}">\n {mode_block(v[1], v[2], v[3])}\n </Compare>' for k, v in MODES.items())
|
||||
|
||||
xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온·비 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
|
||||
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위, 비·눈·천둥이면 구름), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
|
||||
직접 고치지 말고 watch/watchface/gen_watchface.py 를 고친 뒤 다시 만든다: python3 gen_watchface.py src/main/res/raw/watchface.xml -->
|
||||
<WatchFace width="{W}" height="{W}">
|
||||
<Metadata key="CLOCK_TYPE" value="DIGITAL"/>
|
||||
@@ -247,15 +290,9 @@ xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
</Default>
|
||||
</Condition>
|
||||
<!-- 주의: 칸(ComplicationSlot) 순서·slotId 를 바꿔 덮어 설치하면 기존 기기에서 공급원이 한 칸씩 밀린다 (에뮬레이터에서 확인). 새 칸은 맨 뒤에 붙인다 -->
|
||||
<!-- 가운데 해·달·구름은 날씨 칸 안에서 비 막 위에 그린다 -->
|
||||
{precip_slot()}
|
||||
<!-- 해 구슬은 비 막 위에 (밤엔 달빛) -->
|
||||
<Condition>
|
||||
<Expressions><Expression name="night"><![CDATA[[HOUR_0_23] < 5 || [HOUR_0_23] >= 21]]></Expression></Expressions>
|
||||
<Compare expression="night">{orb_fill(MOON)}</Compare>
|
||||
<Default>{sun_rays()}{orb_fill(SUN)}</Default>
|
||||
</Condition>
|
||||
{clock("#FFFFFFFF", ambient_visible=True)}
|
||||
{orb_slot()}
|
||||
{"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))}
|
||||
{event_slot()}
|
||||
</Scene>
|
||||
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |