Compare commits

..
8 Commits
Author SHA1 Message Date
minaChoi ab686165a8 fix: 단풍 지도 그림을 반도만 남긴 평면 그림으로 — 바다·지형 색 빼고 카드 배경 위에 흰 땅과 아래 그림자만 (Codex, 실제 해안선에 맞춤) 2026-10-21 10:19:27 +09:00
minaChoi 463978c183 feat: 단풍 지도 카드 — 산림청 2026 단풍절정 예측 23곳을 한반도 그림 지도(실제 해안선에 맞춘 Codex 그림, 독도 포함) 위에 지금 절정·곧·아직·지남 점으로, 서울 근교 절정일, 9/20~11/25 오늘 피드에 2026-10-21 10:02:30 +09:00
minaChoi 74a46dd66a feat: 각 포스트가 비어 보이지 않게 — 점수 구간 설명 문장과 근거 네 줄(비중 큰 조건부터 지금 값: 비 확률·체감·바람·미세먼지)을 카드 안에, 글 설명엔 내일 점수만 2026-10-21 09:49:48 +09:00
minaChoi 3c34b958fa docs: 이벤트 추적 문서에 구글 로그인(method google)과 홈 화면 추가 이벤트 5개 2026-10-21 09:12:38 +09:00
minaChoi c788430fa7 fix: 홈 화면에 추가를 PC Chrome·Edge(설치창을 띄울 수 있는 브라우저)에서도 보이게, PC Safari·Firefox 에선 숨김 2026-10-21 09:10:10 +09:00
minaChoi 77d29ce24f fix: 홈 화면에 추가 카드·메뉴를 휴대폰(아이폰·안드로이드·앱 안 브라우저)에서만 보이게 2026-10-21 09:05:50 +09:00
minaChoi e5716c0c7c feat: 홈 화면에 추가 — 오늘의 각 아래 설치 카드(닫으면 2주 숨김, 홈 화면에서 열면 안 보임)와 내 정보 메뉴, 안드로이드는 설치창·아이폰·카카오톡 등은 기기별 안내, 192·512·maskable 아이콘과 서비스 워커, 설치·실행 GA 이벤트 2026-10-21 09:02:08 +09:00
minaChoi 4e9b0bacba feat: 구글 로그인 — 로그인 창에 구글로 계속하기 버튼, 서버가 구글 ID 토큰 서명·클라이언트 ID·만료를 확인, 처음이면 자동 닉네임으로 가입(구글 이름·이메일은 저장 안 함) 2026-10-21 08:52:34 +09:00
34 changed files with 1061 additions and 31 deletions

No files matched your search

