Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdf8498a56 | ||
|
|
a646d1b26a | ||
|
|
7f2cbc13c9 | ||
|
|
ea5376820c | ||
|
|
e180d9651c | ||
|
|
7dcb40df78 | ||
|
|
07290597a0 | ||
|
|
7451599727 |
No files matched your search
@@ -23,6 +23,13 @@ PORT=9810
|
||||
JWT_ACCESS_SECRET=
|
||||
JWT_REFRESH_SECRET=
|
||||
|
||||
# ── 백엔드: 앱인토스 토스 로그인. 인증서·키는 저장소 최상위 secrets/toss/ 에 두고(커밋 안 함) 컨테이너 안 경로를 적는다
|
||||
# compose 는 secrets/toss 를 backend 의 /run/secrets/toss 에 읽기 전용으로 붙인다
|
||||
TOSS_MTLS_CERT=/run/secrets/toss/nalssigak_public.crt
|
||||
TOSS_MTLS_KEY=/run/secrets/toss/nalssigak_private.key
|
||||
# 연결 끊기 콜백 Basic Auth "아이디:비밀번호" — 콘솔에 넣은 값과 같게. 비우면 콜백을 모두 거절한다
|
||||
TOSS_UNLINK_AUTH=
|
||||
|
||||
# ── 배포(compose): 비우면 로컬 기본값. 킹서버 예: FRONT_PORT=30040, API_BIND=127.0.0.1:9810, PG_BIND=127.0.0.1:5440, REDIS_BIND=127.0.0.1:6390
|
||||
FRONT_PORT=
|
||||
API_BIND=
|
||||
|
||||
+6
-1
@@ -22,4 +22,9 @@ backend/openapi.json
|
||||
# 디자인 도구(impeccable) 캐시
|
||||
.impeccable/
|
||||
|
||||
/zzz
|
||||
/zzz
|
||||
# 인증서·키: 서버와 각자 PC 에만 둔다 (토스 mTLS 등)
|
||||
secrets/
|
||||
*.pem
|
||||
*.key
|
||||
*.crt
|
||||
@@ -147,6 +147,15 @@
|
||||
| [x] | 좋아요·댓글이 전국 공통 — 포스트가 (날짜, 자리) 하나로 전국에 하나뿐이라, 구마다 내용이 다른 카드(오늘 날씨·각 1~3위·노을·미세먼지·행사)도 댓글·좋아요를 전국이 같이 씀. 예: 강남의 "1위 산책각"과 부산의 "1위 빨래각"이 같은 댓글창. 안: 지역 데이터 카드만 시도(17) 단위로 나누고 계절·상식·명언은 전국 공통 유지 | 사용자 질문 (10/8) | `backend/postgres-init/init.sql` (`uq_post_feed`), `backend/services/feed_service.py` (`build_day`, `_gak`) |
|
||||
| [ ] | **[결정 필요]** 포스트 시도 단위가 17이 아니라 16 — `region.code` 앞 2자리에서 광주·전남이 둘 다 `12`(전남광주통합특별시)라 같은 댓글창을 씀. 그대로 둘지, 이름 앞머리로 광주·전남을 나눌지 | 포스트 시도 나누기 (10/8) | `backend/services/feed_service.py` (`sido_of`), `backend/seed/region.csv` |
|
||||
| [ ] | 광주·전남 구는 행사가 안 잡힐 수 있음 — 구 코드 시도는 `12`인데 행사 수집·`event.sido_code`는 `29`(광주)·`46`(전남). 좌표 없는 행사는 `is_nearby`·`nearby_sidos`에서 빠짐 | 포스트 시도 나누기 중 발견 (10/8) | `backend/services/week_service.py:125,144`, `backend/services/external/culture_api.py:28` |
|
||||
| [ ] | **[결정 필요]** 앱인토스 입점 여부 — 검토안은 "웹 출시 후 보기 전용 토스판으로 시험, 첫 달 포인트·알림 20~30만 원, 5주차에 포인트 없는 주의 7일 재방문율 20%를 기준으로 계속/중단" (https://claude.ai/artifact/QgA7iq3CCesTRYcFyZck71) | 앱인토스 검토 | |
|
||||
| [ ] | **[결정 필요]** 토스판 광고 — 앱인토스 수익은 토스 광고·인앱결제뿐인데 웹은 '광고 없음'으로 정함. 안 붙이면 토스판은 비용만 드는 홍보 채널 | 앱인토스 검토 | |
|
||||
| [ ] | 앱인토스 사전 확인 — 시간대별 밤 배경이 '라이트 모드' 규칙에 걸리는지, 네이버 지도 링크가 '단순 정보 확인' 예외인지 채널톡 문의 | 앱인토스 검토 | `frontend/src/b/BLayout.tsx`, `frontend/src/b/ui.tsx` |
|
||||
| [ ] | **[결정 필요]** 각 34개 정리 — 계절 밖 각(10월 물놀이·냉면) 노출 막기(각별 '보여 줄 달'), 나쁜 일 예고 각(택시대란·배달폭주·김서림·화장붕괴)을 순위에서 빼고 '조심' 카드로, 날씨 관계 약한 재미 각(공부·넷플릭스·짬뽕·막걸리·뜨아·군밤·집콕) 축소 또는 '재미' 표시 (https://claude.ai/artifact/4WgpUjdNqdSNnMN4ASB4BB) | 토스판 전략 검토 | `backend/seed/index_definition.json`, `backend/services/index_service.py` |
|
||||
| [ ] | 글 재고 부족 — 25편(한 문장 8·시 3·상식 4·계절 9)이라 매일 보면 1~2주 안에 반복, 계절 글은 10월분뿐. 기획의 'AI 주 1회 생성'이 스케줄러에 없음. 8주치 재고 또는 생성·검토 파이프라인 | 토스판 전략 검토 | `backend/seed/article.json`, `backend/scheduler/jobs.py` |
|
||||
| [ ] | **[결정 필요]** 노을 알림 재검토 — 10/2에 제외했지만 토스 알림은 정보성만 허용돼 "오늘 노을 좋음"이 가장 맞는 알림. 토스판 핵심 후보 | 토스판 전략 검토 | |
|
||||
| [ ] | **[결정 필요]** 히어로 숫자 5개(기온·체감·불쾌지수·날씨 점수·1위 각 점수) — 불쾌지수 여름만, 날씨 점수 유지 여부 | 토스판 전략 검토 | `frontend/src/b/TodayPage.tsx` |
|
||||
| [x] | 토스판 방식 — WebView로 결정(10/12). 별도 프로젝트 없이 `frontend/`에 토스 빌드 모드 추가, RN은 독립 앱만 | 토스판 전략 검토 | `frontend/` |
|
||||
| [x] | 앱인토스 appName 정식 이름으로 교체 — 콘솔 앱 `nalssigak`으로 맞춤(10/13). 정식 앱 등록 후 두 곳을 같이 바꾸고 `npm run build:toss` 다시 실행 | 콘솔 테스트 앱으로 먼저 등록 | `frontend/apps-in-toss.config.ts`, `frontend/src/lib/platform.ts` |
|
||||
| [x] | 전체 날씨 점수 기준 강화 — 100점은 '1년에 하루' 수준으로만 → 각과 같은 계산에 기준만 좁힘(체감 21±0.5°·습도 45~55%·해 90%↑·바람 1m/s↓·초미세먼지 10↓, 사용자 결정 '기준만 좁히기'). 실제 연 몇 번 나오는지는 미확인 (`docs/점수_계산식.md` 3) | 10/8 회의 결정 | `backend/services/index_service.py:203` |
|
||||
| [x] | 각 점수를 아침·낮·저녁·밤 시간대별로 → 지금 구간 점수로 순위, 안 겹치는 각은 순위·피드에서 빼고 스토리·전체엔 '지금 아님'. 히어로는 '지금 날씨 점수'(지금 구간). 운영 DB에 `index_score.slots` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 10/8 회의 결정 | `backend/services/calc/index_calc.py:297` |
|
||||
| [x] | 히어로에 습도·불쾌지수 항상 표시 → 4칸(지금·습도·불쾌지수·상황 1칸, 사용자 결정). 불쾌지수 75 이상이면 경고 색, 상황 칸 후보에서 불쾌지수 뺌 | 10/8 회의 결정 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
|
||||
@@ -158,3 +167,8 @@
|
||||
| [ ] | **[결정 필요]** 각 순위가 점수 순이 아니라 보임 — 순위가 점수 × 중요도라 환기각 92점(하)이 5위, 골프각 89점이 3위, 빨래각 83점이 2위. 각 탭 받침대·스토리에서 높은 점수가 뒤에 있어 어색함. 점수를 순위대로 보여줄지, 중요도 가중을 줄일지 | 화면 직접 확인 중 발견 (10/12) | `backend/services/calc/index_calc.py` (`PRIORITY_WEIGHT`), `frontend/src/b/GakPage.tsx` |
|
||||
| [x] | 노을 점수 29점(잿빛)인데 결론 '나가 볼 만해요' — 결론이 구름 분포만 보고 공기 보정(가시거리·습도)을 안 봤음 → 공기 보정 0.7배 미만이면 결론 한 단계 낮추고 이유에 공기 표시, '해 질 무렵(N시) 예보 기준' 표시. 운영 DB에 `sky_score.air` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 사용자 지적 (10/12, 분당구) | `backend/services/sky_service.py` (`day_verdict`, `build_plan`), `backend/services/calc/sky_score.py` (`air_note`) |
|
||||
| [x] | 노을 탭 다시 짜기 → 시안 A(사용자 선택): 히어로 '오늘은 애매해요 / 18:10쯤 가장 붉어요 / 쉬운 이유', 내일 안내 바로 아래, 숫자는 '자세히', 시간표에 가장 붉을 때 — 처음 보면 '그래서 가?'에서 멈춤: 히어로 18:00이 무슨 시각인지 없음, 결론 카드가 좋은 말·나쁜 말을 섞음, 구름 %·예보 모델 수 같은 전문 용어, '가장 붉을 때'가 시간표에 없음, '내일이 더 나아요'가 맨 아래. 시안 먼저 보고 결정 | 사용자 지적 (10/12) | `frontend/src/b/SkyPage.tsx`, `backend/services/calc/sky_score.py` (`reason`) |
|
||||
| [ ] | 토스 로그인 운영 설정 — 서버 `secrets/toss/` 인증서·키, `.env` `TOSS_*` 세 줄은 넣음(10/14). 남은 것: 정산정보 등록(대표님), 배포, 콘솔 약관 링크·콜백, `4050 인증서버에 등록된 미니앱이 아닙니다` 재확인 | 토스 로그인 구현(10/14) | `compose.yaml`, `.env.example`, `backend/config/settings.py` |
|
||||
| [ ] | 토스 번들 다시 만들기 — 로그인(4050) 풀린 뒤 `npm run build:toss`로 한 번에. 지금 콘솔 번들엔 로그인·GA `platform` 값이 없음. 로그인 실패 상태로 검수 올리면 반려 위험 | 로그인 미완성이라 미룸(10/14) | `frontend/` |
|
||||
| [ ] | **[결정 필요]** 토스 연결 끊기 처리 — 지금은 UNLINK·탈퇴 모두 토큰만 무효로 함. 토스 탈퇴(`WITHDRAWAL_TOSS`·`WITHDRAWAL_TERMS`) 때 계정·댓글을 지울지 | 토스 로그인 구현(10/14) | `backend/services/auth_service.py` |
|
||||
| [ ] | 토스 로그인 문구 검토 — '토스로 로그인', '토스로 로그인했어요', '토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.', 기본 닉네임 '토스1234'(userKey 끝 4자리) | 토스 로그인 구현(10/14) | `frontend/src/b/Sheets.tsx`, `backend/services/auth_service.py` |
|
||||
| [ ] | 댓글 신고·차단 — 앱인토스 필수 아님(신고·차단 필수는 채팅·만남·중고거래만, 서비스 오픈 정책·서비스별 주의사항). 만들지 않기로 함(10/14). 검수에서 요청이 오면 만든다 | 토스 로그인 구현(10/14) | |
|
||||
@@ -159,3 +159,4 @@ class RefType(CodeEnum):
|
||||
class AuthProvider(CodeEnum):
|
||||
LOCAL = 1
|
||||
GOOGLE = 2
|
||||
TOSS = 3
|
||||
@@ -31,14 +31,18 @@ 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
|
||||
jwt_refresh_days: int = 30
|
||||
|
||||
# 앱인토스 토스 로그인. 인증서·키는 저장소 밖(secrets/toss)에 두고 경로만 받는다
|
||||
toss_api_base: str = "https://apps-in-toss-api.toss.im"
|
||||
toss_mtls_cert: str = ""
|
||||
toss_mtls_key: str = ""
|
||||
# 연결 끊기 콜백의 Basic Auth 값 "아이디:비밀번호". 콘솔에 넣은 값과 같아야 한다
|
||||
toss_unlink_auth: str = ""
|
||||
|
||||
@field_validator("data_go_kr_service_key")
|
||||
@classmethod
|
||||
def _decode_service_key(cls, v: str) -> str:
|
||||
|
||||
@@ -12,6 +12,9 @@ class UserCRUD:
|
||||
async def by_login_id(self, s: AsyncSession, login_id: str) -> Optional[User]:
|
||||
return await s.scalar(select(User).where(User.login_id == login_id, User.deleted.is_(False)))
|
||||
|
||||
async def by_provider_uid(self, s: AsyncSession, provider: int, provider_uid: str) -> Optional[User]:
|
||||
return await s.scalar(select(User).where(User.provider == provider, User.provider_uid == provider_uid, User.deleted.is_(False)))
|
||||
|
||||
async def get(self, s: AsyncSession, user_id: uuid.UUID) -> Optional[User]:
|
||||
user = await s.get(User, user_id)
|
||||
return user if user is not None and not user.deleted else None
|
||||
@@ -22,6 +25,12 @@ class UserCRUD:
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def create_social(self, s: AsyncSession, provider: int, provider_uid: str, login_id: str, nickname: str) -> User:
|
||||
user = User(login_id=login_id, password=None, provider_uid=provider_uid, nickname=nickname, provider=provider)
|
||||
s.add(user)
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def update(self, s: AsyncSession, user_id: uuid.UUID, values: dict) -> Optional[User]:
|
||||
user = await self.get(s, user_id)
|
||||
if user is None:
|
||||
|
||||
@@ -184,13 +184,13 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed_scope ON public.post (feed_date,
|
||||
|
||||
-- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나)
|
||||
|
||||
-- 사용자. 일반(아이디·비밀번호) 또는 구글 로그인. 이름·전화번호는 받지 않는다.
|
||||
-- 사용자. 일반(아이디·비밀번호), 구글, 토스(앱인토스) 로그인. 이름·전화번호는 받지 않는다.
|
||||
CREATE TABLE IF NOT EXISTS public.users (
|
||||
user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글
|
||||
login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_<sub>
|
||||
provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글 3=토스
|
||||
login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_<sub>, 토스는 toss_<userKey>
|
||||
password VARCHAR(255) NULL, -- bcrypt 해시. 구글 계정은 NULL
|
||||
provider_uid VARCHAR(255) NULL, -- 구글 sub. 일반 계정은 NULL
|
||||
provider_uid VARCHAR(255) NULL, -- 구글 sub 또는 토스 userKey. 일반 계정은 NULL
|
||||
nickname VARCHAR(30) NOT NULL, -- 댓글에 보이는 이름
|
||||
character VARCHAR(20) NOT NULL DEFAULT 'rabbit', -- 프로필 캐릭터: rabbit·bear·dog·sun·moon·cloud
|
||||
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
||||
@@ -203,6 +203,7 @@ CREATE TABLE IF NOT EXISTS public.users (
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_login_id ON public.users (login_id) WHERE deleted = FALSE;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_google ON public.users (provider_uid) WHERE provider = 2 AND deleted = FALSE;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_toss ON public.users (provider_uid) WHERE provider = 3 AND deleted = FALSE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.post_like (
|
||||
post_id BIGINT NOT NULL,
|
||||
|
||||
@@ -14,7 +14,6 @@ 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
|
||||
@@ -44,7 +43,6 @@ 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):
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
import base64
|
||||
import binascii
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
|
||||
from common.auth import current_user
|
||||
from common.database.model.models import User
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.logger import LOG
|
||||
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_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me, Res_TossUnlink
|
||||
from services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
@@ -33,6 +40,32 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.post("/toss", response_model=Res_Auth, response_model_exclude_none=True, summary="토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)")
|
||||
async def toss(req: Req_TossLogin, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.toss_login(req.authorization_code, req.referrer)
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
def _check_toss_basic(authorization: Optional[str]) -> None:
|
||||
"""콘솔에 넣은 "아이디:비밀번호" 와 같은지 본다. 값이 비어 있으면 모두 거절한다."""
|
||||
given = ""
|
||||
if authorization and authorization.startswith("Basic "):
|
||||
try:
|
||||
given = base64.b64decode(authorization.removeprefix("Basic "), validate=True).decode()
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
given = ""
|
||||
if not settings.toss_unlink_auth or not secrets.compare_digest(given.encode(), settings.toss_unlink_auth.encode()):
|
||||
raise HTTPException(status_code=401, detail=ErrorType.AUTH_FAILED.name)
|
||||
|
||||
|
||||
@router.post("/toss/unlink", response_model=Res_TossUnlink, response_model_exclude_none=True, summary="토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름)")
|
||||
async def toss_unlink(req: Req_TossUnlink, authorization: Optional[str] = Header(None), service: AuthService = Depends()) -> Res_TossUnlink:
|
||||
_check_toss_basic(authorization)
|
||||
LOG.info(f"[auth] toss unlink: {req.referrer}")
|
||||
err = await service.toss_unlink(str(req.userKey))
|
||||
return Res_TossUnlink() if err is ErrorType.SUCCESS else Res_TossUnlink(result=error_info(err))
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급")
|
||||
async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.refresh(req.refresh_token)
|
||||
|
||||
@@ -15,6 +15,17 @@ class Req_Login(Req_WebPacketProtocol):
|
||||
password: str
|
||||
|
||||
|
||||
class Req_TossLogin(Req_WebPacketProtocol):
|
||||
authorization_code: str
|
||||
referrer: str
|
||||
|
||||
|
||||
class Req_TossUnlink(Req_WebPacketProtocol):
|
||||
"""토스가 보내는 모양 그대로 (camelCase)"""
|
||||
userKey: int
|
||||
referrer: str
|
||||
|
||||
|
||||
class Req_Refresh(Req_WebPacketProtocol):
|
||||
refresh_token: str
|
||||
|
||||
@@ -41,6 +52,10 @@ class Res_Auth(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
class Res_TossUnlink(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_Logout(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -1,17 +0,0 @@
|
||||
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"})
|
||||
@@ -1,43 +0,0 @@
|
||||
"""프론트 지역 검색 페이지 목록(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]))
|
||||
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
||||
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']
|
||||
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) == 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')
|
||||
@@ -3730,159 +3730,5 @@
|
||||
"sort_order": 51,
|
||||
"priority": 3,
|
||||
"months": []
|
||||
},
|
||||
{
|
||||
"code": "umbrella_lost",
|
||||
"name": "우산분실각",
|
||||
"icon": "umbrella",
|
||||
"category": 4,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 9,
|
||||
"to": 11
|
||||
},
|
||||
{
|
||||
"from": 11,
|
||||
"to": 13
|
||||
},
|
||||
{
|
||||
"from": 13,
|
||||
"to": 15
|
||||
},
|
||||
{
|
||||
"from": 15,
|
||||
"to": 17
|
||||
},
|
||||
{
|
||||
"from": 17,
|
||||
"to": 19
|
||||
},
|
||||
{
|
||||
"from": 19,
|
||||
"to": 22
|
||||
}
|
||||
],
|
||||
"weight_temp": 0,
|
||||
"weight_rain": 80,
|
||||
"weight_wind": 0,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 20,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "range",
|
||||
"lo": 0,
|
||||
"hi": 40
|
||||
},
|
||||
"rain": {
|
||||
"dir": "dry"
|
||||
},
|
||||
"wind": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "fixed",
|
||||
"value": 100
|
||||
}
|
||||
},
|
||||
"zero_rules": [
|
||||
{
|
||||
"field": "rain_before",
|
||||
"op": "==",
|
||||
"value": "no"
|
||||
},
|
||||
{
|
||||
"field": "rain",
|
||||
"op": "==",
|
||||
"value": "yes"
|
||||
}
|
||||
],
|
||||
"limit_description": "비가 언제 그칠지는 예보만큼만 맞아요",
|
||||
"sentences": {
|
||||
"0": "우산 두고 올 일 없는 날이에요.",
|
||||
"30": "비가 오락가락해요. 우산 손에 꼭 쥐어요.",
|
||||
"60": "비가 그쳤어요. 카페·버스에 우산 두고 오기 딱 좋아요.",
|
||||
"80": "비 끝, 하늘 맑음! 일어날 때 우산부터 챙겨요 ☂️"
|
||||
},
|
||||
"sort_order": 52,
|
||||
"priority": 2,
|
||||
"months": []
|
||||
},
|
||||
{
|
||||
"code": "traffic",
|
||||
"name": "교통체증각",
|
||||
"icon": "drive",
|
||||
"category": 4,
|
||||
"is_fun": false,
|
||||
"is_core": false,
|
||||
"has_detail": true,
|
||||
"description": "출퇴근길 비·눈·추위로 차가 막히는 정도",
|
||||
"windows": [
|
||||
{
|
||||
"from": 7,
|
||||
"to": 10
|
||||
},
|
||||
{
|
||||
"from": 17,
|
||||
"to": 20
|
||||
}
|
||||
],
|
||||
"weight_temp": 10,
|
||||
"weight_rain": 70,
|
||||
"weight_wind": 0,
|
||||
"weight_humidity": 0,
|
||||
"weight_air": 0,
|
||||
"weight_uv": 0,
|
||||
"weight_sun": 0,
|
||||
"weight_view": 0,
|
||||
"weight_time": 20,
|
||||
"factor_rules": {
|
||||
"temp": {
|
||||
"type": "lower",
|
||||
"zero": 10,
|
||||
"full": -5
|
||||
},
|
||||
"rain": {
|
||||
"dir": "wet"
|
||||
},
|
||||
"wind": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"humidity": {
|
||||
"type": "ignore"
|
||||
},
|
||||
"time": {
|
||||
"type": "weekday",
|
||||
"mon": 100,
|
||||
"tue": 100,
|
||||
"wed": 100,
|
||||
"thu": 100,
|
||||
"fri": 100,
|
||||
"sat": 40,
|
||||
"sun": 40,
|
||||
"holiday": 30
|
||||
}
|
||||
},
|
||||
"zero_rules": [],
|
||||
"limit_description": "사고·공사·행사로 막히는 건 반영하지 못해요",
|
||||
"sentences": {
|
||||
"0": "길이 수월해요. 평소처럼 나가요.",
|
||||
"30": "조금 더뎌 수 있어요. 10분 일찍!",
|
||||
"60": "빗길에 차가 막혀요. 대중교통이 나아요.",
|
||||
"80": "출퇴근길 주차장 예상! 30분 일찍 나서요 🚗"
|
||||
},
|
||||
"sort_order": 53,
|
||||
"priority": 2,
|
||||
"months": []
|
||||
}
|
||||
]
|
||||
@@ -7,9 +7,11 @@ from fastapi import Depends
|
||||
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.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
from crud.user_crud import UserCRUD
|
||||
from services.external import toss_login
|
||||
|
||||
LOGIN_ID = re.compile(r"^[a-z0-9_]{4,20}$")
|
||||
PASSWORD_MIN = 8
|
||||
@@ -17,6 +19,7 @@ NICKNAME = re.compile(r"^\S.{0,10}\S$")
|
||||
CHARACTERS = ("rabbit", "bear", "dog", "sun", "moon", "cloud")
|
||||
COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
|
||||
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
|
||||
TOSS_REFERRERS = ("DEFAULT", "SANDBOX")
|
||||
|
||||
|
||||
class AuthService:
|
||||
@@ -47,6 +50,39 @@ class AuthService:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def toss_login(self, authorization_code: str, referrer: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""토스 userKey 로 계정을 찾고, 없으면 만든다. 이름·전화번호 같은 개인정보는 받지 않는다."""
|
||||
if not authorization_code or referrer not in TOSS_REFERRERS:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
try:
|
||||
key = str(await toss_login.user_key(authorization_code, referrer))
|
||||
except toss_login.TossLoginError as e:
|
||||
LOG.error(f"[auth] toss login: {e}")
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
provider = AuthProvider.TOSS.value
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
||||
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_social(s, provider, key, f"toss_{key}", f"토스{key[-4:]}")
|
||||
)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
# 같은 사람이 동시에 두 번 들어온 경우 먼저 만든 계정을 쓴다
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return err if err is not ErrorType.SUCCESS else ErrorType.DB_ERROR, None
|
||||
if user.status != 1:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def toss_unlink(self, user_key: str) -> ErrorType:
|
||||
"""토스에서 연결을 끊으면 그 계정의 모든 토큰을 무효로 만든다. 계정이 없어도 성공으로 본다."""
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, AuthProvider.TOSS.value, user_key))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return err
|
||||
return await self.logout(user)
|
||||
|
||||
async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]:
|
||||
claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh")
|
||||
if claims is None:
|
||||
|
||||
@@ -56,7 +56,6 @@ class Context:
|
||||
lookahead_rain_prob: int
|
||||
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
|
||||
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
|
||||
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -263,8 +262,6 @@ def _cond(r: dict) -> tuple[str, str, str]:
|
||||
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}이면"
|
||||
|
||||
@@ -347,7 +344,6 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
|
||||
"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:
|
||||
@@ -397,8 +393,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
|
||||
notes = {a: n for a, (_, n) in scored.items()}
|
||||
score = _weighted(factors, weights)
|
||||
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
|
||||
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
|
||||
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
|
||||
known = {"rain_prob": max_prob, "snow": "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)
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import ssl
|
||||
from functools import lru_cache
|
||||
|
||||
import httpx
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
TIMEOUT_SEC = 10.0
|
||||
_PATH = "/api-partner/v1/apps-in-toss/user/oauth2"
|
||||
|
||||
|
||||
class TossLoginError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _mtls() -> ssl.SSLContext:
|
||||
if not settings.toss_mtls_cert or not settings.toss_mtls_key:
|
||||
raise TossLoginError("TOSS_MTLS_CERT / TOSS_MTLS_KEY is empty")
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.load_cert_chain(settings.toss_mtls_cert, settings.toss_mtls_key)
|
||||
return ctx
|
||||
|
||||
|
||||
def _success(res: httpx.Response, step: str) -> dict:
|
||||
"""토스는 업무 오류도 HTTP 200 + resultType=FAIL 로 준다. 로그에 토큰·개인정보를 남기지 않는다."""
|
||||
res.raise_for_status()
|
||||
body = res.json()
|
||||
if body.get("resultType") != "SUCCESS":
|
||||
err = body.get("error")
|
||||
code = err.get("errorCode") if isinstance(err, dict) else err
|
||||
raise TossLoginError(f"{step} failed: {code}")
|
||||
return body["success"]
|
||||
|
||||
|
||||
async def user_key(authorization_code: str, referrer: str) -> int:
|
||||
"""앱에서 받은 인가 코드로 토스 토큰을 받고, 그 토큰으로 이 앱 전용 사용자 키(userKey)만 읽는다."""
|
||||
try:
|
||||
async with httpx.AsyncClient(base_url=settings.toss_api_base, verify=_mtls(), timeout=TIMEOUT_SEC, follow_redirects=False) as client:
|
||||
token = _success(
|
||||
await client.post(f"{_PATH}/generate-token", json={"authorizationCode": authorization_code, "referrer": referrer}),
|
||||
"generate-token",
|
||||
)
|
||||
me = _success(
|
||||
await client.get(f"{_PATH}/login-me", headers={"Authorization": f"Bearer {token['accessToken']}"}),
|
||||
"login-me",
|
||||
)
|
||||
return int(me["userKey"])
|
||||
except (httpx.HTTPError, ssl.SSLError, OSError, KeyError, ValueError) as e:
|
||||
LOG.error(f"[toss] login failed: {type(e).__name__}")
|
||||
raise TossLoginError(type(e).__name__) from None
|
||||
@@ -323,9 +323,6 @@ 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:
|
||||
|
||||
@@ -193,12 +193,6 @@ def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
|
||||
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,
|
||||
@@ -394,7 +388,7 @@ class IndexService:
|
||||
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, rain_hours=rain_hours(by_at, today), **base_ctx)
|
||||
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).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()}
|
||||
|
||||
@@ -425,7 +419,7 @@ 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), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, rain_hours=rain_hours(by_at, day), **base_ctx,
|
||||
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, **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)
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
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)
|
||||
@@ -25,7 +25,7 @@ from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestF
|
||||
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 = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다
|
||||
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
|
||||
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
|
||||
_MIN_DAY_HOURS = 8
|
||||
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import base64
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from config.settings import settings
|
||||
from router.router import app
|
||||
from services.external import toss_login
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def toss(monkeypatch):
|
||||
"""토스 서버 대신 코드별로 정해 둔 userKey 를 돌려준다."""
|
||||
keys = {"code-a": 1234567, "code-b": 7654321}
|
||||
|
||||
async def fake_user_key(code: str, referrer: str) -> int:
|
||||
if code not in keys:
|
||||
raise toss_login.TossLoginError("generate-token failed: invalid_grant")
|
||||
return keys[code]
|
||||
|
||||
monkeypatch.setattr(toss_login, "user_key", fake_user_key)
|
||||
monkeypatch.setattr(settings, "toss_unlink_auth", "toss:unlink-secret")
|
||||
|
||||
|
||||
def _basic(value: str) -> dict:
|
||||
return {"Authorization": "Basic " + base64.b64encode(value.encode()).decode()}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_login_creates_once_and_reuses(toss):
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "SANDBOX"})).json()
|
||||
again = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "DEFAULT"})).json()
|
||||
other = (await c.post("/v1/auth/toss", json={"authorization_code": "code-b", "referrer": "DEFAULT"})).json()
|
||||
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()
|
||||
assert first["result"]["success"] is True and first["me"]["provider"] == 3
|
||||
assert first["me"]["login_id"] == again["me"]["login_id"] == "toss_1234567"
|
||||
assert other["me"]["login_id"] == "toss_7654321"
|
||||
assert me["me"]["login_id"] == "toss_1234567"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_login_rejects_bad_code_and_referrer(toss):
|
||||
async with client() as c:
|
||||
bad_code = (await c.post("/v1/auth/toss", json={"authorization_code": "nope", "referrer": "DEFAULT"})).json()
|
||||
bad_ref = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "WEB"})).json()
|
||||
assert bad_code["result"]["desc"] == "AUTH_FAILED"
|
||||
assert bad_ref["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_unlink_needs_basic_auth_and_kills_tokens(toss):
|
||||
async with client() as c:
|
||||
login = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "DEFAULT"})).json()
|
||||
body = {"userKey": 1234567, "referrer": "UNLINK"}
|
||||
assert (await c.post("/v1/auth/toss/unlink", json=body)).status_code == 401
|
||||
assert (await c.post("/v1/auth/toss/unlink", json=body, headers=_basic("toss:wrong"))).status_code == 401
|
||||
ok = await c.post("/v1/auth/toss/unlink", json=body, headers=_basic("toss:unlink-secret"))
|
||||
unknown = await c.post("/v1/auth/toss/unlink", json={"userKey": 1, "referrer": "WITHDRAWAL_TOSS"}, headers=_basic("toss:unlink-secret"))
|
||||
me = await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {login['access_token']}"})
|
||||
assert ok.status_code == 200 and ok.json()["result"]["success"] is True
|
||||
assert unknown.status_code == 200
|
||||
assert me.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_unlink_rejects_all_when_not_configured(toss, monkeypatch):
|
||||
monkeypatch.setattr(settings, "toss_unlink_auth", "")
|
||||
async with client() as c:
|
||||
r = await c.post("/v1/auth/toss/unlink", json={"userKey": 1, "referrer": "UNLINK"}, headers=_basic(":"))
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_success_reads_toss_wrapper():
|
||||
ok = httpx.Response(200, json={"resultType": "SUCCESS", "success": {"userKey": 1}}, request=httpx.Request("GET", "https://x"))
|
||||
fail = httpx.Response(200, json={"resultType": "FAIL", "error": {"errorCode": "4050", "reason": "x"}}, request=httpx.Request("GET", "https://x"))
|
||||
grant = httpx.Response(200, json={"error": "invalid_grant"}, request=httpx.Request("GET", "https://x"))
|
||||
assert toss_login._success(ok, "login-me") == {"userKey": 1}
|
||||
with pytest.raises(toss_login.TossLoginError, match="4050"):
|
||||
toss_login._success(fail, "login-me")
|
||||
with pytest.raises(toss_login.TossLoginError, match="invalid_grant"):
|
||||
toss_login._success(grant, "generate-token")
|
||||
@@ -204,7 +204,7 @@ def test_gak_key_handles_sunset_window():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_missing_gak_is_not_cached(offline, monkeypatch):
|
||||
async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from services.index_service import IndexService
|
||||
@@ -216,7 +216,8 @@ async def test_feed_missing_gak_is_not_cached(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"]]
|
||||
assert [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] == []
|
||||
keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")]
|
||||
assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60
|
||||
|
||||
|
||||
def _alert_ctx(warnings=(), rain_prob=0):
|
||||
|
||||
@@ -308,13 +308,3 @@ def test_humidity_cap():
|
||||
|
||||
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
|
||||
@@ -1,67 +0,0 @@
|
||||
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
|
||||
@@ -43,6 +43,8 @@ services:
|
||||
REDIS_PORT: "6379"
|
||||
ports:
|
||||
- "${API_BIND:-9810}:9800"
|
||||
volumes:
|
||||
- ./secrets/toss:/run/secrets/toss:ro
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# 앱인토스 진행 계획
|
||||
|
||||
기준: 2026-10-12. 근거 문서는 [입점 검토](https://claude.ai/artifact/QgA7iq3CCesTRYcFyZck71), [토스판 전략](https://claude.ai/artifact/4WgpUjdNqdSNnMN4ASB4BB).
|
||||
|
||||
## 정한 것
|
||||
|
||||
- 토스판은 **WebView**로 만든다. React Native(Granite)는 쓰지 않는다. RN은 토스와 무관한 독립 앱으로만 진행한다.
|
||||
- 프로젝트를 따로 만들지 않는다. 지금 `frontend/` 하나에서 **웹 빌드**와 **토스 빌드** 두 가지를 낸다.
|
||||
- 웹을 먼저 출시하고, 토스판은 그 뒤에 낸다.
|
||||
- 토스판 1차부터 **토스 로그인**을 넣는다(10/14 결정). 좋아요·댓글도 웹과 같이 켠다. 아이디 로그인은 토스판에서 쓰지 않는다.
|
||||
|
||||
## 구조
|
||||
|
||||
```
|
||||
frontend/
|
||||
apps-in-toss.config.ts 토스 앱 설정 (appName, brand, permissions, navigationBar, webBundleDir=dist-toss)
|
||||
.env.toss 로컬 전용, 커밋 안 함. VITE_API_BASE_URL·VITE_SITE_URL=https://weather.o2o.kr
|
||||
src/lib/platform.ts 웹/토스 차이를 모으는 유일한 곳
|
||||
```
|
||||
|
||||
- 빌드: 웹은 `npm run build`, 토스는 `npm run build:toss`. 토스 빌드는 `vite build --mode toss --outDir dist-toss`를 돌린 뒤 `ait build`로 `weather-gak-test.ait`를 만든다. 지금 appName은 테스트용 `weather-gak-test`다. 정식 앱으로 바꿀 때는 `apps-in-toss.config.ts`와 `src/lib/platform.ts`(`intoss://` 주소) 두 곳을 같이 고친다.
|
||||
- SDK 3.x는 설정 파일이 `apps-in-toss.config.ts`다. 문서에 나오는 `granite.config.ts`는 2.x 방식이다.
|
||||
- 토스 빌드에서 `.env.toss`에 HTTPS 주소가 없으면 `vite.config.ts`가 빌드를 멈춘다.
|
||||
- `platform.ts`는 `import.meta.env.MODE === 'toss'`로 갈린다. SDK는 토스 모드에서만 동적으로 import하므로 웹 번들에는 들어가지 않는다. 웹 빌드 결과에 SDK 조각이 없는 것을 확인했다.
|
||||
- 화면 코드는 `platform.ts`의 함수만 부른다. 화면 곳곳에 `if (토스)`를 두지 않는다.
|
||||
- 백엔드는 고치지 않는다. CORS는 이미 전부 허용(`backend/router/router.py:34`)이고, API 주소는 `VITE_API_BASE_URL`로 받는다(`frontend/src/api/setup.ts:4`).
|
||||
|
||||
## 웹과 토스가 다른 점
|
||||
|
||||
| 기능 | 웹 | 토스 | 파일 |
|
||||
|---|---|---|---|
|
||||
| 공유 | `navigator.share` (이미지 카드 + 링크) | 이미지는 기기에 저장(`File.saveBase64`), 링크는 `Share.createLink` + `Share.sendMessage`. SDK 공유는 글만 보낼 수 있다 | `frontend/src/b/Sheets.tsx` |
|
||||
| 위치 | `navigator.geolocation` | `Device.getLocation`. 처음 들어올 때는 권한 창을 띄우지 않고, 이미 허용한 사람만 위치로 맞춘다. '내 위치' 버튼을 누를 때 권한 창을 띄운다 | `frontend/src/b/region.tsx` |
|
||||
| 로그인 | 아이디·비밀번호 | 토스 로그인(`TossAuth.login` → `POST /v1/auth/toss`). 토스가 주는 개인정보는 받지 않고 `userKey`만 저장한다 | `frontend/src/b/Sheets.tsx` (`TossLoginSheet`), `backend/services/external/toss_login.py` |
|
||||
| 좋아요·댓글 | 있음 | 있음. 신고·차단은 필수가 아니라 만들지 않는다(검수에서 요청하면 만든다) | `frontend/src/b/Post.tsx`, `frontend/src/b/Sheets.tsx` |
|
||||
| 네이버 지도 링크 | 있음 | 장소 이름만 표시. Q4 답이 '예외 해당'이면 되돌린다 | `frontend/src/b/ui.tsx` (`MapLink`) |
|
||||
| 밤 배경 | 어두운 남색 | Q3 답 보고 결정 | `frontend/src/b/BLayout.tsx` |
|
||||
| GA4 | `index.html`에 태그 | Q2 답 보고 결정 | `frontend/index.html`, `frontend/src/lib/analytics.ts` |
|
||||
| 라우터 | `BrowserRouter` | Q1 답 보고 결정 (안 되면 `HashRouter`) | `frontend/src/App.tsx` |
|
||||
| AI 글 표시 | 없음 | 계절 소식 등에 표시 (문구는 검토받은 뒤) | 글 시트 |
|
||||
|
||||
## 토스에 물어볼 것 (채널톡 · 개발자 커뮤니티)
|
||||
|
||||
| # | 질문 | 답 |
|
||||
|---|---|---|
|
||||
| Q1 | WebView에서 `BrowserRouter`(주소 경로)로 화면을 나눠도 되는가 | |
|
||||
| Q2 | 미니앱 안에서 GA4(`gtag.js`)를 써도 되는가 | |
|
||||
| Q3 | 시간대에 따라 밤에 어두운 배경을 쓰면 '라이트 모드' 규칙에 걸리는가 | |
|
||||
| Q4 | 장소 이름을 누르면 네이버 지도로 가는 링크가 '단순 정보 확인' 예외에 해당하는가 | |
|
||||
| Q5 | 공유창으로 이미지 파일(공유 카드)을 보낼 수 있는가 | SDK 기준 불가(`Share.sendMessage`는 글만). 지금은 이미지를 저장하고 링크를 보낸다 |
|
||||
| Q6 | TDS는 '강력 권장'인데 React 19 프로젝트도 TDS 없이 검수를 통과하는가 (TDS는 React 18 필요) | |
|
||||
| Q7 | 카테고리 목록. '나들이·여가' 같은 분류가 있는가 | |
|
||||
|
||||
## 단계
|
||||
|
||||
각 단계가 끝나면 확인을 받고 다음 단계로 간다. 작업 브랜치는 `feat/apps-in-toss`.
|
||||
|
||||
### 0. 사전 준비 — 사람이 할 일
|
||||
|
||||
- [ ] 앱인토스 콘솔 가입, 앱 등록 → `appName` 확정 (https://apps-in-toss.toss.im)
|
||||
- [ ] 사업자 정보 등록 (영업일 기준 약 1일)
|
||||
- [ ] 위 Q1~Q7 문의
|
||||
- [ ] 샌드박스 앱을 테스트 폰에 설치
|
||||
|
||||
### 1. 토스 빌드 뼈대
|
||||
|
||||
- [x] `@apps-in-toss/web-framework@3.8.0` 설치 (버전 고정)
|
||||
- [x] `apps-in-toss.config.ts`, `.env.toss`(로컬), `package.json`에 `build:toss` 추가 → `weather-gak-test.ait` 생성 확인
|
||||
- [ ] 샌드박스 앱에서 피드가 뜨는지 확인 — 콘솔 앱 등록·샌드박스 설치 뒤
|
||||
|
||||
완료 기준: 웹 빌드 결과가 바뀌지 않고, 샌드박스에서 피드가 열린다.
|
||||
|
||||
### 2. 플랫폼 분기
|
||||
|
||||
- [x] `src/lib/platform.ts`: `IS_TOSS`, `SOCIAL`, `tossShare`, `tossLocation`
|
||||
- [x] 공유·위치·지도 링크를 토스에서 분기
|
||||
- [x] 토스 로그인: 백엔드 `POST /v1/auth/toss`, 연결 끊기 콜백 `POST /v1/auth/toss/unlink`, 프론트 `TossLoginSheet` (10/14)
|
||||
- [ ] 운영 서버에 mTLS 인증서 두기, `.env`에 `TOSS_MTLS_CERT`·`TOSS_MTLS_KEY`·`TOSS_UNLINK_AUTH`, compose 마운트
|
||||
- [ ] 콘솔: 토스 로그인 약관 동의·동의 항목·연결 끊기 콜백 등록
|
||||
- [ ] Q1~Q3 답에 따라 라우터·GA4·밤 배경을 처리한다 (지금은 웹과 같음)
|
||||
|
||||
완료 기준: 웹은 지금과 똑같이 동작한다. 토스에서는 토스 로그인으로만 로그인한다.
|
||||
|
||||
### 3. 토스판 피드 줄이기 — 결정 대기
|
||||
|
||||
TODO.md의 '각 34개 정리', '히어로 숫자 5개'가 결정되면 진행한다. 목표는 피드 8~10칸, 첫 화면에 한 줄 판정이다. 문구는 목록으로 검토받은 뒤 반영한다.
|
||||
|
||||
### 4. 검증
|
||||
|
||||
- [x] `npm run lint`, `npm run build`, `npm run build:toss` 모두 통과 (10/12)
|
||||
- [ ] 샌드박스 실기기 확인: 첫 화면 뒤로가기를 누르면 앱이 닫힌다, 진입하자마자 바텀시트가 뜨지 않는다, 상단 바 버튼이 1개다, 위치 권한을 거부해도 지역 선택으로 쓸 수 있다
|
||||
- [ ] [비게임 검수 체크리스트](https://developers-apps-in-toss.toss.im/checklist/app-nongame.md)와 항목별로 대조
|
||||
- [ ] 토스 공식 `project-validator` 스킬로 점검 (https://github.com/toss/apps-in-toss-skills)
|
||||
|
||||
### 5. 출시
|
||||
|
||||
- [ ] 웹 출시가 끝났는지 확인
|
||||
- [ ] `.ait` 번들을 콘솔에 올리고 검수 요청 (3~5영업일, 반려 시 다시 3~5일)
|
||||
|
||||
### 6. 출시 후 — 별도 결정
|
||||
|
||||
- 스마트 발송(알림): 금요일 주말 판정, 노을 좋은 날. 노을 알림은 TODO.md에서 결정 대기 중이다.
|
||||
- 포인트: 출시 후 2주만 쓰고 끊는다. 포인트를 끊은 주의 재방문율로 계속할지 판단한다.
|
||||
+2
-1
@@ -12,6 +12,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
```
|
||||
|
||||
- 왜 GTM이 아니라 GA4 직접인가: 이벤트를 코드(`analytics.ts`)에서 정하므로, GTM을 쓰면 이벤트마다 트리거·태그를 한 번 더 만들어야 한다. 광고 픽셀도, 마케터가 직접 손볼 일도 아직 없다.
|
||||
- 모든 이벤트에 `platform: 'web' | 'toss'`가 붙는다. `index.html`의 `gtag('config')`에서 빌드 모드(`%MODE%`)로 정한다. GA4에서 보려면 맞춤 측정기준(이벤트 범위, `platform`)을 한 번 등록한다.
|
||||
- 개발 서버(`npm run dev`)에서는 `track()`이 이벤트를 보내지 않는다. 단 `index.html`의 페이지 조회(`page_view`)는 개발 서버에서도 나가므로 GA4에서 `localhost`를 걸러 본다.
|
||||
- 이벤트 이름은 영어 snake_case. GA4 추천 이벤트(`share`, `login`, `sign_up`, `select_content`)는 이름을 그대로 써야 GA4 기본 보고서에 잡힌다.
|
||||
- 값은 사람이 읽을 수 있게 한글 그대로 둔다 (예: `gak_name: '야장각'`).
|
||||
@@ -25,7 +26,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
| `view_gak` | 각 상세 시트가 열려 데이터가 뜸 (같은 각은 한 번만) | `index_id`, `gak_name`, `score`, `rank` | `Sheets.tsx` `GakSheet` |
|
||||
| `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` |
|
||||
| `login` | 로그인 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `login` | 로그인 성공 | `method: 'id'` 또는 `'toss'`(앱인토스) | `Sheets.tsx` `LoginSheet` `done`, `TossLoginSheet` |
|
||||
| `sign_up` | 가입 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `region_change` | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` |
|
||||
|
||||
|
||||
@@ -5,3 +5,6 @@ dist
|
||||
.DS_Store
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
dist-toss
|
||||
*.ait
|
||||
.env.toss
|
||||
@@ -22,3 +22,6 @@ dist-ssr
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
dist-toss
|
||||
*.ait
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from '@apps-in-toss/web-framework/config'
|
||||
|
||||
// appName 은 앱인토스 콘솔에 등록한 이름과 같아야 한다
|
||||
export default defineConfig({
|
||||
appName: 'nalssigak',
|
||||
brand: { primaryColor: '#ff7a45' },
|
||||
permissions: [{ name: 'geolocation', access: 'access' }],
|
||||
navigationBar: { withBackButton: true, withHomeButton: true },
|
||||
webBundleDir: 'dist-toss',
|
||||
})
|
||||
+7
-8
@@ -8,21 +8,21 @@
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
|
||||
gtag('config', 'G-D378J4X373');
|
||||
gtag('config', 'G-D378J4X373', { platform: '%MODE%' === 'toss' ? 'toss' : 'web' });
|
||||
</script>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<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" />
|
||||
@@ -60,7 +60,7 @@
|
||||
"@type": "WebApplication",
|
||||
"name": "날씨각",
|
||||
"url": "%VITE_SITE_URL%/",
|
||||
"description": "날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요.",
|
||||
"description": "세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요.",
|
||||
"applicationCategory": "WeatherApplication",
|
||||
"operatingSystem": "All",
|
||||
"inLanguage": "ko-KR",
|
||||
@@ -98,12 +98,11 @@
|
||||
</head>
|
||||
<body>
|
||||
<!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 -->
|
||||
<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">
|
||||
<div id="boot" 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>
|
||||
<div id="root">
|
||||
<main>
|
||||
<h1>날씨각</h1>
|
||||
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
|
||||
|
||||
@@ -31,23 +31,6 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
|
||||
location ~ ^/today/[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";
|
||||
|
||||
Generated
+1437
-18
File diff suppressed because it is too large.
Load diff
@@ -8,9 +8,11 @@
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview",
|
||||
"api": "openapi-ts"
|
||||
"api": "openapi-ts",
|
||||
"build:toss": "tsc -b && vite build --mode toss --outDir dist-toss && ait build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@apps-in-toss/web-framework": "3.8.0",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/react-query": "^5.104.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
|
||||
@@ -19,15 +19,16 @@
|
||||
<body>
|
||||
<main>
|
||||
<h1>개인정보처리방침</h1>
|
||||
<p class="muted">시행일: 2026년 10월 13일</p>
|
||||
<p class="muted">시행일: 2026년 10월 14일</p>
|
||||
|
||||
<p>AIO2O(이하 "회사")는 날씨각 웹 서비스(이하 "웹")와 날씨각 Wear OS 앱(이하 "워치 앱")을 운영하며, 「개인정보 보호법」에 따라 이용자의 개인정보를 다음과 같이 처리합니다.</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>토스 로그인 시 토스가 주는 이용자 식별값(이 서비스에서만 쓰는 값), 닉네임</td><td>회원 식별, 좋아요·저장·댓글 기능 제공. 토스에서 동의받은 이름 등 다른 정보는 받아 저장하지 않습니다.</td></tr>
|
||||
<tr><td>웹·토스 미니앱·워치 앱 위치</td><td>대략적인 위치(위도·경도)</td><td>가장 가까운 지역(구)의 날씨와 주변 축제를 보여주기 위해 사용합니다. 위치 좌표는 지역을 찾는 데만 쓰고 서버에 저장하지 않습니다.</td></tr>
|
||||
<tr><td>서비스 이용</td><td>접속 기록(IP 주소, 접속 시각, 브라우저 정보), 선택한 지역</td><td>서비스 운영, 오류 확인, 이용 통계</td></tr>
|
||||
</table>
|
||||
<p>위치 권한은 선택 사항입니다. 허용하지 않아도 지역을 직접 골라 이용할 수 있습니다. 워치 앱은 회원가입이나 로그인 없이 이용할 수 있습니다.</p>
|
||||
@@ -42,7 +43,7 @@
|
||||
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
|
||||
|
||||
<h2>5. 이용자의 권리</h2>
|
||||
<p>이용자는 언제든지 자신의 개인정보 열람, 정정, 삭제, 처리 정지와 회원 탈퇴를 요청할 수 있습니다. 아래 연락처로 요청하시면 지체 없이 처리합니다. 워치 앱의 위치 권한은 기기 설정에서 언제든지 끌 수 있습니다.</p>
|
||||
<p>이용자는 언제든지 자신의 개인정보 열람, 정정, 삭제, 처리 정지와 회원 탈퇴를 요청할 수 있습니다. 아래 연락처로 요청하시면 지체 없이 처리합니다. 워치 앱의 위치 권한은 기기 설정에서 언제든지 끌 수 있습니다. 토스 미니앱 회원은 토스 앱에서 날씨각과의 연결을 끊을 수 있으며, 연결을 끊으면 로그인이 풀립니다.</p>
|
||||
|
||||
<h2>6. 안전성 확보 조치</h2>
|
||||
<p>비밀번호는 암호화하여 저장하고, 개인정보에 접근할 수 있는 인원을 최소한으로 제한합니다.</p>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url><loc>https://weather.o2o.kr/</loc><lastmod>2026-10-13</lastmod></url>
|
||||
<url><loc>https://weather.o2o.kr/gak</loc><lastmod>2026-10-13</lastmod></url>
|
||||
<url><loc>https://weather.o2o.kr/sky</loc><lastmod>2026-10-13</lastmod></url>
|
||||
<url><loc>https://weather.o2o.kr/week</loc><lastmod>2026-10-13</lastmod></url>
|
||||
<url><loc>https://weather.o2o.kr/season</loc><lastmod>2026-10-13</lastmod></url>
|
||||
</urlset>
|
||||
@@ -0,0 +1,92 @@
|
||||
<!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; }
|
||||
ul { padding-left: 20px; }
|
||||
.muted { color: #5a6380; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>이용약관</h1>
|
||||
<p class="muted">시행일: 2026년 10월 14일</p>
|
||||
|
||||
<p>이 약관은 AIO2O(이하 "회사")가 제공하는 날씨각 서비스의 이용 조건과 절차, 회사와 이용자의 권리·의무를 정합니다.</p>
|
||||
|
||||
<h2>1. 용어</h2>
|
||||
<ul>
|
||||
<li>서비스: 회사가 웹(weather.o2o.kr), 토스 앱 안의 미니앱(이하 "토스 미니앱"), Wear OS 워치 앱으로 제공하는 날씨각과 그에 딸린 날씨·각 점수·노을·주말·행사·계절 정보, 좋아요·댓글·저장 기능</li>
|
||||
<li>이용자: 서비스를 이용하는 모든 사람</li>
|
||||
<li>회원: 웹에서 아이디·비밀번호로 가입했거나, 토스 미니앱에서 토스 로그인으로 로그인한 이용자</li>
|
||||
<li>게시물: 회원이 서비스에 올린 댓글</li>
|
||||
</ul>
|
||||
|
||||
<h2>2. 약관의 효력과 변경</h2>
|
||||
<p>이 약관은 서비스 화면에 게시해 효력이 생깁니다. 회사는 관련 법령을 어기지 않는 범위에서 약관을 바꿀 수 있으며, 바꿀 때는 시행 7일 전(이용자에게 불리한 변경은 30일 전)부터 서비스 안에서 알립니다.</p>
|
||||
<p>바뀐 약관에 동의하지 않으면 이용을 그만두고 탈퇴할 수 있습니다. 알린 시행일 뒤에도 계속 이용하면 바뀐 약관에 동의한 것으로 봅니다.</p>
|
||||
|
||||
<h2>3. 회원가입과 로그인</h2>
|
||||
<p>웹에서는 아이디, 비밀번호, 닉네임을 입력하고 가입합니다. 토스 미니앱에서는 토스 로그인에 동의하면 회원이 됩니다. 가입하거나 토스 로그인을 하면 이 약관과 <a href="/privacy">개인정보처리방침</a>에 동의한 것으로 봅니다.</p>
|
||||
<p>만 14세 미만은 회원이 될 수 없습니다. 다른 사람의 정보를 쓰거나 다른 사람을 사칭하는 닉네임을 쓸 수 없습니다.</p>
|
||||
|
||||
<h2>4. 서비스 이용</h2>
|
||||
<p>날씨와 각 점수, 노을, 주말·행사, 계절 정보는 로그인 없이 무료로 볼 수 있습니다. 좋아요, 댓글, 저장은 로그인한 뒤에 쓸 수 있습니다.</p>
|
||||
<p>회사는 운영상·기술상 필요에 따라 서비스의 내용을 바꾸거나 일부 또는 전부를 중단할 수 있으며, 중요한 변경이나 중단은 미리 알립니다. 다만 미리 알릴 수 없는 사정이 있으면 나중에 알릴 수 있습니다.</p>
|
||||
|
||||
<h2>5. 날씨 정보와 면책</h2>
|
||||
<p>서비스의 날씨, 미세먼지, 각 점수, 노을 판정, 주말 순위, 행사 정보는 공공 데이터와 외부 예보를 바탕으로 회사가 계산하거나 정리한 참고 정보입니다. 예보는 실제 날씨와 다를 수 있고, 외부 제공처의 사정으로 늦거나 빠질 수 있습니다.</p>
|
||||
<p>회사는 이 정보의 정확성이나 이 정보를 근거로 한 결정의 결과를 보증하지 않습니다. 야외 활동, 여행, 행사 참석 같은 결정은 이용자 스스로 판단하며, 기상특보나 행사 일정은 기상청과 각 주최 측의 공식 안내를 함께 확인해 주세요.</p>
|
||||
<p>회사의 고의나 중대한 과실로 생긴 손해는 이 면책에서 제외합니다.</p>
|
||||
|
||||
<h2>6. 게시물(댓글)</h2>
|
||||
<p>게시물에 대한 책임은 그 게시물을 쓴 회원에게 있습니다. 다음 게시물은 쓸 수 없습니다.</p>
|
||||
<ul>
|
||||
<li>욕설, 비방, 혐오, 음란한 내용</li>
|
||||
<li>다른 사람의 개인정보(이름, 연락처, 주소 등)를 드러내는 내용</li>
|
||||
<li>광고, 홍보, 같은 내용을 되풀이하는 도배</li>
|
||||
<li>다른 사람의 저작권 등 권리를 침해하거나 법령을 어기는 내용</li>
|
||||
</ul>
|
||||
<p>회사는 위에 해당하거나 권리자의 요청이 있는 게시물을 미리 알리지 않고 지우거나 보이지 않게 할 수 있습니다. 문제가 있는 게시물은 <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a>로 알려 주세요. 회원은 자신의 댓글을 언제든 직접 지울 수 있습니다.</p>
|
||||
<p>게시물의 저작권은 쓴 회원에게 있습니다. 회원은 회사가 서비스 안에 그 게시물을 보여 주는 데 필요한 범위에서 이용하도록 허락합니다.</p>
|
||||
|
||||
<h2>7. 회원의 의무와 이용 제한</h2>
|
||||
<p>회원은 자신의 계정을 스스로 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다.</p>
|
||||
<p>자동화된 수단으로 정보를 대량으로 가져가거나, 서비스 운영을 방해하거나, 이 약관을 어기면 회사는 해당 게시물을 지우고 서비스 이용을 제한할 수 있습니다.</p>
|
||||
|
||||
<h2>8. 회원 탈퇴</h2>
|
||||
<p>회원은 언제든 <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a>로 탈퇴를 요청할 수 있고, 회사는 지체 없이 처리합니다. 토스 미니앱 회원은 토스 앱에서 날씨각과의 연결을 끊을 수도 있습니다. 탈퇴하면 회원 정보, 댓글, 좋아요, 저장한 포스트를 <a href="/privacy">개인정보처리방침</a>에 따라 파기하며 되살릴 수 없습니다.</p>
|
||||
|
||||
<h2>9. 책임의 한계</h2>
|
||||
<p>회사는 천재지변, 정전, 외부 데이터 제공처의 장애처럼 회사가 통제할 수 없는 사유나 이용자의 잘못으로 생긴 서비스 장애에 대해서는 책임지지 않습니다. 회원끼리 또는 회원과 제3자 사이에 게시물로 생긴 분쟁에 대해서도 같습니다.</p>
|
||||
|
||||
<h2>10. 분쟁 해결</h2>
|
||||
<p>이 약관과 서비스 이용에는 대한민국 법을 적용합니다. 서비스 이용과 관련해 분쟁이 생기면 회사와 이용자는 먼저 성실히 협의하고, 소송이 필요하면 민사소송법에 따른 관할 법원에 제기합니다.</p>
|
||||
|
||||
<h2>11. 데이터 출처</h2>
|
||||
<p>서비스는 다음 기관과 제공처의 데이터를 사용합니다. 공공 데이터는 공공데이터포털(data.go.kr)을 통해 받으며 각 기관의 이용 조건을 따릅니다.</p>
|
||||
<ul>
|
||||
<li>기상청: 단기·초단기·중기 예보, 기상특보</li>
|
||||
<li>한국환경공단 에어코리아: 대기오염 실시간 측정 정보</li>
|
||||
<li>한국천문연구원: 공휴일·24절기, 해 뜨고 지는 시각</li>
|
||||
<li>한국관광공사: 축제·행사, 명소 정보와 사진 (ⓒ한국관광공사)</li>
|
||||
<li>한국문화정보원: 공연·전시 정보와 사진 (ⓒ한국문화정보원)</li>
|
||||
<li>Open-Meteo: 구름 등 기상 예보 (CC BY 4.0)</li>
|
||||
<li>팝가: 팝업스토어 정보</li>
|
||||
</ul>
|
||||
|
||||
<h2>12. 운영자 정보</h2>
|
||||
<p>상호: AIO2O<br />문의: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></p>
|
||||
|
||||
<h2>부칙</h2>
|
||||
<p>이 약관은 2026년 10월 14일부터 시행합니다.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -202,13 +202,5 @@
|
||||
{
|
||||
"name": "싱잉인더레인각",
|
||||
"description": "비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도"
|
||||
},
|
||||
{
|
||||
"name": "우산분실각",
|
||||
"description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도"
|
||||
},
|
||||
{
|
||||
"name": "교통체증각",
|
||||
"description": "출퇴근길 비·눈·추위로 차가 막히는 정도"
|
||||
}
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,7 +12,6 @@ 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 />} />
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, toss, tossUnlink, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
@@ -379,6 +379,40 @@ export const loginMutation = (options?: Partial<Options<LoginData>>): UseMutatio
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)
|
||||
*/
|
||||
export const tossMutation = (options?: Partial<Options<TossData>>): UseMutationOptions<TossResponse, TossError, Options<TossData>> => {
|
||||
const mutationOptions: UseMutationOptions<TossResponse, TossError, Options<TossData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await toss({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름)
|
||||
*/
|
||||
export const tossUnlinkMutation = (options?: Partial<Options<TossUnlinkData>>): UseMutationOptions<TossUnlinkResponse, TossUnlinkError, Options<TossUnlinkData>> => {
|
||||
const mutationOptions: UseMutationOptions<TossUnlinkResponse, TossUnlinkError, Options<TossUnlinkData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await tossUnlink({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 토큰 재발급
|
||||
*/
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, typeLine truncated
|
||||
export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, toss, tossUnlink, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqTossLogin, type ReqTossUnlink, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResTossUnlink, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TossDaLine truncated
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||
/**
|
||||
@@ -127,6 +127,30 @@ export const login = <ThrowOnError extends boolean = true>(options: Options<Logi
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)
|
||||
*/
|
||||
export const toss = <ThrowOnError extends boolean = true>(options: Options<TossData, ThrowOnError>): RequestResult<TossResponses, TossErrors, ThrowOnError> => (options.client ?? client).post<TossResponses, TossErrors, ThrowOnError>({
|
||||
url: '/v1/auth/toss',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름)
|
||||
*/
|
||||
export const tossUnlink = <ThrowOnError extends boolean = true>(options: Options<TossUnlinkData, ThrowOnError>): RequestResult<TossUnlinkResponses, TossUnlinkErrors, ThrowOnError> => (options.client ?? client).post<TossUnlinkResponses, TossUnlinkErrors, ThrowOnError>({
|
||||
url: '/v1/auth/toss/unlink',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 토큰 재발급
|
||||
*/
|
||||
|
||||
@@ -123,13 +123,20 @@ export type ArticleSummary = {
|
||||
/**
|
||||
* AuthProvider
|
||||
*/
|
||||
export const AuthProvider = { /**
|
||||
export const AuthProvider = {
|
||||
/**
|
||||
* LOCAL
|
||||
*/
|
||||
LOCAL: 1, /**
|
||||
LOCAL: 1,
|
||||
/**
|
||||
* GOOGLE
|
||||
*/
|
||||
GOOGLE: 2 } as const;
|
||||
GOOGLE: 2,
|
||||
/**
|
||||
* TOSS
|
||||
*/
|
||||
TOSS: 3
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* AuthProvider
|
||||
@@ -1247,6 +1254,36 @@ export type ReqSignup = {
|
||||
nickname: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_TossLogin
|
||||
*/
|
||||
export type ReqTossLogin = {
|
||||
/**
|
||||
* Authorization Code
|
||||
*/
|
||||
authorization_code: string;
|
||||
/**
|
||||
* Referrer
|
||||
*/
|
||||
referrer: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_TossUnlink
|
||||
*
|
||||
* 토스가 보내는 모양 그대로 (camelCase)
|
||||
*/
|
||||
export type ReqTossUnlink = {
|
||||
/**
|
||||
* Userkey
|
||||
*/
|
||||
userKey: number;
|
||||
/**
|
||||
* Referrer
|
||||
*/
|
||||
referrer: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Req_UpdateMe
|
||||
*/
|
||||
@@ -1760,6 +1797,17 @@ export type ResSkyRanking = {
|
||||
items?: Array<RankData>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_TossUnlink
|
||||
*/
|
||||
export type ResTossUnlink = {
|
||||
result?: ErrorInfo;
|
||||
/**
|
||||
* Msg
|
||||
*/
|
||||
msg?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Res_WatchSummary
|
||||
*/
|
||||
@@ -2635,6 +2683,10 @@ export type WatchNow = {
|
||||
* Rain 2H
|
||||
*/
|
||||
rain_2h?: boolean | null;
|
||||
/**
|
||||
* Thunder
|
||||
*/
|
||||
thunder?: boolean | null;
|
||||
/**
|
||||
* Text
|
||||
*/
|
||||
@@ -3472,6 +3524,62 @@ export type LoginResponses = {
|
||||
|
||||
export type LoginResponse = LoginResponses[keyof LoginResponses];
|
||||
|
||||
export type TossData = {
|
||||
body: ReqTossLogin;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/auth/toss';
|
||||
};
|
||||
|
||||
export type TossErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type TossError = TossErrors[keyof TossErrors];
|
||||
|
||||
export type TossResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResAuth;
|
||||
};
|
||||
|
||||
export type TossResponse = TossResponses[keyof TossResponses];
|
||||
|
||||
export type TossUnlinkData = {
|
||||
body: ReqTossUnlink;
|
||||
headers?: {
|
||||
/**
|
||||
* Authorization
|
||||
*/
|
||||
authorization?: string | null;
|
||||
};
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/v1/auth/toss/unlink';
|
||||
};
|
||||
|
||||
export type TossUnlinkErrors = {
|
||||
/**
|
||||
* Validation Error
|
||||
*/
|
||||
422: HttpValidationError;
|
||||
};
|
||||
|
||||
export type TossUnlinkError = TossUnlinkErrors[keyof TossUnlinkErrors];
|
||||
|
||||
export type TossUnlinkResponses = {
|
||||
/**
|
||||
* Successful Response
|
||||
*/
|
||||
200: ResTossUnlink;
|
||||
};
|
||||
|
||||
export type TossUnlinkResponse = TossUnlinkResponses[keyof TossUnlinkResponses];
|
||||
|
||||
export type RefreshData = {
|
||||
body: ReqRefresh;
|
||||
path?: never;
|
||||
|
||||
@@ -48,17 +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 px-4 pt-[env(safe-area-inset-top,0px)]">
|
||||
<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="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 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)]"
|
||||
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)]"
|
||||
>
|
||||
<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>}
|
||||
<PinIcon className="size-3.5" />
|
||||
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : region.name}
|
||||
</button>
|
||||
{mePending ? (
|
||||
<Skel shape className="size-9 shrink-0 rounded-full" />
|
||||
@@ -208,10 +208,6 @@ function Shell() {
|
||||
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])
|
||||
@@ -232,14 +228,14 @@ function Shell() {
|
||||
{TABS.map((t) =>
|
||||
t.key === 'today' ? (
|
||||
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
|
||||
<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)')}>
|
||||
<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="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} 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]')}>
|
||||
<NavLink key={t.key} to={t.to} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
|
||||
<TabIcon name={t.key} className="size-[25px]" />
|
||||
{t.label}
|
||||
</NavLink>
|
||||
|
||||
@@ -16,11 +16,13 @@ import {
|
||||
loginMutation,
|
||||
meQueryKey,
|
||||
signupMutation,
|
||||
tossMutation,
|
||||
unlikeCommentMutation,
|
||||
updateMeMutation,
|
||||
} 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 { IS_TOSS, tossLogin, tossShare } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||
@@ -550,6 +552,19 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
const send = () => {
|
||||
if (!image) return
|
||||
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
|
||||
if (IS_TOSS) {
|
||||
tossShare(image.blob, file.name, share.title).then(
|
||||
(r) => {
|
||||
setToast(r === 'saved' ? '이미지를 저장하고 링크를 보냈어요' : '링크를 보냈어요')
|
||||
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[share] toss', e)
|
||||
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
if (navigator.canShare?.({ files: [file], text })) {
|
||||
navigator.share({ files: [file], title: share.title, text }).then(
|
||||
() => {
|
||||
@@ -826,6 +841,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
}
|
||||
|
||||
if (me) return <MeSheet onDone={onDone} />
|
||||
if (IS_TOSS) return <TossLoginSheet onDone={onDone} onLoggedIn={onLoggedIn} />
|
||||
|
||||
const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3'
|
||||
return (
|
||||
@@ -861,6 +877,56 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
||||
)
|
||||
}
|
||||
|
||||
/** 앱인토스는 토스 로그인만 쓸 수 있다 */
|
||||
function TossLoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
|
||||
const [error, setError] = useState('')
|
||||
const [opening, setOpening] = useState(false)
|
||||
const toss = useMutation(tossMutation())
|
||||
const pending = opening || toss.isPending
|
||||
|
||||
const start = async () => {
|
||||
setError('')
|
||||
setOpening(true)
|
||||
let code: Awaited<ReturnType<typeof tossLogin>>
|
||||
try {
|
||||
code = await tossLogin()
|
||||
} catch (e) {
|
||||
console.error('[login] toss', e)
|
||||
setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.')
|
||||
return
|
||||
} finally {
|
||||
setOpening(false)
|
||||
}
|
||||
toss.mutate(
|
||||
{ body: { authorization_code: code.authorizationCode, referrer: code.referrer } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success || !res.access_token) return setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.')
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
track('login', { method: 'toss' })
|
||||
onLoggedIn()
|
||||
},
|
||||
onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Body className="flex flex-col gap-2.5">
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||||
{error}
|
||||
</p>
|
||||
<button type="button" onClick={start} disabled={pending} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
<Swap labels={['토스로 로그인', '로그인 중…']} at={pending ? 1 : 0} />
|
||||
</button>
|
||||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||||
나중에 할게요
|
||||
</button>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
|
||||
function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
const { me, logout } = useAuth()
|
||||
@@ -896,7 +962,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
<Body className="flex flex-col gap-3">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<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.TOSS ? '토스로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
|
||||
</div>
|
||||
<section aria-label="내 캐릭터">
|
||||
<h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4>
|
||||
|
||||
+43
-73
@@ -1,26 +1,12 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { matchPath, useLocation, useNavigate } from 'react-router'
|
||||
import regionPages from '../../seo/region.json'
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { nearestRegion } from '../api/client/sdk.gen'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { IS_TOSS, tossLocation } from '../lib/platform'
|
||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
|
||||
type RegionPage = (typeof regionPages)[number]
|
||||
|
||||
/** /today/gyeonggi/seongnam 같은 지역 페이지 주소면 그 페이지 */
|
||||
function pageOf(pathname: string): RegionPage | undefined {
|
||||
const m = matchPath('/today/:sido/:place', pathname)
|
||||
return m ? regionPages.find((p) => p.path === `${m.params.sido}/${m.params.place}`) : 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)
|
||||
@@ -41,45 +27,50 @@ 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 [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>(!landing && !stored && canLocate ? 'locating' : 'idle')
|
||||
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION)
|
||||
const canLocate = IS_TOSS || (typeof navigator !== 'undefined' && 'geolocation' in navigator)
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>((!stored || IS_TOSS) && canLocate ? 'locating' : 'idle')
|
||||
|
||||
// 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
const next = regionPages.find((p) => p.regions.some((g) => g.code === r.code))
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`)
|
||||
}, [navigate])
|
||||
}, [])
|
||||
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
|
||||
const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false) => {
|
||||
const fromCoords = useCallback((lat: number, lon: number, onFound?: () => void) => {
|
||||
nearestRegion({ query: { lat, lon } })
|
||||
.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?.()
|
||||
})
|
||||
.catch(() => setLocateStatus('error'))
|
||||
}, [setRegion])
|
||||
|
||||
// ask=false 면 토스에서 권한 창 없이, 이미 허용한 사람만 위치로 맞춘다
|
||||
const findNearest = useCallback((onFound?: () => void, ask = true) => {
|
||||
if (IS_TOSS) {
|
||||
tossLocation(ask).then(
|
||||
(loc) => {
|
||||
if (loc === null) setLocateStatus('idle')
|
||||
else if (loc === 'denied') setLocateStatus('denied')
|
||||
else fromCoords(loc.lat, loc.lon, onFound)
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[region] toss location', e)
|
||||
setLocateStatus('error')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||
.then(({ data: res }) => {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setLocateStatus('idle')
|
||||
apply(res.region)
|
||||
})
|
||||
.catch(() => !quiet && setLocateStatus('error'))
|
||||
},
|
||||
(err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
(pos) => fromCoords(pos.coords.latitude, pos.coords.longitude, onFound),
|
||||
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
{ timeout: 10000, maximumAge: 600000 },
|
||||
)
|
||||
}, [])
|
||||
}, [fromCoords])
|
||||
|
||||
const locate = useCallback((onFound?: () => void) => {
|
||||
if (!canLocate) {
|
||||
@@ -87,36 +78,15 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest((r) => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
onFound?.()
|
||||
})
|
||||
}, [canLocate, findNearest, setRegion])
|
||||
findNearest(onFound)
|
||||
}, [canLocate, findNearest])
|
||||
|
||||
// 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 토스판은 지역을 고른 적 있어도 권한이 있으면 들어올 때마다 지금 위치로
|
||||
useEffect(() => {
|
||||
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])
|
||||
if (!stored) findNearest()
|
||||
else if (IS_TOSS) findNearest(undefined, false)
|
||||
}, [stored, canLocate, findNearest])
|
||||
|
||||
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
||||
return <RegionContext value={api}>{children}</RegionContext>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { IS_TOSS } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useCarousel, type Carousel } from './carousel'
|
||||
import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
|
||||
@@ -202,6 +203,8 @@ export function StateBox({ load, onRetry, empty, className, hold }: StateProps)
|
||||
/** 줄 목록 (라벨 · 값) */
|
||||
/** 위치가 정해진 장소 이름. 누르면 네이버 지도가 새 탭으로 열린다 */
|
||||
export function MapLink({ place, children, className }: { place: string; children: ReactNode; className?: string }) {
|
||||
// 앱인토스는 외부 이동을 막는다
|
||||
if (IS_TOSS) return <span className={className}>{children}</span>
|
||||
return (
|
||||
<a href={naverMap(place)} target="_blank" rel="noopener noreferrer" aria-label={`${place}, 네이버 지도에서 보기`} className={cx('underline decoration-dotted decoration-1 underline-offset-[3px]', className)}>
|
||||
{children}
|
||||
|
||||
@@ -3,7 +3,7 @@ type Events = {
|
||||
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
|
||||
select_content: { content_type: 'article'; item_id: number; category: string }
|
||||
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
|
||||
login: { method: 'id' }
|
||||
login: { method: 'id' | 'toss' }
|
||||
sign_up: { method: 'id' }
|
||||
region_change: { region_name: string; method: 'list' | 'location' }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/** 웹/앱인토스 차이를 모으는 곳. 토스 SDK 는 토스 빌드(`vite build --mode toss`)에서만 불러온다 */
|
||||
export const IS_TOSS = import.meta.env.MODE === 'toss'
|
||||
|
||||
const TOSS_APP = 'intoss://nalssigak'
|
||||
|
||||
// 웹 빌드에서는 이 분기가 지워져 SDK 가 번들에 들어가지 않는다
|
||||
const sdk = () => (import.meta.env.MODE === 'toss' ? import('@apps-in-toss/web-framework') : Promise.reject(new Error('토스 앱 밖에서는 쓸 수 없어요')))
|
||||
|
||||
function toBase64(blob: Blob): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '')
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
}
|
||||
|
||||
/** 토스: 이미지를 기기에 저장하고 토스 앱 링크를 공유창으로 보낸다 */
|
||||
export async function tossShare(image: Blob, fileName: string, title: string): Promise<'saved' | 'link-only'> {
|
||||
const { File, Share } = await sdk()
|
||||
let saved = false
|
||||
if (File.saveBase64.isSupported()) {
|
||||
await File.saveBase64({ data: await toBase64(image), fileName, mimeType: image.type })
|
||||
saved = true
|
||||
}
|
||||
const link = await Share.createLink({ path: TOSS_APP })
|
||||
await Share.sendMessage({ message: `${title} · 날씨각 ${link}` })
|
||||
return saved ? 'saved' : 'link-only'
|
||||
}
|
||||
|
||||
/** 토스: 토스 로그인 창을 띄우고 서버로 보낼 인가 코드를 받는다 */
|
||||
export async function tossLogin() {
|
||||
const { TossAuth } = await sdk()
|
||||
return TossAuth.login()
|
||||
}
|
||||
|
||||
export type TossLocation = { lat: number; lon: number } | 'denied'
|
||||
|
||||
/** 토스: 위치를 읽는다. 권한이 없으면 ask 일 때만 권한 창을 띄운다 */
|
||||
export async function tossLocation(ask: boolean): Promise<TossLocation | null> {
|
||||
const { Accuracy, Device } = await sdk()
|
||||
let status = await Device.getLocation.getPermission()
|
||||
if (status !== 'allowed' && ask) status = await Device.getLocation.openPermissionDialog()
|
||||
if (status !== 'allowed') return ask ? 'denied' : null
|
||||
const { coords } = await Device.getLocation({ accuracy: Accuracy.Balanced })
|
||||
return { lat: coords.latitude, lon: coords.longitude }
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
|
||||
@@ -19,5 +19,5 @@
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
"include": ["vite.config.ts", "apps-in-toss.config.ts"]
|
||||
}
|
||||
+19
-41
@@ -1,18 +1,16 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig, type Plugin } from 'vite'
|
||||
import { defineConfig, loadEnv, 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 }[] = [
|
||||
const PAGES: { path: string; title: string; description: string; body: string }[] = [
|
||||
{
|
||||
path: 'gak',
|
||||
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
|
||||
@@ -39,30 +37,6 @@ const PAGES: { path: string; title: string; description: string; body: string; c
|
||||
},
|
||||
]
|
||||
|
||||
/** 제목 앞자리: 검색어처럼 시군구 이름부터 (경기 성남시 → 성남시) */
|
||||
const headName = (name: string) => name.split(' ').at(-1)!
|
||||
/** 검색어로 많이 치는 꼴: 성남시 → 성남. 중구처럼 두 글자는 그대로 */
|
||||
const bareName = (name: string) => (name.length > 2 ? name.slice(0, -1) : name)
|
||||
|
||||
/** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */
|
||||
for (const r of regionPages) {
|
||||
const sido = r.path.split('/')[0]
|
||||
const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`))
|
||||
const parts = r.regions.length > 1 ? `<p>${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).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(' ')[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 {
|
||||
@@ -82,24 +56,28 @@ function seoPages(): Plugin {
|
||||
.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)
|
||||
writeFileSync(resolve(outDir, `${p.path}.html`), 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`)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 토스 빌드는 토스 도메인에서 열리므로 API·사이트 주소를 HTTPS 절대 주소로 받아야 한다
|
||||
function checkTossEnv(mode: string) {
|
||||
if (mode !== 'toss') return
|
||||
const env = loadEnv(mode, process.cwd())
|
||||
for (const key of ['VITE_API_BASE_URL', 'VITE_SITE_URL']) {
|
||||
if (!env[key]?.startsWith('https://')) throw new Error(`토스 빌드: ${key} 에 https:// 주소가 필요해요 (frontend/.env.toss)`)
|
||||
}
|
||||
}
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss(), seoPages()],
|
||||
export default defineConfig(({ mode }) => {
|
||||
checkTossEnv(mode)
|
||||
return {
|
||||
plugins: [react(), tailwindcss(), ...(mode === 'toss' ? [] : [seoPages()])],
|
||||
}
|
||||
})
|
||||
@@ -1,15 +1,3 @@
|
||||
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")
|
||||
@@ -21,13 +9,10 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "kr.o2o.nalssigak"
|
||||
// Wear OS 6+ 만. 앱 설치 때 스킨을 같이 깔고 시계 화면으로 바꾸는 Watch Face Push 가 API 36 부터다
|
||||
minSdk = 36
|
||||
targetSdk = 36
|
||||
minSdk = 30
|
||||
targetSdk = 34
|
||||
versionCode = 1
|
||||
versionName = "0.1"
|
||||
// 앱에 실은 스킨 버전. 워치에 깔린 스킨이 이보다 낮으면 앱이 바꿔 끼운다 (MainActivity.useSkin)
|
||||
buildConfigField("int", "SKIN_VERSION", providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get())
|
||||
}
|
||||
buildTypes {
|
||||
// 에뮬레이터에서 본 맥의 로컬 백엔드 (compose 포트 9810)
|
||||
@@ -53,36 +38,4 @@ 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,9 +4,6 @@
|
||||
<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"
|
||||
@@ -16,11 +13,6 @@
|
||||
<!-- 폰 앱 없이 워치에서 단독으로 동작 -->
|
||||
<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" />
|
||||
@@ -134,7 +126,7 @@
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
<!-- 워치 스킨 숨은 칸용: 날씨(비·눈·천둥)·기온·가운데 1위 -->
|
||||
<!-- 워치 스킨 숨은 칸용: 비·눈 여부 -->
|
||||
<service
|
||||
android:name=".RainComplicationService"
|
||||
android:exported="true"
|
||||
@@ -144,7 +136,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="RANGED_VALUE" />
|
||||
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="SHORT_TEXT" />
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ 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
|
||||
@@ -18,85 +16,29 @@ 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 askPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
load()
|
||||
useSkin()
|
||||
}
|
||||
private val askLocation = registerForActivityResult(ActivityResultContracts.RequestPermission()) { load() }
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val opened = intent.getStringExtra(EXTRA_GAK)
|
||||
setContent { MaterialTheme { App(summary, loading, opened) { load(force = true) } } }
|
||||
// 위치와 스킨 적용을 한 번에 묻는다
|
||||
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()
|
||||
}
|
||||
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) load()
|
||||
else askLocation.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
}
|
||||
|
||||
private fun load(force: Boolean = false) {
|
||||
@@ -108,7 +50,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class Page { DETAIL, HOURS, EVENTS, TOP, PICKS, SUNSET }
|
||||
private enum class Page { DETAIL, EVENTS, TOP, PICKS, SUNSET, HOURS }
|
||||
|
||||
@Composable
|
||||
private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> Unit) {
|
||||
@@ -123,15 +65,15 @@ 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)
|
||||
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.sunset != null) add(Page.SUNSET)
|
||||
if (s.slots.isNotEmpty()) add(Page.HOURS)
|
||||
}
|
||||
val state = rememberPagerState { pages.size }
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
|
||||
@@ -1,45 +1,27 @@
|
||||
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.RangedValueComplicationData
|
||||
import androidx.wear.watchface.complications.data.ShortTextComplicationData
|
||||
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
|
||||
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 ?: "")
|
||||
return data(s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", s.rainLabel)
|
||||
}
|
||||
|
||||
override fun getPreviewData(type: ComplicationType): ComplicationData = data(0, 88, "20°", "산책각")
|
||||
override fun getPreviewData(type: ComplicationType): ComplicationData = data("20°", "비 없음")
|
||||
|
||||
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()
|
||||
}
|
||||
private fun data(temp: String, rain: String) = ShortTextComplicationData.Builder(
|
||||
PlainComplicationText.Builder(temp).build(),
|
||||
PlainComplicationText.Builder("$temp $rain").build(),
|
||||
).setTitle(PlainComplicationText.Builder(rain).build()).build()
|
||||
}
|
||||
@@ -60,7 +60,7 @@ data class Summary(
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** 비 소식. 스킨 날씨 칸(RainComplicationService)이 이 글자로 날씨 코드를 정한다 */
|
||||
/** 스킨 칩의 비 소식. 스킨은 이 글자를 보고 가운데를 비구름·천둥 구름·눈구름으로 바꾼다 */
|
||||
val rainLabel: String get() = when {
|
||||
precip == "snow" -> "눈 와요"
|
||||
thunder == true -> "천둥 쳐요"
|
||||
|
||||
@@ -1,4 +1,2 @@
|
||||
org.gradle.jvmargs=-Xmx2g
|
||||
android.useAndroidX=true
|
||||
# 워치 스킨 버전. 스킨(watchface.xml·리소스)을 바꾸면 1 올린다. 앱은 깔린 스킨이 이보다 낮으면 앱에 실은 스킨으로 바꿔 끼운다
|
||||
NALSSIGAK_SKIN_VERSION=2
|
||||
@@ -9,16 +9,15 @@ android {
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
// 앱(:app)이 Watch Face Push 로 같이 설치하려면 "<앱 패키지>.watchfacepush.<이름>" 이어야 한다
|
||||
applicationId = "kr.o2o.nalssigak.watchfacepush.skin"
|
||||
applicationId = "kr.o2o.nalssigak.watchface"
|
||||
// WFF 버전 2 는 Wear OS 5(API 34)부터
|
||||
minSdk = 34
|
||||
targetSdk = 34
|
||||
versionCode = providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get().toInt()
|
||||
versionCode = 1
|
||||
versionName = "0.1"
|
||||
}
|
||||
// 스킨 APK 엔 dex 가 없어야 한다 (Play 번들, 앱에 싣는 Watch Face Push 둘 다). R8 이 R 클래스까지 다 걷어내게
|
||||
buildTypes.all {
|
||||
buildTypes.getByName("release") {
|
||||
// 스킨 번들엔 dex 가 없어야 한다. R8 이 R 클래스까지 다 걷어내게
|
||||
isMinifyEnabled = true
|
||||
// 스킨 XML 이 이름으로만 부르는 아이콘·글꼴을 안 쓰는 걸로 보고 지운다. 켜지 말 것
|
||||
isShrinkResources = false
|
||||
|
||||
@@ -117,19 +117,21 @@ 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_text():
|
||||
"""해 구슬 위 1위 점수·이름. 날씨 칸 값: 값 = 날씨 코드 × 1000 + 1위 점수, 제목 = 1위 이름 (1위가 없으면 빈 제목)"""
|
||||
def orb_slot():
|
||||
x, y = CX - ORB // 2, CY - ORB // 2
|
||||
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 = 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}
|
||||
</Compare>
|
||||
</Condition>'''
|
||||
</Complication>
|
||||
<Complication type="SHORT_TEXT">
|
||||
{body}
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>'''
|
||||
|
||||
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):
|
||||
@@ -180,11 +182,10 @@ def chip(x, w, icon, expr):
|
||||
{text(x + 32, CHIP_Y + 5, w - 38, 30, "jua", 21, INK, expr, amb=True)}'''
|
||||
|
||||
def precip_slot():
|
||||
"""화면 전체를 덮는 숨은 칸. WFF 는 칸이 8개까지라 날씨와 1위를 이 칸 하나로 받는다.
|
||||
날씨각 앱(RainComplicationService)이 값 = 날씨 코드 × 1000 + 1위 점수, 글자 = 기온, 제목 = 1위 이름을 준다.
|
||||
날씨 코드 1(비·곧 비)이면 빗줄기와 비구름, 2(천둥)면 빗줄기와 번개 구름, 3(눈)이면 눈송이와 눈구름을 가운데 해 자리에 그리고,
|
||||
그 위에 1위 점수·이름, 아래에 기온 칩을 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다.
|
||||
터치는 가운데 구슬만 받는다(누르면 앱). 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다."""
|
||||
"""화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면
|
||||
아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기와 비구름, "천둥 쳐요"면 빗줄기와 번개 구름,
|
||||
"눈 와요"면 눈송이와 눈구름을 가운데 해 자리에 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다.
|
||||
터치는 막지 않게 BoundingOval 을 1px 로 둔다. 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다."""
|
||||
import random
|
||||
r = random.Random(7)
|
||||
drops, flakes = [], []
|
||||
@@ -206,16 +207,15 @@ 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>'
|
||||
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">
|
||||
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">
|
||||
<Condition>
|
||||
<Expressions>
|
||||
<Expression name="thunder"><![CDATA[{mode} == 2]]></Expression>
|
||||
<Expression name="rain"><![CDATA[{mode} == 1]]></Expression>
|
||||
<Expression name="snow"><![CDATA[{mode} == 3]]></Expression>
|
||||
<Expression name="thunder"><![CDATA[[COMPLICATION.TITLE] == "천둥 쳐요"]]></Expression>
|
||||
<Expression name="rain"><![CDATA[[COMPLICATION.TITLE] == "비 와요" || [COMPLICATION.TITLE] == "곧 비"]]></Expression>
|
||||
<Expression name="snow"><![CDATA[[COMPLICATION.TITLE] == "눈 와요"]]></Expression>
|
||||
<Expression name="night"><![CDATA[{NIGHT_EXPR}]]></Expression>
|
||||
</Expressions>
|
||||
<Compare expression="thunder">
|
||||
@@ -235,8 +235,8 @@ def precip_slot():
|
||||
</Compare>
|
||||
{sun_or_moon()}
|
||||
</Condition>
|
||||
{chip(CX - 52, 104, "thermo", "[COMPLICATION.TEXT]")}
|
||||
{orb_text()}
|
||||
{chip(108, 104, "thermo", "[COMPLICATION.TEXT]")}
|
||||
{chip(220, 122, "umbrella", "[COMPLICATION.TITLE]")}
|
||||
</Complication>
|
||||
<Complication type="EMPTY">
|
||||
<Condition>
|
||||
@@ -273,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"/>
|
||||
@@ -293,6 +293,7 @@ xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- 가운데 해·달·구름은 날씨 칸 안에서 비 막 위에 그린다 -->
|
||||
{precip_slot()}
|
||||
{clock("#FFFFFFFF", ambient_visible=True)}
|
||||
{orb_slot()}
|
||||
{"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))}
|
||||
{event_slot()}
|
||||
</Scene>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?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="450" height="450">
|
||||
<Metadata key="CLOCK_TYPE" value="DIGITAL"/>
|
||||
@@ -148,15 +148,15 @@
|
||||
</Condition>
|
||||
<!-- 주의: 칸(ComplicationSlot) 순서·slotId 를 바꿔 덮어 설치하면 기존 기기에서 공급원이 한 칸씩 밀린다 (에뮬레이터에서 확인). 새 칸은 맨 뒤에 붙인다 -->
|
||||
<!-- 가운데 해·달·구름은 날씨 칸 안에서 비 막 위에 그린다 -->
|
||||
<ComplicationSlot slotId="7" x="0" y="0" width="450" height="450" displayName="slot_precip" supportedTypes="RANGED_VALUE EMPTY" isCustomizable="FALSE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.RainComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="450" height="450"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
<ComplicationSlot slotId="7" x="0" y="0" width="450" height="450" displayName="slot_precip" supportedTypes="SHORT_TEXT EMPTY" isCustomizable="FALSE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.RainComplicationService" primaryProviderType="SHORT_TEXT"/>
|
||||
<BoundingOval x="0" y="0" width="1" height="1"/>
|
||||
<Complication type="SHORT_TEXT">
|
||||
<Condition>
|
||||
<Expressions>
|
||||
<Expression name="thunder"><![CDATA[floor([COMPLICATION.RANGED_VALUE_VALUE] / 1000) == 2]]></Expression>
|
||||
<Expression name="rain"><![CDATA[floor([COMPLICATION.RANGED_VALUE_VALUE] / 1000) == 1]]></Expression>
|
||||
<Expression name="snow"><![CDATA[floor([COMPLICATION.RANGED_VALUE_VALUE] / 1000) == 3]]></Expression>
|
||||
<Expression name="thunder"><![CDATA[[COMPLICATION.TITLE] == "천둥 쳐요"]]></Expression>
|
||||
<Expression name="rain"><![CDATA[[COMPLICATION.TITLE] == "비 와요" || [COMPLICATION.TITLE] == "곧 비"]]></Expression>
|
||||
<Expression name="snow"><![CDATA[[COMPLICATION.TITLE] == "눈 와요"]]></Expression>
|
||||
<Expression name="night"><![CDATA[[HOUR_0_23] < 5 || [HOUR_0_23] >= 21]]></Expression>
|
||||
</Expressions>
|
||||
<Compare expression="thunder">
|
||||
@@ -495,24 +495,22 @@
|
||||
<Ellipse x="16" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse><Ellipse x="97" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse>
|
||||
</PartDraw></Default>
|
||||
</Condition>
|
||||
<PartDraw x="173" y="366" width="104" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<PartDraw x="108" y="366" width="104" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<RoundRectangle x="0" y="0" width="104" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="#B8FFFFFF"/></RoundRectangle>
|
||||
<RoundRectangle x="0" y="35" width="104" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartImage x="181" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_thermo"/></PartImage>
|
||||
<PartText x="205" y="371" width="66" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<PartImage x="116" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_thermo"/></PartImage>
|
||||
<PartText x="140" y="371" width="66" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FF28304A"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
<Condition>
|
||||
<Expressions><Expression name="ranked"><![CDATA[[COMPLICATION.TITLE] != ""]]></Expression></Expressions>
|
||||
<Compare expression="ranked">
|
||||
<PartText x="157" y="209" width="136" height="61">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="round([COMPLICATION.RANGED_VALUE_VALUE] % 1000)"/></Template></Font></Text>
|
||||
</PartText><PartText x="171" y="268" width="108" height="28">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
<PartDraw x="220" y="366" width="122" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<RoundRectangle x="0" y="0" width="122" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="#B8FFFFFF"/></RoundRectangle>
|
||||
<RoundRectangle x="0" y="35" width="122" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartImage x="228" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_umbrella"/></PartImage>
|
||||
<PartText x="252" y="371" width="84" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FF28304A"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Compare>
|
||||
</Condition>
|
||||
</Complication>
|
||||
<Complication type="EMPTY">
|
||||
<Condition>
|
||||
@@ -537,6 +535,25 @@
|
||||
<Font family="bagel_fat_one" size="68" color="#FFFFFFFF"/>
|
||||
</TimeText>
|
||||
</DigitalClock>
|
||||
<ComplicationSlot slotId="0" x="157" y="184" width="136" height="136" displayName="slot_rank1" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank1ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="136" height="136"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
<PartText x="0" y="25" width="136" height="61">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText><PartText x="14" y="84" width="108" height="28">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="SHORT_TEXT">
|
||||
<PartText x="0" y="25" width="136" height="61">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText><PartText x="14" y="84" width="108" height="28">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>
|
||||
<ComplicationSlot slotId="1" x="71" y="149" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank2ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="68" height="68"/>
|
||||
|
||||
Reference in new issue
Block a user