+2
View File
@@ -20,6 +20,8 @@ PORT=9810
# ── 백엔드: 로그인 토큰 서명 키. 비우면 로그인이 동작하지 않는다 # ── 백엔드: 로그인 토큰 서명 키. 비우면 로그인이 동작하지 않는다
# 생성: python -c "import secrets; print(secrets.token_urlsafe(48))" # 생성: python -c "import secrets; print(secrets.token_urlsafe(48))"
# 구글 로그인 OAuth 클라이언트 ID (console.cloud.google.com/apis/credentials, 웹 애플리케이션)
GOOGLE_CLIENT_ID=
JWT_ACCESS_SECRET= JWT_ACCESS_SECRET=
JWT_REFRESH_SECRET= JWT_REFRESH_SECRET=
+1 -1
View File
@@ -37,7 +37,7 @@
| [ ] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글 로그인 여부 확인 필요 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` | | [ ] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글 로그인 여부 확인 필요 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` |
| [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` | | [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` |
| [ ] | 사람 글 사진 올리기 — 보여 주기(talk.image)는 됨, 올리기는 패키지 설치 확인 후(python-multipart·Pillow, 위치 정보 지우기) | 10/20 회의 결정 | `backend/router/v1/talk/talk.py`, `frontend/src/b/talk.tsx` | | [ ] | 사람 글 사진 올리기 — 보여 주기(talk.image)는 됨, 올리기는 패키지 설치 확인 후(python-multipart·Pillow, 위치 정보 지우기) | 10/20 회의 결정 | `backend/router/v1/talk/talk.py`, `frontend/src/b/talk.tsx` |
| [ ] | 날씨 타로·오늘 날씨 코디 기획 (옷차림 [보류] 행과 합침) | 10/20 회의 | | | [ ] | 날씨 타로·오늘 날씨 코디 기획 (옷차림 [보류] 행과 합침). 타로는 운세 주제별 귀여운 각 이름으로 — 예: 애정 날씨 타로 → '다툼구름각' (사용자 10/21) | 10/20 회의 | |
| [ ] | **[결정 필요]** 피드 각 카드에서 빨래각 같은 평이한 각 빼기 — 피드 각 3개는 전체 순위로 골라 빨래각(priority 1)이 들어감. priority를 낮추면 히어로·각 탭 순위도 바뀜. priority 조정 vs 피드에선 is_fun 각 먼저 | 피드 순서 작업 중 발견 | `backend/seed/index_definition.json`, `backend/services/feed_service.py` | | [ ] | **[결정 필요]** 피드 각 카드에서 빨래각 같은 평이한 각 빼기 — 피드 각 3개는 전체 순위로 골라 빨래각(priority 1)이 들어감. priority를 낮추면 히어로·각 탭 순위도 바뀜. priority 조정 vs 피드에선 is_fun 각 먼저 | 피드 순서 작업 중 발견 | `backend/seed/index_definition.json`, `backend/services/feed_service.py` |
| [ ] | 오늘의 각 카드 순위와 점수 순서가 다름(1위 83점, 2위 97점) — 순위에 중요도를 섞어서. 카드로 보이니 어색함 | 카드화 중 발견 | `backend/services/index_service.py` | | [ ] | 오늘의 각 카드 순위와 점수 순서가 다름(1위 83점, 2위 97점) — 순위에 중요도를 섞어서. 카드로 보이니 어색함 | 카드화 중 발견 | `backend/services/index_service.py` |
| [ ] | 테스트 실패 2건: `test_feed.py::test_feed_assembles_hero_stories_posts_and_bands`(각 57개, 기대 40 — 커밋 전 각 추가 영향), `test_weather_today.py:60`(날짜 따라 18시 아이콘 moon) | 피드 순서 작업 중 발견 | `backend/tests/` | | [ ] | 테스트 실패 2건: `test_feed.py::test_feed_assembles_hero_stories_posts_and_bands`(각 57개, 기대 40 — 커밋 전 각 추가 영향), `test_weather_today.py:60`(날짜 따라 18시 아이콘 moon) | 피드 순서 작업 중 발견 | `backend/tests/` |
+43
View File
@@ -0,0 +1,43 @@
import time
from typing import Optional
import httpx
from jose import JWTError, jwt
from common.logger import LOG
from config.settings import settings
CERTS_URL = "https://www.googleapis.com/oauth2/v3/certs"
ISSUERS = ("accounts.google.com", "https://accounts.google.com")
_CERTS_TTL = 3600
_certs: dict = {"keys": [], "at": 0.0}
async def _keys(force: bool = False) -> list[dict]:
"""구글 서명 공개키. 한 시간 캐시하고, 모르는 키가 오면 한 번 다시 받는다."""
if force or not _certs["keys"] or time.monotonic() - _certs["at"] > _CERTS_TTL:
async with httpx.AsyncClient(timeout=5) as c:
res = await c.get(CERTS_URL)
res.raise_for_status()
_certs["keys"], _certs["at"] = res.json()["keys"], time.monotonic()
return _certs["keys"]
async def verify(credential: str) -> Optional[str]:
"""구글 로그인 버튼이 준 ID 토큰을 확인하고 구글 사용자 고유 번호(sub)를 돌려준다. 서명·발급처·우리 클라이언트 ID·만료가 하나라도 안 맞으면 None."""
if not settings.google_client_id:
LOG.error("[google] GOOGLE_CLIENT_ID is empty")
return None
try:
kid = jwt.get_unverified_header(credential).get("kid")
keys = await _keys()
key = next((k for k in keys if k.get("kid") == kid), None) or next((k for k in await _keys(force=True) if k.get("kid") == kid), None)
if key is None:
return None
claims = jwt.decode(credential, key, algorithms=["RS256"], audience=settings.google_client_id, options={"verify_at_hash": False})
except (JWTError, httpx.HTTPError, KeyError, ValueError) as e:
LOG.warning("[google] id token rejected: %s", type(e).__name__)
return None
if claims.get("iss") not in ISSUERS or not claims.get("sub"):
return None
return str(claims["sub"])
+3
View File
@@ -37,6 +37,9 @@ class Settings(BaseSettings):
# 사람 글 사진을 저장할 폴더 (compose 볼륨) # 사람 글 사진을 저장할 폴더 (compose 볼륨)
upload_dir: str = "uploads" upload_dir: str = "uploads"
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
google_client_id: str = ""
jwt_access_secret: str = "" jwt_access_secret: str = ""
jwt_refresh_secret: str = "" jwt_refresh_secret: str = ""
jwt_access_minutes: int = 60 jwt_access_minutes: int = 60
+6
View File
@@ -22,6 +22,12 @@ class UserCRUD:
await s.flush() await s.flush()
return user return user
async def create_google(self, s: AsyncSession, sub: str, nickname: str) -> User:
user = User(login_id=f"google_{sub}", provider_uid=sub, nickname=nickname, provider=2)
s.add(user)
await s.flush()
return user
async def update(self, s: AsyncSession, user_id: uuid.UUID, values: dict) -> Optional[User]: async def update(self, s: AsyncSession, user_id: uuid.UUID, values: dict) -> Optional[User]:
user = await self.get(s, user_id) user = await self.get(s, user_id)
if user is None: if user is None:
+13 -1
View File
@@ -4,7 +4,8 @@ from common.auth import current_user
from common.database.model.models import User from common.database.model.models import User
from common.enums import AuthProvider, ErrorType from common.enums import AuthProvider, ErrorType
from common.models.errors import error_info from common.models.errors import error_info
from router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me from config.settings import settings
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me
from services.auth_service import AuthService from services.auth_service import AuthService
router = APIRouter(prefix="/v1/auth", tags=["auth"]) router = APIRouter(prefix="/v1/auth", tags=["auth"])
@@ -33,6 +34,17 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
return _auth(err, user, service) return _auth(err, user, service)
@router.post("/google", response_model=Res_Auth, response_model_exclude_none=True, summary="구글 로그인 (처음이면 자동 닉네임으로 가입)")
async def google_login(req: Req_Google, service: AuthService = Depends()) -> Res_Auth:
err, user = await service.google(req.credential)
return _auth(err, user, service)
@router.get("/config", response_model=Res_AuthConfig, response_model_exclude_none=True, summary="로그인 화면 설정 (구글 클라이언트 ID)")
async def auth_config() -> Res_AuthConfig:
return Res_AuthConfig(google_client_id=settings.google_client_id or None)
@router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급") @router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급")
async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth: async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth:
err, user = await service.refresh(req.refresh_token) err, user = await service.refresh(req.refresh_token)
+10
View File
@@ -1,5 +1,7 @@
from typing import Optional from typing import Optional
from pydantic import Field
from common.enums import AuthProvider from common.enums import AuthProvider
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
@@ -15,6 +17,10 @@ class Req_Login(Req_WebPacketProtocol):
password: str password: str
class Req_Google(Req_WebPacketProtocol):
credential: str = Field(min_length=20, max_length=4096, description="구글 로그인 버튼이 준 ID 토큰")
class Req_Refresh(Req_WebPacketProtocol): class Req_Refresh(Req_WebPacketProtocol):
refresh_token: str refresh_token: str
@@ -47,3 +53,7 @@ class Res_Logout(Res_WebPacketProtocol):
class Res_Me(Res_WebPacketProtocol): class Res_Me(Res_WebPacketProtocol):
me: Optional[Me] = None me: Optional[Me] = None
class Res_AuthConfig(Res_WebPacketProtocol):
google_client_id: Optional[str] = Field(None, description="구글 로그인 버튼에 쓸 OAuth 클라이언트 ID. 없으면 구글 로그인을 숨긴다")
+2
View File
@@ -49,6 +49,8 @@ class GakSlide(WebPacketProtocol):
score: int score: int
line: str line: str
summary: str summary: str
rows: list[Row] = Field(default=[], description="점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)")
say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)")
class Cut(WebPacketProtocol): class Cut(WebPacketProtocol):
+31
View File
@@ -1,4 +1,5 @@
import re import re
import secrets
import uuid import uuid
from typing import Optional from typing import Optional
@@ -6,6 +7,7 @@ from fastapi import Depends
from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens, verify_password from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens, verify_password
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.google_id import verify as verify_google
from common.database.model.models import User from common.database.model.models import User
from common.enums import ErrorType from common.enums import ErrorType
from config.settings import settings from config.settings import settings
@@ -19,6 +21,15 @@ COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow") MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
_NICK_WORDS = ("맑은", "포근한", "산들", "반짝", "느긋한", "보슬", "선선한", "따끈한")
_NICK_ANIMALS = {"rabbit": "토끼", "bear": "곰", "dog": "강아지", "sun": "해님", "moon": "달님", "cloud": "구름"}
def auto_nickname() -> str:
"""구글로 처음 들어온 사람의 이름: 맑은토끼 482. 내 정보에서 바꿀 수 있다."""
return f"{secrets.choice(_NICK_WORDS)}{secrets.choice(list(_NICK_ANIMALS.values()))} {secrets.randbelow(900) + 100}"
class AuthService: class AuthService:
def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None: def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None:
self.crud = crud self.crud = crud
@@ -47,6 +58,26 @@ class AuthService:
return ErrorType.AUTH_FAILED, None return ErrorType.AUTH_FAILED, None
return ErrorType.SUCCESS, user return ErrorType.SUCCESS, user
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
sub = await verify_google(credential)
if sub is None:
return ErrorType.AUTH_FAILED, None
login_id = f"google_{sub}"
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
if err is not ErrorType.SUCCESS:
return err, None
if user is None:
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create_google(s, sub, auto_nickname()))
if err is not ErrorType.SUCCESS:
# 같은 계정이 동시에 처음 들어온 경우엔 먼저 만들어진 쪽을 쓴다
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
if err is not ErrorType.SUCCESS or user is None:
return ErrorType.DB_ERROR, None
if user.status != 1:
return ErrorType.AUTH_FAILED, None
return ErrorType.SUCCESS, user
async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]: async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]:
claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh") claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh")
if claims is None: if claims is None:
+28 -4
View File
@@ -1,5 +1,6 @@
import asyncio import asyncio
import random import random
import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta from datetime import date, datetime, time, timedelta
from typing import Optional from typing import Optional
@@ -456,7 +457,7 @@ class FeedService:
def _gak(self, p: Post, i: IndexItem) -> PostData: def _gak(self, p: Post, i: IndexItem) -> PostData:
d = i.definition d = i.definition
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i), return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary)], slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))],
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"]) share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]: def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
@@ -723,9 +724,32 @@ def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
return sentences[str(lo)] if lo is not None else None return sentences[str(lo)] if lo is not None else None
# 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다
_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"}
_NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "}
def gak_rows(i: IndexItem, n: int = 4) -> list[Row]:
"""비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m)."""
d, notes = i.definition, i.score.notes or {}
weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}"))
axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)]
rows = []
for a in axes[:n]:
head, _, tail = notes[a].partition(", ")
prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None
if prob:
value = prob.group(0)
elif a == "air" and tail:
value = tail
else:
value = head.removeprefix(_NOTE_HEAD.get(a, ""))
rows.append(Row(label=_AXIS_NAME[a], value=value))
return rows
def _gak_caption(i: IndexItem) -> str: def _gak_caption(i: IndexItem) -> str:
"""점수 구간 설명 문장 + 슬라이드에 없는 내일 점수(없으면 하기 좋은 시간).""" """슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
band = _band_sentence(i.definition.sentences, i.score.score)
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None) nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
if nxt is not None: if nxt is not None:
diff = nxt.score - i.score.score diff = nxt.score - i.score.score
@@ -734,7 +758,7 @@ def _gak_caption(i: IndexItem) -> str:
else: else:
spans = [_span(w) for w in i.definition.windows or []] spans = [_span(w) for w in i.definition.windows or []]
tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요." tail = f"하기 좋은 때는 {spans[0][0]}~{spans[0][1]}시예요." if spans else f"오늘의 각 {i.rank}위예요."
return f"{band} {tail}" if band else tail return tail
def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]: def _temp_change(today: Optional[TodayWeather], tomorrow: Optional[TodayWeather]) -> Optional[str]:
+20 -4
View File
@@ -383,14 +383,14 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg" assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
def test_gak_caption_starts_with_score_band_sentence(): def test_gak_band_sentence_moves_to_slide_and_caption_keeps_hours():
"""점수 구간 설명 문장은 슬라이드(say)에 두고, 글 설명엔 내일 점수나 하기 좋은 때만."""
from types import SimpleNamespace from types import SimpleNamespace
from services.feed_service import _gak_caption from services.feed_service import _band_sentence, _gak_caption
d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}]) d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}])
item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1) item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1)
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요." assert _band_sentence(d.sentences, 83) == "딱 좋아요!"
item.definition.sentences = {}
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요." assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
@@ -410,3 +410,19 @@ def test_uv_post_only_when_moderate_or_higher():
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([(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([(9, 1.0), (12, 2.5)])) is None
assert FeedService._uv_post(None, base, ctx([])) is None assert FeedService._uv_post(None, base, ctx([])) is None
def test_gak_rows_shows_heaviest_conditions_with_short_values():
from types import SimpleNamespace
from services.feed_service import gak_rows
d = SimpleNamespace(weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=0, weight_air=15, weight_uv=0, weight_sun=0, weight_view=0, weight_time=20)
notes = {"temp": "체감 18°, 편한 범위 15~25° 안", "rain": "비 확률 20%", "wind": "바람 초속 3.1m", "air": "초미세먼지 16㎍/㎥, 좋음", "time": "수요일"}
item = SimpleNamespace(definition=d, score=SimpleNamespace(notes=notes))
assert [(r.label, r.value) for r in gak_rows(item, 3)] == [("기온", "체감 18°"), ("비", "확률 20%"), ("미세먼지", "좋음")]
# 점수에 안 쓰는 조건은 뒤에 지금 날씨로 채운다
d.weight_wind = 0
assert [r.label for r in gak_rows(item)] == ["기온", "비", "미세먼지", "바람"]
item.score.notes = {**notes, "rain": "비 소식, 내일까지 비 확률 70%"}
assert gak_rows(item)[1].value == "확률 70%"
+80
View File
@@ -0,0 +1,80 @@
import time
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from httpx import ASGITransport, AsyncClient
from jose import jwk, jwt
import common.google_id as google_id
import services.auth_service as auth_service
from config.settings import settings
from router.router import app
CLIENT_ID = "test-client.apps.googleusercontent.com"
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
@pytest.fixture
def google_keys(monkeypatch):
"""가짜 구글 서명키. 공개키는 _keys 대신 돌려준다."""
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
public = jwk.construct(key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo), "RS256").to_dict()
public["kid"] = "k1"
async def keys(force: bool = False):
return [public]
monkeypatch.setattr(google_id, "_keys", keys)
def sign(**over):
claims = {"iss": "https://accounts.google.com", "aud": CLIENT_ID, "sub": "1234567890", "exp": int(time.time()) + 600, "iat": int(time.time()), "name": "홍길동", "email": "a@example.com"}
claims.update(over)
return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": "k1"})
return sign
@pytest.mark.anyio
async def test_verify_accepts_only_our_valid_tokens(google_keys):
assert await google_id.verify(google_keys()) == "1234567890"
assert await google_id.verify(google_keys(aud="other.apps.googleusercontent.com")) is None
assert await google_id.verify(google_keys(iss="https://evil.example")) is None
assert await google_id.verify(google_keys(exp=int(time.time()) - 10)) is None
assert await google_id.verify(google_keys()[:-4] + "abcd") is None
@pytest.mark.anyio
async def test_google_login_creates_once_with_auto_nickname_and_no_real_name(google_keys):
async with client() as c:
first = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
assert first["access_token"] and first["me"]["provider"] == 2
nick = first["me"]["nickname"]
assert "홍길동" not in nick and "@" not in nick
again = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
assert again["me"]["nickname"] == nick and again["me"]["login_id"] == first["me"]["login_id"]
other = (await c.post("/v1/auth/google", json={"credential": google_keys(sub="999")})).json()
assert other["me"]["login_id"] != first["me"]["login_id"]
bad = (await c.post("/v1/auth/google", json={"credential": google_keys(aud="x")})).json()
assert bad["result"]["desc"] == "AUTH_FAILED"
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()["me"]
assert me["nickname"] == nick
@pytest.mark.anyio
async def test_config_exposes_client_id_only_when_set(monkeypatch):
async with client() as c:
monkeypatch.setattr(settings, "google_client_id", "")
assert "google_client_id" not in (await c.get("/v1/auth/config")).json()
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
assert (await c.get("/v1/auth/config")).json()["google_client_id"] == CLIENT_ID
def test_auto_nickname_fits_nickname_rule():
for _ in range(50):
assert auth_service.NICKNAME.match(auth_service.auto_nickname())
+8 -2
View File
@@ -1,6 +1,6 @@
# 이벤트 추적 (GA4) # 이벤트 추적 (GA4)
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx` (2026-10-08) 기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx`, `frontend/src/b/install.ts`, `frontend/src/b/installBanner.tsx`, `frontend/src/main.tsx` (2026-10-21)
## 한 줄 요약 ## 한 줄 요약
@@ -25,12 +25,18 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `view_gak` | 각 상세 시트가 열려 데이터가 뜸 (같은 각은 한 번만) | `index_id`, `gak_name`, `score`, `rank` | `Sheets.tsx` `GakSheet` | | `view_gak` | 각 상세 시트가 열려 데이터가 뜸 (같은 각은 한 번만) | `index_id`, `gak_name`, `score`, `rank` | `Sheets.tsx` `GakSheet` |
| `select_content` | 글 시트가 열려 데이터가 뜸 (같은 글은 한 번만) | `content_type: 'article'`, `item_id`(글 번호), `category`(분류 이름) | `Sheets.tsx` `ArticleSheet` | | `select_content` | 글 시트가 열려 데이터가 뜸 (같은 글은 한 번만) | `content_type: 'article'`, `item_id`(글 번호), `category`(분류 이름) | `Sheets.tsx` `ArticleSheet` |
| `share` | 공유창으로 보내기 성공, 또는 이미지 내려받기 | `content_type: 'image'`, `item_id`(공유 제목), `method: 'share_sheet' \| 'download'`, `ratio`(이미지 비율) | `Sheets.tsx` `ShareSheet` `send` | | `share` | 공유창으로 보내기 성공, 또는 이미지 내려받기 | `content_type: 'image'`, `item_id`(공유 제목), `method: 'share_sheet' \| 'download'`, `ratio`(이미지 비율) | `Sheets.tsx` `ShareSheet` `send` |
| `login` | 로그인 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` | | `login` | 로그인 성공 (구글로 처음 들어와 자동 가입된 경우도 `login`) | `method: 'id' \| 'google'` | `Sheets.tsx` `LoginSheet` `done` |
| `sign_up` | 가입 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` | | `sign_up` | 가입 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
| `region_change` | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` | | `region_change` | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` |
| `install_banner_view` | 오늘 탭의 '홈 화면에 추가' 카드가 보임 (설치할 수 있는 곳에서, 닫은 지 2주 안 지났으면 안 보임) | 없음 | `installBanner.tsx` `InstallBanner` |
| `install_click` | '홈 화면에 추가'를 누름 | `from: 'banner' \| 'menu'`(카드·내 정보 메뉴), `method: 'prompt' \| 'guide'`(설치창을 띄움·기기별 안내를 염) | `install.ts` `useInstall` |
| `install_choice` | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
| `install_done` | 설치 완료 (브라우저가 `appinstalled`를 줄 때만. 아이폰은 오지 않음) | 없음 | `install.ts` |
| `app_launch` | 홈 화면 아이콘(설치한 앱)으로 엶 | `mode: 'standalone'` | `main.tsx` |
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다. - 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다. - `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
- 설치는 카드 노출 → 누름 → 설치 완료 → 홈 화면 실행 순서로 본다. 아이폰은 설치 완료를 알 수 없어 `app_launch`로 대신 본다.
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다. - 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
## GA4 설정 ## GA4 설정
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+25 -4
View File
@@ -3,12 +3,33 @@
"short_name": "날씨각", "short_name": "날씨각",
"description": "오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 이번 주말 가까운 축제까지.", "description": "오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 이번 주말 가까운 축제까지.",
"lang": "ko-KR", "lang": "ko-KR",
"start_url": "/", "start_url": "/?source=homescreen",
"display": "standalone", "display": "standalone",
"background_color": "#d6ebff", "background_color": "#d6ebff",
"theme_color": "#d6ebff", "theme_color": "#d6ebff",
"icons": [ "icons": [
{ "src": "/favicon.svg", "sizes": "any", "type": "image/svg+xml" }, {
{ "src": "/apple-touch-icon.png", "sizes": "180x180", "type": "image/png" } "src": "/app/icon-192.png",
] "sizes": "192x192",
"type": "image/png"
},
{
"src": "/app/icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/app/icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/favicon.svg",
"sizes": "any",
"type": "image/svg+xml"
}
],
"id": "/",
"scope": "/"
} }
+4
View File
@@ -0,0 +1,4 @@
// 홈 화면 설치 조건을 맞추려고 둔 서비스 워커. 화면을 캐시하지 않고 네트워크로 그대로 보낸다 (옛 화면이 남지 않게)
self.addEventListener('install', () => self.skipWaiting())
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()))
self.addEventListener('fetch', () => {})
+218
View File
@@ -0,0 +1,218 @@
{
"source": "산림청·국립수목원·국립산림과학원 「2026년 한반도 단풍절정 예측지도」(2026.9.22 보도자료, 단풍나무류 지도)",
"source_url": "https://www.korea.kr/briefing/pressReleaseView.do?newsId=156782827",
"map_image_url": "https://www.korea.kr/common/download.do?fileId=198558074&tblKey=GMN",
"basis": "단풍나무류 잎의 50% 이상이 물든 때(지도 기준: 단풍나무류 단풍 50% 이상). 산별 시작일은 발표에 없어 start는 null",
"license": "공공누리 제1유형(출처표시) — 정책브리핑 게재본은 '텍스트에 한하여' 1유형, 사진·이미지는 저작권자 허락 필요(지도 이미지 자체 재사용은 확인 필요)",
"coord_source": "한국관광공사 TourAPI(KorService2 searchKeyword2) 관광지 좌표 mapy/mapx; 산마다 쓴 지점명은 coord_point(정상이 아닌 국립공원·탐방 지점일 수 있음)",
"updated": "2026-10-21",
"mountains": [
{
"name": "설악산",
"region": "강원 속초·양양·인제",
"lat": 38.119,
"lon": 128.465,
"start": null,
"peak": "2026-10-20",
"coord_point": "설악산 대청봉"
},
{
"name": "점봉산",
"region": "강원 인제·양양",
"lat": 38.036,
"lon": 128.471,
"start": null,
"peak": "2026-10-21",
"coord_point": "점봉산 곰배령"
},
{
"name": "광덕산",
"region": "강원 화천·경기 포천",
"lat": 38.115,
"lon": 127.439,
"start": null,
"peak": "2026-10-22",
"coord_point": "광덕산(화천)"
},
{
"name": "화악산",
"region": "강원 화천·경기 가평",
"lat": 38.048,
"lon": 127.522,
"start": null,
"peak": "2026-10-20",
"coord_point": "화악산"
},
{
"name": "축령산",
"region": "경기 남양주·가평",
"lat": 37.753,
"lon": 127.309,
"start": null,
"peak": "2026-10-26",
"coord_point": "축령산"
},
{
"name": "용문산",
"region": "경기 양평",
"lat": 37.551,
"lon": 127.569,
"start": null,
"peak": "2026-10-23",
"coord_point": "용문산"
},
{
"name": "수리산",
"region": "경기 군포·안양·안산",
"lat": 37.348,
"lon": 126.901,
"start": null,
"peak": "2026-11-02",
"coord_point": "수리산도립공원"
},
{
"name": "가야산(충남)",
"region": "충남 서산·예산",
"lat": 36.704,
"lon": 126.609,
"start": null,
"peak": "2026-10-31",
"coord_point": "가야산(서산)"
},
{
"name": "소백산",
"region": "충북 단양·경북 영주",
"lat": 36.935,
"lon": 128.457,
"start": null,
"peak": "2026-10-20",
"coord_point": "소백산 천문대"
},
{
"name": "속리산",
"region": "충북 보은·경북 상주",
"lat": 36.517,
"lon": 127.817,
"start": null,
"peak": "2026-10-28",
"coord_point": "속리산국립공원(충북)"
},
{
"name": "계룡산",
"region": "충남 공주·계룡, 대전",
"lat": 36.357,
"lon": 127.232,
"start": null,
"peak": "2026-11-01",
"coord_point": "계룡산국립공원"
},
{
"name": "주왕산",
"region": "경북 청송",
"lat": 36.394,
"lon": 129.142,
"start": null,
"peak": "2026-10-26",
"coord_point": "주왕산국립공원"
},
{
"name": "팔공산",
"region": "대구·경북",
"lat": 35.99,
"lon": 128.696,
"start": null,
"peak": "2026-10-30",
"coord_point": "팔공산국립공원(동화사지구)"
},
{
"name": "가야산(경북)",
"region": "경북 성주·경남 합천",
"lat": 35.8,
"lon": 128.142,
"start": null,
"peak": "2026-10-28",
"coord_point": "가야산국립공원(백운동 지구)"
},
{
"name": "금원산",
"region": "경남 거창",
"lat": 35.731,
"lon": 127.761,
"start": null,
"peak": "2026-10-25",
"coord_point": "금원산"
},
{
"name": "지리산",
"region": "경남·전남·전북",
"lat": 35.304,
"lon": 127.749,
"start": null,
"peak": "2026-10-27",
"coord_point": "지리산 천왕봉"
},
{
"name": "변산반도",
"region": "전북 부안",
"lat": 35.642,
"lon": 126.58,
"start": null,
"peak": "2026-11-04",
"coord_point": "변산반도국립공원"
},
{
"name": "내장산",
"region": "전북 정읍·전남 장성",
"lat": 35.471,
"lon": 126.867,
"start": null,
"peak": "2026-11-04",
"coord_point": "내장산국립공원"
},
{
"name": "월출산",
"region": "전남 영암·강진",
"lat": 34.775,
"lon": 126.722,
"start": null,
"peak": "2026-11-09",
"coord_point": "월출산국립공원"
},
{
"name": "두륜산",
"region": "전남 해남",
"lat": 34.49,
"lon": 126.616,
"start": null,
"peak": "2026-11-11",
"coord_point": "두륜산도립공원"
},
{
"name": "상왕봉",
"region": "전남 완도",
"lat": 34.348,
"lon": 126.693,
"start": null,
"peak": "2026-11-11",
"coord_point": "상왕산"
},
{
"name": "교래곶자왈",
"region": "제주 제주시 조천",
"lat": 33.442,
"lon": 126.667,
"start": null,
"peak": "2026-11-02",
"coord_point": "제주 교래자연휴양림"
},
{
"name": "한라산(1100도로)",
"region": "제주",
"lat": 33.358,
"lon": 126.463,
"start": null,
"peak": "2026-11-06",
"coord_point": "1100고지습지"
}
]
}
@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen'; import { client } from '../client.gen';
import { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen'; import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen'; import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AuthConfigData, AuthConfigResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
export type QueryKey<TOptions extends Options> = [ export type QueryKey<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & { Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -379,6 +379,41 @@ export const loginMutation = (options?: Partial<Options<LoginData>>): UseMutatio
return mutationOptions; return mutationOptions;
}; };
/**
* 구글 로그인 (처음이면 자동 닉네임으로 가입)
*/
export const googleLoginMutation = (options?: Partial<Options<GoogleLoginData>>): UseMutationOptions<GoogleLoginResponse, GoogleLoginError, Options<GoogleLoginData>> => {
const mutationOptions: UseMutationOptions<GoogleLoginResponse, GoogleLoginError, Options<GoogleLoginData>> = {
mutationFn: async (fnOptions) => {
const { data } = await googleLogin({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const authConfigQueryKey = (options?: Options<AuthConfigData>) => createQueryKey('authConfig', options);
/**
* 로그인 화면 설정 (구글 클라이언트 ID)
*/
export const authConfigOptions = (options?: Options<AuthConfigData>) => queryOptions<AuthConfigResponse, DefaultError, AuthConfigResponse, ReturnType<typeof authConfigQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await authConfig({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: authConfigQueryKey(options)
});
/** /**
* 토큰 재발급 * 토큰 재발급
*/ */
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts // This file is auto-generated by @hey-api/openapi-ts
export { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen'; export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakRule, type MyGakScore, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceDatLine truncated export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, Line truncated
+18 -1
View File
@@ -2,7 +2,7 @@
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client'; import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
import { client } from './client.gen'; import { client } from './client.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen'; import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & { export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/** /**
@@ -127,6 +127,23 @@ export const login = <ThrowOnError extends boolean = true>(options: Options<Logi
} }
}); });
/**
* 구글 로그인 (처음이면 자동 닉네임으로 가입)
*/
export const googleLogin = <ThrowOnError extends boolean = true>(options: Options<GoogleLoginData, ThrowOnError>): RequestResult<GoogleLoginResponses, GoogleLoginErrors, ThrowOnError> => (options.client ?? client).post<GoogleLoginResponses, GoogleLoginErrors, ThrowOnError>({
url: '/v1/auth/google',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 로그인 화면 설정 (구글 클라이언트 ID)
*/
export const authConfig = <ThrowOnError extends boolean = true>(options?: Options<AuthConfigData, ThrowOnError>): RequestResult<AuthConfigResponses, unknown, ThrowOnError> => (options?.client ?? client).get<AuthConfigResponses, unknown, ThrowOnError>({ url: '/v1/auth/config', ...options });
/** /**
* 토큰 재발급 * 토큰 재발급
*/ */
+82
View File
@@ -545,6 +545,18 @@ export type GakSlide = {
* Summary * Summary
*/ */
summary: string; summary: string;
/**
* Rows
*
* 점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)
*/
rows?: Array<Row>;
/**
* Say
*
* 점수 구간 설명 문장 (seed sentences)
*/
say?: string | null;
}; };
/** /**
@@ -1310,6 +1322,18 @@ export type ReqComment = {
body: string; body: string;
}; };
/**
* Req_Google
*/
export type ReqGoogle = {
/**
* Credential
*
* 구글 로그인 버튼이 준 ID 토큰
*/
credential: string;
};
/** /**
* Req_Login * Req_Login
*/ */
@@ -1481,6 +1505,23 @@ export type ResAuth = {
me?: Me | null; me?: Me | null;
}; };
/**
* Res_AuthConfig
*/
export type ResAuthConfig = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Google Client Id
*
* 구글 로그인 버튼에 쓸 OAuth 클라이언트 ID. 없으면 구글 로그인을 숨긴다
*/
google_client_id?: string | null;
};
/** /**
* Res_Comment * Res_Comment
*/ */
@@ -3843,6 +3884,47 @@ export type LoginResponses = {
export type LoginResponse = LoginResponses[keyof LoginResponses]; export type LoginResponse = LoginResponses[keyof LoginResponses];
export type GoogleLoginData = {
body: ReqGoogle;
path?: never;
query?: never;
url: '/v1/auth/google';
};
export type GoogleLoginErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GoogleLoginError = GoogleLoginErrors[keyof GoogleLoginErrors];
export type GoogleLoginResponses = {
/**
* Successful Response
*/
200: ResAuth;
};
export type GoogleLoginResponse = GoogleLoginResponses[keyof GoogleLoginResponses];
export type AuthConfigData = {
body?: never;
path?: never;
query?: never;
url: '/v1/auth/config';
};
export type AuthConfigResponses = {
/**
* Successful Response
*/
200: ResAuthConfig;
};
export type AuthConfigResponse = AuthConfigResponses[keyof AuthConfigResponses];
export type RefreshData = { export type RefreshData = {
body: ReqRefresh; body: ReqRefresh;
path?: never; path?: never;
+7
View File
@@ -133,6 +133,13 @@ function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSPro
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow> <Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big> <Big>{slide.line}</Big>
<Pic name={slide.code} /> <Pic name={slide.code} />
{slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>}
{/* 점수 근거: 비중 큰 조건과 지금 값. 오른쪽 아이콘과 겹치지 않게 왼쪽 반만 */}
{!!slide.rows?.length && (
<div className="relative z-[1] mt-2 w-[56%] rounded-[16px] bg-white/70 px-3 text-[14px] [&_b]:text-[15px] [&>div>div]:py-1.5 [&>div]:mt-0">
<Rows rows={slide.rows} />
</div>
)}
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b> <b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p> <p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
<Eyebrow className="mt-1">{slide.summary}</Eyebrow> <Eyebrow className="mt-1">{slide.summary}</Eyebrow>
+21 -9
View File
@@ -20,11 +20,14 @@ import {
unlikeCommentMutation, unlikeCommentMutation,
updateMeMutation, updateMeMutation,
} from '../api/client/@tanstack/react-query.gen' } from '../api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen' import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.gen'
import { track } from '../lib/analytics' import { track } from '../lib/analytics'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib' import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { MixSheet } from './myGak' import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext' import { ownPage, useRegion } from './regionContext'
import { useSky } from './skyContext' import { useSky } from './skyContext'
@@ -73,7 +76,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
) )
} }
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */ /** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) { function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -134,6 +137,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'me' && <MeSheet onDone={onClose} />} {state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />} {state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />} {state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />}
</div> </div>
)} )}
{!state && <RegionLinks />} {!state && <RegionLinks />}
@@ -808,13 +812,13 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
const signup = useMutation(signupMutation()) const signup = useMutation(signupMutation())
const pending = login.isPending || signup.isPending const pending = login.isPending || signup.isPending
const done = (res: ResAuth) => { const done = (res: ResAuth, method: 'id' | 'google' = 'id') => {
if (!res.result?.success || !res.access_token) { if (!res.result?.success || !res.access_token) {
setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.') setError(method === 'google' ? '구글로 로그인하지 못했어요. 다시 해 주세요.' : (AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.'))
return return
} }
setTokens(res.access_token, res.refresh_token ?? null) setTokens(res.access_token, res.refresh_token ?? null)
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' }) track(method === 'google' ? 'login' : mode === 'login' ? 'login' : 'sign_up', { method })
onLoggedIn() onLoggedIn()
} }
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.') const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
@@ -822,8 +826,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
const submit = (e: FormEvent) => { const submit = (e: FormEvent) => {
e.preventDefault() e.preventDefault()
setError('') setError('')
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail }) if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: (res) => done(res), onError: fail })
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail }) else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: (res) => done(res), onError: fail })
} }
if (me) return <MeSheet onDone={onDone} /> if (me) return <MeSheet onDone={onDone} />
@@ -832,7 +836,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
return ( return (
<Body> <Body>
<form onSubmit={submit} className="flex flex-col gap-2.5"> <form onSubmit={submit} className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</p> <p className="text-center text-sm font-semibold text-(--ink2)">글쓰기·댓글은 로그인한 뒤에 할 수 있어요.</p>
<GoogleButton onResult={(res) => done(res, 'google')} onFail={fail} />
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입"> <div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
{( {(
[ [
@@ -864,6 +869,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */ /* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
function MeSheet({ onDone }: { onDone: () => void }) { function MeSheet({ onDone }: { onDone: () => void }) {
const install = useInstall()
const installable = useInstallable()
const { me, logout } = useAuth() const { me, logout } = useAuth()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const update = useMutation(updateMeMutation()) const update = useMutation(updateMeMutation())
@@ -897,8 +904,13 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<Body className="flex flex-col gap-3"> <Body className="flex flex-col gap-3">
<div className="flex flex-col items-center gap-1.5"> <div className="flex flex-col items-center gap-1.5">
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} /> <Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.login_id}(으)로 로그인했어요</p> <p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
</div> </div>
{installable && (
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
📲 홈 화면에 추가
</button>
)}
<section aria-label="내 캐릭터"> <section aria-label="내 캐릭터">
<h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4> <h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4>
<div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="캐릭터 고르기"> <div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="캐릭터 고르기">
+4
View File
@@ -5,6 +5,8 @@ import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TalkData, type TopIndex, type WeatherSlot } from '../api/client/types.gen' import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TalkData, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib' import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MyGakRow } from './myGak' import { MyGakRow } from './myGak'
import { fromShare } from './myGakState' import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post' import { PostCard, PostCardSkel, PostFrame } from './Post'
@@ -400,6 +402,7 @@ export function TodayPage() {
) : ( ) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" /> <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
)} )}
<InstallBanner />
<div> <div>
{load === 'loading' && <PostsSkel />} {load === 'loading' && <PostsSkel />}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */} {/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
@@ -409,6 +412,7 @@ export function TodayPage() {
{posts.map((p, i) => ( {posts.map((p, i) => (
<Fragment key={p.post_id}> <Fragment key={p.post_id}>
<PostCard post={p} /> <PostCard post={p} />
{i === 1 && <FoliageCard />}
{(i + 1) % 3 === 0 && talks[(i + 1) / 3 - 1] && <TalkCard t={talks[(i + 1) / 3 - 1]} />} {(i + 1) % 3 === 0 && talks[(i + 1) / 3 - 1] && <TalkCard t={talks[(i + 1) / 3 - 1]} />}
{bandAt.find(([at]) => at === i + 1)?.[1]} {bandAt.find(([at]) => at === i + 1)?.[1]}
</Fragment> </Fragment>
+95
View File
@@ -0,0 +1,95 @@
import { useState } from 'react'
import data from '../../seo/foliage_2026.json'
import { cx } from '../lib/utils'
import { kst } from './lib'
import { PostFrame } from './Post'
type Mountain = { name: string; region: string; lat: number; lon: number; peak: string }
type Stage = 'peak' | 'soon' | 'before' | 'after'
// 지도 그림(public/foliage/korea-map.webp, 1024×1536)의 위경도 → 그림 위 위치. generated-images/foliage-map/korea_outline.json 과 같은 값
const MAP = { lon0: 124.0, lon1: 132.2, lat0: 33.0, lat1: 43.1, w: 900, h: 1407, scale: 1.09168, ox: 20.74, cw: 1024, ch: 1536 }
const PEAK_DAYS = 3 // 절정일 앞뒤 이만큼은 '지금 절정'
const SOON_DAYS = 7
const SEASON = { from: '09-20', to: '11-25' }
const SEOUL = { lat: 37.566, lon: 126.978 }
const STAGE: Record<Stage, { label: string; dot: string }> = {
peak: { label: '지금 절정', dot: 'bg-[#ff5a36]' },
soon: { label: '곧 절정', dot: 'bg-[#ffb02e]' },
before: { label: '아직', dot: 'bg-[#7cc47a]' },
after: { label: '절정 지남', dot: 'bg-[#b9a69a]' },
}
const pos = (m: Mountain) => ({
left: `${((MAP.ox + ((m.lon - MAP.lon0) / (MAP.lon1 - MAP.lon0)) * MAP.w * MAP.scale) / MAP.cw) * 100}%`,
top: `${((((MAP.lat1 - m.lat) / (MAP.lat1 - MAP.lat0)) * MAP.h * MAP.scale) / MAP.ch) * 100}%`,
})
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(m: Mountain, today: string): Stage {
const d = days(today, m.peak)
if (Math.abs(d) <= PEAK_DAYS) return 'peak'
if (d < 0) return 'after'
return d <= SOON_DAYS ? 'soon' : 'before'
}
const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
/** 단풍철에만 나오는 단풍 지도 카드. 산마다 절정 예측일로 지금 절정·곧·아직·지남을 점으로 */
export function FoliageCard() {
const [now] = useState(() => new Date())
const t = kst(now)
const today = `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
const [picked, setPicked] = useState<string | null>(null)
const mmdd = today.slice(5)
if (mmdd < SEASON.from || mmdd > SEASON.to) return null
const mountains = (data.mountains as unknown as Mountain[]).map((m) => ({ ...m, stage: stage(m, today) }))
const peakNow = mountains.filter((m) => m.stage === 'peak').map((m) => m.name)
// 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 산으로
const seoul = mountains.reduce((a, b) => (Math.hypot(b.lat - SEOUL.lat, b.lon - SEOUL.lon) < Math.hypot(a.lat - SEOUL.lat, a.lon - SEOUL.lon) ? b : a))
const sel = mountains.find((m) => m.name === picked)
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peakNow.length ? `지금 절정: ${peakNow.join(' · ')}` : undefined}>
<div className="relative bg-[#e6f2ff] px-4 pt-4 pb-3">
<p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">서울 근교 {seoul.name} 절정 예상 {md(seoul.peak)}</p>
<div className="relative mx-auto mt-2 aspect-[2/3] w-[86%]">
<img src="/foliage/korea-map.webp" alt="한반도 지도" className="absolute inset-0 size-full" />
{mountains.map((m) => (
<button
key={m.name}
type="button"
onClick={() => setPicked(m.name === picked ? null : m.name)}
aria-label={`${m.name} ${STAGE[m.stage].label}, 절정 예상 ${md(m.peak)}`}
className="absolute -translate-x-1/2 -translate-y-1/2 cursor-pointer p-1.5"
style={pos(m)}
>
<i className={cx('block size-3.5 rounded-full border-2 border-white shadow-[0_1px_4px_rgb(40_48_74/0.35)]', STAGE[m.stage].dot, m.name === picked && 'size-5')} />
</button>
))}
{sel && (
<p className="absolute right-0 bottom-0 m-0 rounded-[14px] bg-white/90 px-3 py-2 text-[13px] font-bold shadow-[0_4px_12px_rgb(40_48_74/0.15)]">
<b className="font-jua text-[16px] font-normal">{sel.name}</b> {sel.region}
<br />
{STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)}
</p>
)}
</div>
<div className="mt-2 flex flex-wrap justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
{(Object.keys(STAGE) as Stage[]).map((s) => (
<span key={s} className="flex items-center gap-1">
<i className={cx('size-2.5 rounded-full', STAGE[s].dot)} />
{STAGE[s].label}
</span>
))}
</div>
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 단풍나무 잎 절반이 물든 때 기준
</p>
</div>
</PostFrame>
)
}
+83
View File
@@ -0,0 +1,83 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '../api/client/@tanstack/react-query.gen'
import type { ResAuth } from '../api/client/types.gen'
type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id
const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false)
const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail })
useEffect(() => {
cb.current = { onResult, onFail }
}, [onResult, onFail])
useEffect(() => {
if (!clientId || !box.current) return
let alive = true
loadGoogle().then(
(g) => {
if (!alive || !box.current) return
g.initialize({
client_id: clientId,
ux_mode: 'popup',
callback: (r) => {
if (!r.credential) return cb.current.onFail()
mutate({ body: { credential: r.credential } }, { onSuccess: (res) => cb.current.onResult(res), onError: () => cb.current.onFail() })
},
})
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
},
(e: unknown) => {
console.error('[google] script', e)
if (alive) setBroken(true)
},
)
return () => {
alive = false
}
}, [clientId, mutate])
if (!clientId) return null
return (
<div className="flex flex-col gap-2">
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 아이디로 로그인해 주세요.</p>}
<p className="m-0 flex items-center gap-2 text-[12.5px] font-bold text-(--ink3) before:h-px before:flex-1 before:bg-(--line) after:h-px after:flex-1 after:bg-(--line)">또는 아이디로</p>
</div>
)
}
+98
View File
@@ -0,0 +1,98 @@
import { useSyncExternalStore } from 'react'
import { track } from '../lib/analytics'
import { useSheet } from './sheetContext'
type InstallPromptEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> }
const DISMISS_KEY = 'nalssigak.b.installDismissed'
const DISMISS_DAYS = 14
// 안드로이드 Chrome 은 설치할 수 있을 때 이 이벤트를 한 번 준다. 앱이 뜨기 전에 올 수 있어 모듈을 불러올 때 바로 받아 둔다
let deferred: InstallPromptEvent | null = null
const listeners = new Set<() => void>()
const notify = () => listeners.forEach((cb) => cb())
if (typeof window !== 'undefined') {
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault()
deferred = e as InstallPromptEvent
notify()
})
window.addEventListener('appinstalled', () => {
deferred = null
track('install_done', {})
notify()
})
}
export type Platform = 'standalone' | 'inapp' | 'ios' | 'android' | 'other'
/** 지금 이 기기에서 홈 화면 추가를 어떻게 안내할지 */
export function platform(): Platform {
const ua = navigator.userAgent
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) return 'standalone'
if (/KAKAOTALK|Instagram|FBAN|FBAV|NAVER\(inapp|; wv\)|Line\//i.test(ua)) return 'inapp'
if (/iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return 'ios'
if (/Android/.test(ua)) return 'android'
return 'other'
}
const onPhone = () => ['ios', 'android', 'inapp'].includes(platform())
/** 설치를 권할 곳: 휴대폰 브라우저, 그리고 설치창을 띄울 수 있는 PC 브라우저(Chrome·Edge). PC Safari·Firefox 와 이미 설치해 연 화면은 뺀다 */
export function useInstallable() {
const canPrompt = useCanPrompt()
return platform() !== 'standalone' && (onPhone() || canPrompt)
}
/** 설치창을 바로 띄울 수 있는지 (안드로이드 Chrome 등) */
export function useCanPrompt() {
return useSyncExternalStore(
(cb) => {
listeners.add(cb)
return () => listeners.delete(cb)
},
() => deferred != null,
)
}
/** 설치창을 띄운다. 띄웠으면 true */
export async function promptInstall(): Promise<boolean> {
if (!deferred) return false
const e = deferred
deferred = null
notify()
await e.prompt()
const { outcome } = await e.userChoice
track('install_choice', { outcome })
return true
}
export function dismissed(): boolean {
try {
const at = Number(localStorage.getItem(DISMISS_KEY))
return at > 0 && Date.now() - at < DISMISS_DAYS * 86_400_000
} catch {
// 저장소를 못 쓰는 브라우저에선 이번 방문 동안만 보인다
return false
}
}
export function dismiss() {
try {
localStorage.setItem(DISMISS_KEY, String(Date.now()))
} catch (e) {
console.warn('[install] 닫은 시각을 저장하지 못함', e)
}
}
/** 홈 화면에 추가: 설치창을 띄울 수 있으면 띄우고, 아니면 기기별 안내 창을 연다 */
export function useInstall() {
const { open } = useSheet()
const canPrompt = useCanPrompt()
return async (from: 'banner' | 'menu') => {
const shown = canPrompt && (await promptInstall())
track('install_click', { from, method: shown ? 'prompt' : 'guide' })
if (!shown) open({ type: 'install' })
}
}
+105
View File
@@ -0,0 +1,105 @@
import { useEffect, useState } from 'react'
import { track } from '../lib/analytics'
import { dismiss, dismissed, platform, useInstall, useInstallable } from './install'
const SITE = 'https://weather.o2o.kr'
/** 오늘 탭의 작은 설치 카드. 오늘의 각까지 본 뒤 자리에 놓고, 설치할 수 있는 곳(휴대폰, PC Chrome·Edge)에서만 보인다. 닫으면 2주 숨긴다 */
export function InstallBanner() {
const install = useInstall()
const installable = useInstallable()
const [closed, setClosed] = useState(dismissed)
const hidden = !installable || closed
useEffect(() => {
if (!hidden) track('install_banner_view', {})
}, [hidden])
if (hidden) return null
return (
<aside aria-label="홈 화면에 추가" className="mx-3 mt-3.5 flex items-center gap-3 rounded-[22px] bg-white p-3.5 shadow-[inset_0_-5px_0_var(--shade)]">
<img src="/app/icon-192.png" alt="" className="size-12 shrink-0 rounded-[14px]" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16.5px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
<p className="m-0 mt-0.5 text-[12.5px] font-semibold text-(--ink2)">날씨각을 홈 화면에 추가하고 한 번에 열어보세요.</p>
<div className="mt-2 flex gap-1.5">
<button type="button" onClick={() => install('banner')} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
📲 홈 화면에 추가
</button>
<button
type="button"
onClick={() => {
dismiss()
setClosed(true)
}}
className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2)"
>
닫기
</button>
</div>
</div>
</aside>
)
}
function Steps({ items }: { items: string[] }) {
return (
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{items.map((t, i) => (
<li key={t} className="flex items-start gap-2.5 rounded-2xl bg-[#f3f6fb] px-3.5 py-3 text-[14.5px] font-bold">
<b className="grid size-6 shrink-0 place-items-center rounded-full bg-(--orange) font-jua text-[14px] font-normal text-white">{i + 1}</b>
<span>{t}</span>
</li>
))}
</ol>
)
}
/** 설치창을 띄울 수 없는 기기의 안내 */
export function InstallSheet() {
const p = platform()
const [copied, setCopied] = useState(false)
const copy = () =>
navigator.clipboard.writeText(SITE).then(
() => setCopied(true),
(e: unknown) => console.error('[install] copy', e),
)
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{p === 'standalone' && <p className="m-0 text-[15px] font-bold">이미 홈 화면에서 열었어요. 다음에도 아이콘을 눌러 바로 여세요.</p>}
{p === 'ios' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">아이폰은 Safari에서 이렇게 추가해요.</p>
<Steps items={['아래쪽 가운데 공유 버튼(네모에 위쪽 화살표)을 눌러요', "목록을 올려 '홈 화면에 추가'를 눌러요", "오른쪽 위 '추가'를 누르면 끝이에요"]} />
</>
)}
{p === 'android' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">지금 브라우저에선 설치창을 바로 띄울 수 없어요. 메뉴에서 추가해 주세요.</p>
<Steps items={['오른쪽 위 ⋮ 메뉴를 눌러요', "'홈 화면에 추가' 또는 '앱 설치'를 눌러요", "'추가' 또는 '설치'를 누르면 끝이에요"]} />
</>
)}
{p === 'inapp' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">카카오톡 같은 앱 안에서는 홈 화면에 추가할 수 없어요. Safari나 Chrome에서 열어 주세요.</p>
<Steps items={["오른쪽 위 ⋮ 또는 공유 버튼에서 '다른 브라우저로 열기'를 눌러요", '안 보이면 아래 주소를 복사해 Safari·Chrome에 붙여 넣어요', "열린 화면에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{p === 'other' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">휴대폰에서 열면 홈 화면에 추가할 수 있어요.</p>
<Steps items={['휴대폰 Safari(아이폰)나 Chrome(갤럭시)에서 아래 주소를 열어요', "공유 버튼이나 ⋮ 메뉴에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{(p === 'inapp' || p === 'other') && (
<div className="mt-3 flex items-center gap-2 rounded-2xl border border-(--line) px-3.5 py-2.5">
<span className="min-w-0 flex-1 truncate text-[14.5px] font-bold select-all">{SITE}</span>
<button type="button" onClick={copy} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied ? '복사함' : '주소 복사'}
</button>
</div>
)}
</div>
)
}
+1
View File
@@ -14,6 +14,7 @@ export type SheetState =
| { type: 'me' } | { type: 'me' }
| { type: 'region' } | { type: 'region' }
| { type: 'mix'; shared?: MyGak } | { type: 'mix'; shared?: MyGak }
| { type: 'install' }
| null | null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void } export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
+6 -1
View File
@@ -3,9 +3,14 @@ type Events = {
view_gak: { index_id: number; gak_name: string; score: number; rank: number } view_gak: { index_id: number; gak_name: string; score: number; rank: number }
select_content: { content_type: 'article'; item_id: number; category: string } select_content: { content_type: 'article'; item_id: number; category: string }
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string } share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
login: { method: 'id' } login: { method: 'id' | 'google' }
sign_up: { method: 'id' } sign_up: { method: 'id' }
region_change: { region_name: string; method: 'list' | 'location' } region_change: { region_name: string; method: 'list' | 'location' }
install_banner_view: Record<string, never>
install_click: { from: 'banner' | 'menu'; method: 'prompt' | 'guide' }
install_choice: { outcome: 'accepted' | 'dismissed' }
install_done: Record<string, never>
app_launch: { mode: 'standalone' }
} }
declare global { declare global {
+8
View File
@@ -4,6 +4,8 @@ import { createRoot } from 'react-dom/client'
import './index.css' import './index.css'
import './api/setup' import './api/setup'
import App from './App.tsx' import App from './App.tsx'
import './b/install'
import { track } from './lib/analytics'
// iOS는 user-scalable=no를 무시해서 두 손가락 확대를 직접 막는다 // iOS는 user-scalable=no를 무시해서 두 손가락 확대를 직접 막는다
for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false }) for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false })
@@ -13,6 +15,12 @@ const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } }, defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } },
}) })
// 홈 화면 설치 조건(서비스 워커)과, 홈 화면 아이콘으로 연 횟수
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch((e: unknown) => console.error('[sw] register', e))
}
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) track('app_launch', { mode: 'standalone' })
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>