Merge remote-tracking branch 'origin/main' into feat/apps-in-toss

This commit is contained in:
minaChoi committed 2026-10-26 15:46:15 +09:00
commit 0a84f34729
164 files changed
+23161 -4535

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
---
description: 날씨각(weather.o2o.kr) 구글·네이버 검색 노출 매일 점검 + 다음 할 일 제안
---
weather.o2o.kr 검색 노출을 점검하고, 어제와 비교해 다음 할 일을 제안한다.
## 1. 검색어
날씨각 · 오늘 날씨 · 분당구 오늘 날씨 · 분당 날씨 · 성남 오늘 날씨 · 마포구 오늘 날씨 · 마포구 날씨 · 강남구 오늘 날씨 · 세차하기 좋은 날 · 빨래하기 좋은 날 · 오늘 노을 시간 · 이번 주말 날씨 · 세차각
$ARGUMENTS 가 있으면 위 목록에 더한다.
## 2. 구글 (Chrome 확장)
- google.com 탭을 하나 열고, 그 탭에서 `fetch('/search?hl=ko&gl=kr&num=20&q=…')`로 검색어마다 결과 HTML을 받는다. 요청 사이 1.5초 쉰다.
- `a h3`의 링크를 순서대로 모아 google 도메인을 빼고, 같은 호스트는 한 번만 센다. weather.o2o.kr이 몇 번째 사이트인지, 어느 주소·제목으로 잡혔는지 적는다.
- '날씨각' 결과는 사이트 이름(링크 위 이름)도 적는다. 지금은 '에이아이오투오'로 나온다.
- `site:weather.o2o.kr` 결과의 주소 목록도 적는다.
- 끝나면 연 탭을 닫는다.
## 3. 네이버 (curl)
- 브라우저 UA로 `https://search.naver.com/search.naver?query=…`를 받는다. 요청 사이 3초 이상 쉰다.
- 응답이 30KB 안팎이고 본문이 비어 있으면 네이버가 막은 것이다. 그 검색어는 "차단"으로 적고 다시 시도하지 않는다.
- 외부 링크 호스트를 순서대로 중복 없이 세서 weather.o2o.kr 순서를 적는다(http/https 같은 사이트는 하나로).
- `query=site:weather.o2o.kr&where=web`으로 색인된 주소 목록을 적는다.
## 4. 기록
- `docs/검색노출_기록.md` 표 맨 아래에 오늘 날짜 행을 더한다. 형식은 파일 안 표를 따른다.
- 어제 행과 비교해 바뀐 것(새로 잡힘·빠짐·순위 변화·색인 주소 수)을 뽑는다.
## 5. 다음 할 일 제안
- 근거는 공식 문서만 쓴다: `docs/구글_검색_정책_리서치.md`, 구글 Search Central, 네이버 서치어드바이저 가이드. 문서에 없는 건 "문서에 없음"이라 쓰고, 판단·추정은 따로 표시한다.
- 같은 페이지를 매일 수집 요청하지 않는다(네이버: 반영에 1일~몇 주, 매일 반복 불필요).
- 바꾼 뒤 결과는 몇 주 단위로 본다(구글: 변경 반영에 몇 시간~몇 달). 하루 변화로 원인을 단정하지 않는다.
- 코드·문구 수정이 필요하면 고치지 말고 제안만 하고, 결정이 필요한 건 `TODO.md`에 적는다.
## 6. 보고 (채팅, 짧게)
- 바뀐 것 3줄 이내
- 검색어별 구글/네이버 순서 (없음·차단 포함)
- 다음 할 일 1~3개 (근거 출처 포함)
+14
View File
@@ -0,0 +1,14 @@
# 저장소 루트를 빌드 대상으로 쓰는 건 frontend 이미지뿐이라 frontend·shared·루트 package 파일만 넘긴다
*
!package.json
!package-lock.json
!frontend
!shared
!mobile/package.json
**/node_modules
**/dist
**/*.log
**/.DS_Store
**/dist-toss
**/*.ait
**/.env.toss
+5
View File
@@ -13,6 +13,11 @@ INSTAGRAM_USER_ID=
# 인스타가 카드 이미지를 받아 갈 공개 주소
PUBLIC_BASE_URL=https://weather.o2o.kr
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
# 오늘 화면 쇼츠 줄 (YouTube Data API v3 키, console.cloud.google.com/apis/credentials 에서 발급·YouTube Data API v3 만 허용).
# 비우면 채널 쇼츠를 자동으로 못 받고 YOUTUBE_SHORTS(영상 ID, 쉼표로 구분, 최신순)만 보여 준다. 둘 다 비우면 기본값(영상 3개)
YOUTUBE_API_KEY=
YOUTUBE_CHANNEL_ID=UCWdesmwvHFsnjMUWNcDaA9w
YOUTUBE_SHORTS=
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
DB_HOST=localhost
+3
View File
@@ -4,6 +4,9 @@
.env.*
!.env.example
# npm workspaces 의존성 (frontend·mobile·shared 가 루트 하나를 같이 쓴다)
node_modules/
# Python 바이트코드/캐시
__pycache__/
*.py[cod]
+48
View File
@@ -59,6 +59,10 @@
| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` |
| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | |
| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | |
| [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` |
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
| [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` |
| [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | |
| [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | |
| [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | |
@@ -294,3 +298,47 @@
| [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` |
| [x] | 10/25 건강·운동 타로(킹서버 카드 7→포스트 3960, 인스타 https://www.instagram.com/p/De5iLg4AS_M/)·꾸안꾸 코디는 처음 올린 카드 8→포스트 3961(인스타 De58VfXINy0)이 40대~ 옷이 20-30대와 같아 숨기고, 40대~ 옷을 새로 써서 카드 9→포스트 3962(인스타 De5-8gboL-c)로 재게시했으나 40대 여자 그림에 롱가디건이 끼고 전체가 여름 옷으로 보여 다시 숨김. 일교차 8도 이상이면 겉옷을 5번째 옷으로 넣게 고쳐 카드 10→포스트 3963(인스타 De6B2gwIMXF)으로 올렸으나 그림 배치와 이름표 자리가 어긋나 숨김. 프롬프트에 옷 자리를 적고 다시 그려 카드 11→포스트 3964, 인스타 https://www.instagram.com/p/De6JRIkoKbT/ 로 최종 게시. 07:52 예약(세션 크론)이 세션 종료로 안 돌아 09:46 수동 실행. 코디는 사용자 결정으로 사람 구분을 20-30대·40대~ 4장으로 바꿈(f30·m30 그림 파일 8장은 남아 있으나 미사용). 새 그림 8장(러닝각·자전거각·warm 꾸안꾸 6) | 사용자 요청 (10/24) | `admin/image-prompts/ootd.json`, `admin/scripts/card.mjs` |
## 앱(React Native) 마이그레이션
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [x] | 1단계: 웹·앱 공통 코드 `shared/`(`@nalssigak/shared`) 분리, 루트 npm workspaces, 웹 Docker 빌드 대상을 루트로 | 앱과 API 클라이언트·로직 공유 | `package.json`, `shared/`, `frontend/Dockerfile`, `compose.yaml`, `.dockerignore` |
| [x] | 2단계: 앱에 react-query·Uniwind 설정 + Metro가 `react`를 `mobile/node_modules`(19.2.3) 것만 쓰게 설정 — 루트에는 웹용 react 19.3.0이 있고 RN 렌더러는 19.2.3에서만 돌아감 | 앱 시작 준비 | `mobile/metro.config.js`, `mobile/src/app/_layout.tsx`, `mobile/src/lib/query-client.ts` |
| [x] | 앱 토큰 저장소 `expo-secure-store`로 `configureApi` 연결, API 주소는 `EXPO_PUBLIC_API_BASE_URL` | 웹은 localStorage | `mobile/src/lib/api.ts`, `mobile/.env.example` |
| [x] | 안드로이드 에뮬레이터(Expo Go)에서 확인: 오늘 화면 실데이터, 위치 권한 창, 탭 이동, 각 근거 시트 | | `mobile/` |
| [x] | 안드로이드 개발 빌드에서 가입·로그인(아바타 표시)·좋아요·이미지 공유·위치로 지역 찾기 확인 | | `mobile/` |
| [ ] | 안드로이드 댓글 쓰기·내 정보 바꾸기·로그아웃 확인 | 아직 안 눌러 봄 | `mobile/src/components/sheets/` |
| [x] | 출시 빌드 설정: `eas.json`(production 은 운영 API·사이트 주소, 빌드 번호 자동 증가), iOS 수출 규정 암호화 없음, 안드로이드 권한은 대략 위치만(정밀 위치·저장소·다른 앱 위에 그리기 뺌) | | `mobile/eas.json`, `mobile/app.json` |
| [ ] | 출시 빌드 전 준비(사용자): Apple Developer·Google Play Console·Expo 계정, 스토어 스크린샷·설명·데이터 안전 양식 | 서명·제출에 필요 | |
| [x] | 회원 탈퇴(스토어 심사 필수): `DELETE /v1/auth/me` — 계정·댓글·좋아요·저장 모두 삭제, 게시물·댓글 수 맞춤. 웹·앱 내 정보 시트 '탈퇴하기'(한 번 더 확인) | Apple 5.1.1(v), Google Play 계정 삭제 정책 | `backend/crud/user_crud.py`, `backend/services/auth_service.py`, `frontend/src/b/Sheets.tsx`, `mobile/src/components/sheets/me.tsx` |
| [ ] | 운영 배포 때 탈퇴 API 같이 나감 — 배포 전 웹 내 정보 시트 '탈퇴하기' 화면 확인 (앱은 안드로이드에서 확인, 웹은 빌드·린트만) | | `frontend/src/b/Sheets.tsx` |
| [ ] | 백엔드 테스트 3개가 날짜 때문에 실패 (10/19): `test_feed`(제철 각 수 42≠40), `test_watch`, `test_weather_today`(10월 하순 18시가 일몰 뒤라 'sunset' 아이콘 아님) — 탈퇴 작업과 무관 | 기대값을 날짜에 안 묶이게 고쳐야 함 | `backend/tests/` |
| [ ] | Xcode 설치 후 iOS 시뮬레이터에서 전체 확인 | | `mobile/` |
| [x] | 안드로이드 개발 빌드(`expo run:android`) 설치 확인: 홈 화면 해 아이콘·'날씨각' 이름, 실데이터 화면 | | `mobile/` |
| [x] | 앱 ID: 안드로이드 패키지 `kr.o2o.nalssigak` — Play Console 기존 '날씨각'(Wear OS 트랙에 워치 앱 있음)에 휴대전화 앱으로 추가하려면 패키지명이 같아야 함. iOS 번들 ID는 미정 | 스토어에 올리면 못 바꿈 | `mobile/app.json` |
| [x] | Play 제출: 휴대전화 versionCode 1000부터 (10/23 `app.json` versionCode 1000, 로컬 빌드)(워치가 1 사용) — `eas login` 후 `eas build:version:set -p android` | 같은 앱 안에서 versionCode 겹치면 안 됨 | `mobile/eas.json` |
| [x] | Play 제출: 워치 앱과 같은 업로드 키 (10/23 로컬 빌드로 서명 확인, SHA-1 D3:51…44:79. 비밀번호는 ~/.gradle/gradle.properties `NALSSIGAK_UPLOAD_*`)(.jks)를 `eas credentials -p android`로 등록 (사용자: 키 파일·비밀번호 준비, 분실 시 Play Console에서 업로드 키 재설정) | EAS는 안 넣으면 새 키를 만듦 | |
| [ ] | 출시 aab 서명 설정이 생성 폴더 `mobile/android/app/build.gradle`에만 있음 — `expo prebuild --clean` 하면 지워지니 다시 넣거나 config plugin으로 옮기기 | `android/`는 gitignore·재생성 | `mobile/android/app/build.gradle` |
| [ ] | 앱 구글 로그인 기기 확인: 네이티브 다시 빌드 → 구글 계정 로그인된 에뮬레이터(Play 서비스 이미지)에서 구글로 계속하기 | 새 네이티브 모듈이라 지금 설치된 개발 빌드엔 없음. Android 클라이언트(개발·Play SHA-1)는 콘솔에 등록됨 | `mobile/src/components/sheets/google.tsx` |
| [ ] | 운영 서버 `.env`에 `GOOGLE_CLIENT_ID`(웹 클라이언트 ID) 넣고 구글 로그인 백엔드 배포 | 비어 있으면 `/v1/auth/config`가 ID를 안 줘서 앱·웹 구글 버튼이 숨음 | `backend/config/settings.py` |
| [ ] | Play 제출(사용자): 휴대전화 스크린샷 2장+, 개인정보처리방침 URL, 계정 삭제 URL(웹 '탈퇴하기' 운영 배포 후), 데이터 보안 양식(대략 위치·계정 정보·댓글), 콘텐츠 등급, 앱 액세스용 심사 테스트 계정. 개인 계정(2023.11 이후)이면 비공개 테스트 12명·14일 | | |
| [x] | Play UGC 정책(댓글): 처음 댓글 쓸 때 이용약관 동의(`POST /v1/auth/terms`), 남의 댓글 ⋯ → 신고(이유 4가지, 신고한 사람에겐 바로 숨김, 3건이면 모두에게 숨김) / 이 사람 차단, 내 정보 '차단한 사람'·풀기, 운영 조치 `scripts/moderate.py`(숨김·되살림·정지), 탈퇴 때 신고·차단도 삭제 | Play 'User Generated Content' 정책 | `backend/`, `frontend/src/b/Sheets.tsx`, `frontend/public/terms.html`, `mobile/src/components/sheets/` |
| [ ] | 운영 DB 반영: `init.sql`의 `users.terms_agreed_at`, `comment.report_count`·`is_hidden`, `comment_report`, `user_block` (ALTER·CREATE IF NOT EXISTS) — 코드 배포 전에 먼저 | 새 코드가 이 칼럼을 읽음 | `backend/postgres-init/init.sql` |
| [ ] | **[검토 필요]** 이용약관 초안 문구 검토 | 법무 문구라 확인 필요 | `frontend/public/terms.html` |
| [ ] | 개인정보처리방침에 휴대전화 앱·댓글·신고·차단 기록 추가 (지금은 웹·워치 앱만 적혀 있음) | Play 데이터 보안 양식과 맞아야 함 | `frontend/public/privacy.html` |
| [x] | 앱 신고·차단·약관 화면 안드로이드 확인: ⋯ 메뉴, 차단 확인·안내·목록에서 빠짐, 약관 동의 후 바로 게시, 내 정보 '차단한 사람' 풀기 (신고 흐름은 백엔드 테스트로만). 새 패키지 `kr.o2o.nalssigak` 개발 빌드로 다시 설치함 | | `mobile/` |
| [ ] | 오늘 날씨 칸(3시·6시 등)이 '?' — 백엔드가 며칠 꺼져 있다 켜지면 최신 발표(예: 8시, 9시부터 예보)만 받아 새벽 칸 행이 없음. 0시 재수신(`_midnight_missing`)은 0시에 묵은 값이 있으면 안 돎. 운영은 늘 켜져 있어 드묾 — 고칠 땐 오늘 칸 중 비거나 묵은 칸이 있으면 다시 받기 | 10/19 로컬(9811)에서 확인, 앱·웹 버그 아님 | `backend/services/weather_service.py` (`today`, `ensure_vilage`, `_midnight_missing`) |
| [x] | 앱 아이콘 3D 해 그림(600px 원본)으로: iOS 1024, 안드로이드 적응형(앞·뒤·단색), 스플래시. Expo Go 에선 안 보이고 개발 빌드부터 보임. 스토어용으로는 1024px 이상 원본이 있으면 더 선명 | | `mobile/assets/images/` |
| [x] | 3단계-1: 탭 5개 구조·위 막대·하늘 배경·밤 테마(Uniwind dark), Today 히어로·각 순위·행사/TOP5/계절 띠 | | `mobile/src/app/`, `mobile/src/components/` |
| [x] | Today 게시물 카드(슬라이드 7종·넘기기·좋아요·댓글·텍스트 공유), 3·6·9번째 글 뒤 띠 | | `mobile/src/components/post/`, `mobile/src/app/index.tsx` |
| [x] | 시트 7종(각 근거·읽을거리·댓글·이번 주 특집·로그인/가입·내 정보·지역 고르기)을 RN `Modal`로, 위 막대 로그인/아바타 | 새 패키지 없이 | `mobile/src/components/sheets/`, `mobile/src/components/top-bar.tsx` |
| [x] | 고른 지역 저장 (SecureStore) | | `mobile/src/lib/region.tsx` |
| [x] | 위치로 지역 찾기(`expo-location`): 처음 켠 사람은 가장 가까운 구로, 지역 시트 '지금 위치로 찾기' | 웹과 같게 | `mobile/src/lib/region.tsx`, `mobile/src/components/sheets/region.tsx` |
| [x] | 움직임: 해·구름 떨어지기/둥둥, 비·눈, 스켈레톤 깜빡임, 첫 로딩 덮개, 하늘색 서서히 바뀜, 밤 별 반짝임 ('동작 줄이기' 켜면 멈춤) | | `mobile/src/components/today/hero.tsx`, `first-load.tsx`, `sky-bg.tsx` |
| [x] | 나머지 탭(각·노을·주말·행사·계절·상식) 옮기기 | | `mobile/src/app/`, `mobile/src/components/{gak,sky,week,season}/` |
| [x] | 이미지로 공유(`react-native-view-shot` + `expo-sharing`): 게시물은 보고 있는 슬라이드, 주말은 고른 날 추천 카드 | 웹 스토리 이미지(머리말·주소 붙인 9:16)와는 다름 | `mobile/src/lib/share-image.ts` |
| [x] | 웹과 다른 작은 것들 맞춤: 좋아요 튀는 하트·토스트, 밤 별똥별, 단풍잎 떨어짐, 시 구절 고운바탕, 실패·빈 안내 높이 유지(hold), 시트 배경은 제자리 페이드 | | `mobile/src/` |
| [ ] | 공유 이미지를 웹처럼 9:16 스토리(머리말·사이트 주소)로 — 지금은 화면 그대로 찍음. 좋아요 효과는 카드 안에만 뜸(RN에 portal 없음) | 남은 차이 | `mobile/src/lib/share-image.ts`, `mobile/src/components/post/` |
| [x] | `mobile/` 템플릿 예제 화면·`.vscode`·`LICENSE`·README 지움, `AGENTS.md`·`.claude`는 둠 | 사용자 결정 | `mobile/` |
| [ ] | `frontend-dev` 개발 컨테이너 실제로 띄워 확인 (이미지 빌드만 확인, 5173이 사용 중이라 실행은 못 함) | 볼륨 경로 바뀜 | `compose.yaml` |
| [ ] | 운영 서버가 git pull 뒤 루트 `package-lock.json`으로 빌드되는지 배포 때 확인 | 빌드 대상이 `./frontend` → `.` | `deploy.sh`, `compose.yaml` |
+20 -6
View File
@@ -360,6 +360,7 @@ class User(Base):
color: Mapped[str] = mapped_column(String(20), default="orange")
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
status: Mapped[int] = mapped_column(SmallInteger, default=1)
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
@@ -400,10 +401,29 @@ class Comment(Base):
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
body: Mapped[str] = mapped_column(String(60))
like_count: Mapped[int] = mapped_column(Integer, default=0)
report_count: Mapped[int] = mapped_column(Integer, default=0)
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
class CommentReport(Base):
__tablename__ = "comment_report"
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
reason: Mapped[int] = mapped_column(SmallInteger)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class UserBlock(Base):
__tablename__ = "user_block"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class CommentLike(Base):
__tablename__ = "comment_like"
@@ -472,9 +492,3 @@ class TalkReport(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class UserBlock(Base):
__tablename__ = "user_block"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+8
View File
@@ -25,6 +25,7 @@ class ErrorType(Enum):
AUTH_FAILED = 4002
AUTH_DUPLICATE_ID = 4003
AUTH_TOKEN_INVALID = 4004
TERMS_REQUIRED = 4005
class Sky(CodeEnum):
@@ -192,3 +193,10 @@ class AuthProvider(CodeEnum):
LOCAL = 1
GOOGLE = 2
TOSS = 3
class ReportReason(CodeEnum):
ABUSE = 1
AD = 2
PRIVACY = 3
OTHER = 4
+5
View File
@@ -51,6 +51,11 @@ class Settings(BaseSettings):
azure_blob_base_url: str = ""
azure_blob_sas_token: str = ""
# 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다
youtube_api_key: str = ""
youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w"
youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM"
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
google_client_id: str = ""
+62 -10
View File
@@ -2,13 +2,15 @@ import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import delete, func, select, update
from sqlalchemy import delete, func, or_, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, Post, PostLike, PostLikeAnon, PostSave, User
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, CommentReport, Post, PostLike, PostLikeAnon, PostSave, User, UserBlock
from common.liker import Liker
HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
@@ -52,9 +54,16 @@ class ReactionCRUD:
stmt = stmt.where(Post.post_id < cursor)
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다."""
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다. 숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(
Comment.post_id == post_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)
)
if viewer is not None:
stmt = stmt.where(
Comment.comment_id.not_in(select(CommentReport.comment_id).where(CommentReport.user_id == viewer)),
or_(Comment.user_id.is_(None), Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer))),
)
if cursor is not None:
stmt = stmt.where(Comment.comment_id > cursor)
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
@@ -81,18 +90,61 @@ class ReactionCRUD:
owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash))
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
.values(deleted=True).returning(Comment.post_id)
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
)
post_id = res.scalar()
if post_id is None:
row = res.first()
if row is None:
return False
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
# 숨긴 댓글은 이미 댓글 수에서 빠져 있다
if not row.is_hidden:
await s.execute(update(Post).where(Post.post_id == row.post_id).values(comment_count=Post.comment_count - 1))
return True
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))
if exists is None:
return None
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
async def comment_author(self, s: AsyncSession, comment_id: int):
"""지금 보이는 댓글이면 (comment_id, user_id) 행, 없으면 None. 로그인 없이 쓴 댓글은 user_id 가 None."""
return (await s.execute(select(Comment.comment_id, Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))).first()
async def report_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, reason: int) -> None:
"""같은 사람이 두 번 신고해도 한 번만 센다. HIDE_AT 건이 되면 숨기고 댓글 수에서 뺀다."""
res = await s.execute(insert(CommentReport).values(comment_id=comment_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(CommentReport.comment_id))
if res.first() is None:
return
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(report_count=Comment.report_count + 1))
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, Comment.report_count >= HIDE_AT, Comment.is_hidden.is_(False), Comment.deleted.is_(False))
.values(is_hidden=True).returning(Comment.post_id)
)
post_id = res.scalar()
if post_id is not None:
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
async def set_hidden(self, s: AsyncSession, comment_id: int, hidden: bool) -> bool:
"""운영자가 댓글을 숨기거나 되살린다. 실제로 바뀌었을 때만 댓글 수를 고친다."""
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, Comment.is_hidden.is_(not hidden), Comment.deleted.is_(False))
.values(is_hidden=hidden).returning(Comment.post_id)
)
post_id = res.scalar()
if post_id is None:
return False
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + (-1 if hidden else 1)))
return True
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
async def unblock(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> bool:
res = await s.execute(delete(UserBlock).where(UserBlock.user_id == user_id, UserBlock.blocked_id == blocked_id).returning(UserBlock.blocked_id))
return res.first() is not None
async def blocked(self, s: AsyncSession, user_id: uuid.UUID) -> list[User]:
stmt = select(User).join(UserBlock, UserBlock.blocked_id == User.user_id).where(UserBlock.user_id == user_id).order_by(UserBlock.created_at.desc())
return list((await s.scalars(stmt)).all())
+29 -2
View File
@@ -1,11 +1,12 @@
import uuid
from collections import Counter
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import select
from sqlalchemy import delete, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import User
from common.database.model.models import Comment, CommentLike, CommentReport, Post, PostLike, PostSave, User, UserBlock
class UserCRUD:
@@ -46,3 +47,29 @@ class UserCRUD:
user.updated_at = datetime.now(timezone.utc)
await s.flush()
return user
async def agree_terms(self, s: AsyncSession, user_id: uuid.UUID) -> None:
await s.execute(update(User).where(User.user_id == user_id, User.terms_agreed_at.is_(None)).values(terms_agreed_at=datetime.now(timezone.utc)))
async def withdraw(self, s: AsyncSession, user_id: uuid.UUID) -> None:
"""계정과 그 사람이 남긴 좋아요·저장·댓글·신고·차단을 모두 지우고, 게시물·댓글에 쌓인 수를 그만큼 줄인다."""
liked_posts = (await s.scalars(delete(PostLike).where(PostLike.user_id == user_id).returning(PostLike.post_id))).all()
if liked_posts:
await s.execute(update(Post).where(Post.post_id.in_(liked_posts)).values(like_count=Post.like_count - 1))
liked_comments = (await s.scalars(delete(CommentLike).where(CommentLike.user_id == user_id).returning(CommentLike.comment_id))).all()
if liked_comments:
await s.execute(update(Comment).where(Comment.comment_id.in_(liked_comments)).values(like_count=Comment.like_count - 1))
await s.execute(delete(PostSave).where(PostSave.user_id == user_id))
reported = (await s.scalars(delete(CommentReport).where(CommentReport.user_id == user_id).returning(CommentReport.comment_id))).all()
if reported:
await s.execute(update(Comment).where(Comment.comment_id.in_(reported)).values(report_count=Comment.report_count - 1))
await s.execute(delete(UserBlock).where((UserBlock.user_id == user_id) | (UserBlock.blocked_id == user_id)))
mine = (await s.execute(delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.deleted, Comment.is_hidden))).all()
if mine:
ids = [c for c, _, _, _ in mine]
await s.execute(delete(CommentLike).where(CommentLike.comment_id.in_(ids)))
await s.execute(delete(CommentReport).where(CommentReport.comment_id.in_(ids)))
# 이미 지웠거나 숨긴 댓글은 댓글 수에서 빠져 있다
for post_id, n in Counter(p for _, p, deleted, hidden in mine if not deleted and not hidden).items():
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - n))
await s.execute(delete(User).where(User.user_id == user_id))
+23 -18
View File
@@ -218,6 +218,7 @@ CREATE TABLE IF NOT EXISTS public.users (
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
mood VARCHAR(20) NULL, -- 오늘 기분: clear·partly·cloudy·rain·thunder·snow·fog·rainbow. NULL = 안 고름
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
terms_agreed_at TIMESTAMPTZ NULL, -- 이용약관 동의 시각. NULL 이면 댓글을 못 쓴다
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
@@ -266,16 +267,28 @@ ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
-- 댓글 신고 (보류)
-- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
-- ALTER TABLE public.comment ADD COLUMN is_hidden BOOLEAN NOT NULL DEFAULT FALSE;
-- CREATE TABLE IF NOT EXISTS public.comment_report (
-- comment_id BIGINT NOT NULL,
-- user_id UUID NOT NULL,
-- reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
-- PRIMARY KEY (comment_id, user_id)
-- );
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS is_hidden BOOLEAN NOT NULL DEFAULT FALSE; -- 신고 3건이면 숨김. 숨긴 댓글은 댓글 수에서 빠진다
-- 댓글 신고. 신고한 사람에게는 그 댓글이 바로 안 보인다
CREATE TABLE IF NOT EXISTS public.comment_report (
comment_id BIGINT NOT NULL,
user_id UUID NOT NULL,
reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (comment_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_comment_report_user ON public.comment_report (user_id);
-- 사용자 차단. 차단한 사람의 댓글·동네 이야기 글이 내게 안 보인다
CREATE TABLE IF NOT EXISTS public.user_block (
user_id UUID NOT NULL, -- 차단한 사람
blocked_id UUID NOT NULL, -- 차단당한 사람
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, blocked_id)
);
CREATE INDEX IF NOT EXISTS idx_user_block_blocked ON public.user_block (blocked_id);
CREATE TABLE IF NOT EXISTS public.comment_like (
comment_id BIGINT NOT NULL,
@@ -343,14 +356,6 @@ CREATE TABLE IF NOT EXISTS public.talk_report (
PRIMARY KEY (talk_id, user_id)
);
-- 이 사람 글 안 보기
CREATE TABLE IF NOT EXISTS public.user_block (
user_id UUID NOT NULL,
blocked_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, blocked_id)
);
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
-- 구 목록.
+2
View File
@@ -18,6 +18,7 @@ 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.shorts.shorts import router as shorts_router
from router.v1.sky.sky import router as sky_router
from router.v1.talk.talk import router as talk_router
from router.v1.watch.watch import router as watch_router
@@ -53,6 +54,7 @@ app.include_router(image_router)
app.include_router(seo_router)
app.include_router(card_router)
app.include_router(reel_router)
app.include_router(shorts_router)
class Res_Health(Res_WebPacketProtocol):
+16 -2
View File
@@ -11,14 +11,14 @@ from common.enums import AuthProvider, ErrorType
from common.logger import LOG
from common.models.errors import error_info
from config.settings import settings
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_TossUnlink
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_TossUnlink, Res_Withdraw
from services.auth_service import AuthService
router = APIRouter(prefix="/v1/auth", tags=["auth"])
def _me(u: User) -> Me:
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider))
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider), terms_agreed=u.terms_agreed_at is not None)
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
@@ -100,3 +100,17 @@ async def update_me(req: Req_UpdateMe, user: User = Depends(current_user), servi
if err is not ErrorType.SUCCESS:
return Res_Me(result=error_info(err))
return Res_Me(me=_me(updated))
@router.post("/terms", response_model=Res_Me, response_model_exclude_none=True, summary="이용약관 동의 (댓글 쓰기 전에 한 번)")
async def agree_terms(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Me:
err, updated = await service.agree_terms(user)
if err is not ErrorType.SUCCESS:
return Res_Me(result=error_info(err))
return Res_Me(me=_me(updated))
@router.delete("/me", response_model=Res_Withdraw, response_model_exclude_none=True, summary="탈퇴 (계정과 남긴 댓글·좋아요를 모두 지운다)")
async def withdraw(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Withdraw:
err = await service.withdraw(user)
return Res_Withdraw() if err is ErrorType.SUCCESS else Res_Withdraw(result=error_info(err))
+5
View File
@@ -48,6 +48,7 @@ class Me(WebPacketProtocol):
color: str
mood: Optional[str] = None
provider: AuthProvider
terms_agreed: bool = False
class Res_Auth(Res_WebPacketProtocol):
@@ -64,6 +65,10 @@ class Res_Logout(Res_WebPacketProtocol):
pass
class Res_Withdraw(Res_WebPacketProtocol):
pass
class Res_Me(Res_WebPacketProtocol):
me: Optional[Me] = None
+17 -1
View File
@@ -1,9 +1,10 @@
import uuid
from datetime import date, datetime
from typing import Optional
from pydantic import Field
from common.enums import PostType
from common.enums import PostType, ReportReason
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
@@ -58,3 +59,18 @@ class Res_Comment(Res_WebPacketProtocol):
class Res_CommentLike(Res_WebPacketProtocol):
liked: Optional[bool] = None
like_count: Optional[int] = None
class Req_Report(Req_WebPacketProtocol):
reason: ReportReason
class BlockedUser(WebPacketProtocol):
user_id: uuid.UUID
nickname: str
character: str
color: str
class Res_BlockedList(Res_WebPacketProtocol):
users: list[BlockedUser] = []
+27 -2
View File
@@ -1,3 +1,4 @@
import uuid
from typing import Optional
from fastapi import APIRouter, Depends, Path, Query
@@ -10,7 +11,8 @@ from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST
from router.v1.reaction.protocol import (
CommentData, Req_Comment, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave, Res_SavedList, SavedPost,
BlockedUser, CommentData, Req_Comment, Req_Report, Res_BlockedList, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave,
Res_SavedList, SavedPost,
)
from services.reaction_service import PAGE, CommentView, ReactionService
@@ -69,7 +71,7 @@ async def list_comments(
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)")
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)")
async def add_comment(
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
) -> Res_Comment:
@@ -95,3 +97,26 @@ async def like_comment(comment_id: int = Path(...), who: Liker = Depends(liker),
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
async def unlike_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
return await _clike(comment_id, who, False, service)
@router.post("/comment/{comment_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)")
async def report_comment(comment_id: int = Path(...), req: Req_Report = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.report_comment(comment_id, user, req.reason)))
@router.post("/comment/{comment_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임)")
async def block_author(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.block_author(comment_id, user)))
@router.get("/block/list", response_model=Res_BlockedList, response_model_exclude_none=True, summary="내가 차단한 사람")
async def list_blocked(user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_BlockedList:
err, users = await service.blocked(user)
if err is not ErrorType.SUCCESS:
return Res_BlockedList(result=error_info(err))
return Res_BlockedList(users=[BlockedUser(user_id=u.user_id, nickname=u.nickname, character=u.character, color=u.color) for u in users])
@router.delete("/block/{user_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="차단 풀기")
async def unblock(user_id: uuid.UUID = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.unblock(user, user_id)))
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
class ShortItem(WebPacketProtocol):
id: str # 유튜브 영상 ID
title: str
class Res_ShortList(Res_WebPacketProtocol):
items: list[ShortItem] = []
+16
View File
@@ -0,0 +1,16 @@
from fastapi import APIRouter, Depends
from common.enums import ErrorType
from common.models.errors import error_info
from router.v1.shorts.protocol import Res_ShortList, ShortItem
from services.shorts_service import ShortsService
router = APIRouter(prefix="/v1/shorts", tags=["shorts"])
@router.get("", response_model=Res_ShortList, response_model_exclude_none=True, summary="오늘 화면 쇼츠 줄: 날씨각 유튜브 채널의 쇼츠, 최신순")
async def list_shorts(service: ShortsService = Depends()) -> Res_ShortList:
err, items = await service.items()
if err is not ErrorType.SUCCESS:
return Res_ShortList(result=error_info(err))
return Res_ShortList(items=[ShortItem(**i) for i in items])
+8
View File
@@ -21,6 +21,7 @@ from services.external.culture_api import SIDO_NAME
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
from services.feed_service import build_feed_day, clear_feed_cache
from services.shorts_service import ShortsService
from services.week_service import collect_events, drop_known
from services.weekend_rank import WeekendRank
@@ -188,3 +189,10 @@ async def refresh_events(only_if_missing: bool = False) -> ErrorType:
LOG.error(f"[scheduler] refresh_events done mark: {e}")
LOG.info(f"[scheduler] refresh_events: {detail}")
return ErrorType.SUCCESS if ok else ErrorType.EXTERNAL_API_ERROR
async def refresh_shorts() -> ErrorType:
"""오늘 화면 쇼츠 줄 목록을 유튜브에서 새로 받아 둔다."""
err, items = await ShortsService().refresh()
LOG.info(f"[scheduler] refresh_shorts: {len(items)}개 {err.name}")
return err
+64
View File
@@ -0,0 +1,64 @@
"""운영자용 댓글·사용자 조치.
python scripts/moderate.py reports 신고 받은 댓글 (많은 순 30개)
python scripts/moderate.py hide <comment_id> 댓글 숨김
python scripts/moderate.py show <comment_id> 숨긴 댓글 되살림
python scripts/moderate.py suspend <login_id> 이용 정지 (로그인·토큰 막힘)
python scripts/moderate.py resume <login_id> 정지 풀기
"""
import asyncio
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy import select, update # noqa: E402
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
from common.database.model.models import Comment, User # noqa: E402
from common.enums import ErrorType # noqa: E402
from crud.reaction_crud import ReactionCRUD # noqa: E402
async def _reports(s):
stmt = (
select(Comment.comment_id, Comment.report_count, Comment.is_hidden, User.login_id, Comment.body)
.join(User, User.user_id == Comment.user_id)
.where(Comment.report_count > 0, Comment.deleted.is_(False))
.order_by(Comment.report_count.desc(), Comment.comment_id.desc())
.limit(30)
)
return (await s.execute(stmt)).all()
async def _set_status(s, login_id: str, status: int) -> bool:
res = await s.execute(
update(User).where(User.login_id == login_id, User.deleted.is_(False)).values(status=status, token_version=User.token_version + 1).returning(User.user_id)
)
return res.first() is not None
async def main(argv: list[str]) -> int:
if len(argv) < 1 or argv[0] not in {"reports", "hide", "show", "suspend", "resume"} or (argv[0] != "reports" and len(argv) != 2):
print(__doc__)
return 2
cmd = argv[0]
if cmd == "reports":
err, rows = await DB_SESSION_MNG.execute_lambda(_reports)
for comment_id, count, hidden, login_id, body in rows or []:
print(f"{comment_id}\t신고 {count}\t{'숨김' if hidden else '보임'}\t{login_id}\t{body}")
elif cmd in {"hide", "show"}:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: ReactionCRUD().set_hidden(s, int(argv[1]), cmd == "hide"))
print("바뀜" if ok else "그대로 (없는 댓글이거나 이미 그 상태)")
else:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: _set_status(s, argv[1], 2 if cmd == "suspend" else 1))
print("바뀜" if ok else "없는 아이디")
await DB_SESSION_MNG.stop()
if err is not ErrorType.SUCCESS:
print(err.name)
return 1
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main(sys.argv[1:])))
+10
View File
@@ -127,6 +127,16 @@ class AuthService:
"""이 사용자의 모든 기기 토큰을 무효로 만든다."""
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.update(s, user.user_id, {"token_version": user.token_version + 1})])
async def agree_terms(self, user: User) -> tuple[ErrorType, Optional[User]]:
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.agree_terms(s, user.user_id)])
if err is not ErrorType.SUCCESS:
return err, None
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, user.user_id))
async def withdraw(self, user: User) -> ErrorType:
"""탈퇴: 계정과 남긴 댓글·좋아요를 한 번에 지운다. 계정이 없어지니 가진 토큰도 바로 못 쓴다."""
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.withdraw(s, user.user_id)])
async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]:
"""닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다."""
values: dict = {}
+55
View File
@@ -0,0 +1,55 @@
import re
from typing import Optional
import httpx
# YouTube Data API v3 (API 키). 채널 업로드 목록 → 영상 정보로 쇼츠만 고른다
API_URL = "https://www.googleapis.com/youtube/v3"
# 키 없이 영상 제목만 받을 때
OEMBED_URL = "https://www.youtube.com/oembed"
SHORT_MAX_SEC = 180 # 쇼츠는 3분 이하
_DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$")
def seconds(iso: str) -> Optional[int]:
"""ISO 8601 길이("PT1M5S") → 초. 형식이 다르면 None."""
m = _DURATION.match(iso or "")
if not m:
return None
h, mi, s = (int(g or 0) for g in m.groups())
return h * 3600 + mi * 60 + s
async def channel_shorts(client: httpx.AsyncClient, key: str, channel_id: str, limit: int) -> list[dict]:
"""채널의 공개·퍼가기 허용 쇼츠 [{id, title, published}], 최신순."""
res = await client.get(f"{API_URL}/channels", params={"part": "contentDetails", "id": channel_id, "key": key})
res.raise_for_status()
channels = res.json().get("items") or []
if not channels:
return []
uploads = channels[0]["contentDetails"]["relatedPlaylists"]["uploads"]
res = await client.get(f"{API_URL}/playlistItems", params={"part": "contentDetails", "playlistId": uploads, "maxResults": 50, "key": key})
res.raise_for_status()
ids = [i["contentDetails"]["videoId"] for i in res.json().get("items") or []]
if not ids:
return []
res = await client.get(f"{API_URL}/videos", params={"part": "snippet,contentDetails,status", "id": ",".join(ids), "key": key})
res.raise_for_status()
found = []
for v in res.json().get("items") or []:
status, sec = v.get("status", {}), seconds(v["contentDetails"].get("duration", ""))
if status.get("privacyStatus") != "public" or not status.get("embeddable") or sec is None or sec > SHORT_MAX_SEC:
continue
found.append({"id": v["id"], "title": v["snippet"]["title"], "published": v["snippet"]["publishedAt"]})
found.sort(key=lambda x: x["published"], reverse=True)
return found[:limit]
async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str]:
"""영상 제목. 없거나 퍼가기가 막힌 영상이면 None."""
res = await client.get(OEMBED_URL, params={"url": f"https://www.youtube.com/shorts/{video_id}", "format": "json"})
if res.status_code in (401, 403, 404):
return None
res.raise_for_status()
return res.json().get("title")
+39 -2
View File
@@ -1,3 +1,4 @@
import uuid
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
@@ -6,7 +7,7 @@ from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Comment, Post, User
from common.enums import ErrorType
from common.enums import ErrorType, ReportReason
from common.liker import Liker
from common.utils.kma_time import kst_midnight, now_kst
from crud.feed_crud import FeedCRUD
@@ -92,7 +93,7 @@ class ReactionService:
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, user.user_id if user else None, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
@@ -109,6 +110,8 @@ class ReactionService:
body = body.strip()
if not body or len(body) > COMMENT_MAX:
return ErrorType.INVALID_INPUT, None
if user is not None and user.terms_agreed_at is None:
return ErrorType.TERMS_REQUIRED, None
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err, None
@@ -145,3 +148,37 @@ class ReactionService:
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
async def _others_comment(self, comment_id: int, user: User) -> tuple[ErrorType, Optional[uuid.UUID]]:
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT, 로그인 없이 쓴 댓글이면 작성자는 None."""
err, author = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comment_author(s, comment_id))
if err is not ErrorType.SUCCESS:
return err, None
if author is None:
return ErrorType.NOT_FOUND, None
return (ErrorType.INVALID_INPUT, None) if author.user_id == user.user_id else (ErrorType.SUCCESS, author.user_id)
async def report_comment(self, comment_id: int, user: User, reason: ReportReason) -> ErrorType:
err, _ = await self._others_comment(comment_id, user)
if err is not ErrorType.SUCCESS:
return err
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.report_comment(s, comment_id, user.user_id, reason.value)])
async def block_author(self, comment_id: int, user: User) -> ErrorType:
err, author = await self._others_comment(comment_id, user)
if err is not ErrorType.SUCCESS:
return err
# 로그인 없이 쓴 댓글은 차단할 사람이 없어 신고만 받는다
if author is None:
return ErrorType.INVALID_INPUT
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.block(s, user.user_id, author)])
async def unblock(self, user: User, blocked_id: uuid.UUID) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.unblock(s, user.user_id, blocked_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
async def blocked(self, user: User) -> tuple[ErrorType, list[User]]:
err, users = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.blocked(s, user.user_id))
return err, users or []
+51
View File
@@ -0,0 +1,51 @@
import asyncio
import json
import httpx
from redis.exceptions import RedisError
from common.cache.redis_client import REDIS
from common.enums import ErrorType
from common.logger import LOG
from config.settings import settings
from services.external import youtube
CACHE_KEY = "shorts:list"
# 워커가 하루 3번(07·12·18시 10분) 새로 받는다. 한 번 실패해도 다음 회차까지 이전 목록을 쓰게 넉넉히 둔다
CACHE_SEC = 2 * 86400
MAX_ITEMS = 10
class ShortsService:
async def items(self) -> tuple[ErrorType, list[dict]]:
"""오늘 화면 쇼츠 줄 [{id, title}]. 워커가 받아 둔 목록을 읽고, 없을 때만(처음 켰을 때) 바로 받는다."""
try:
cached = await REDIS.conn.get(CACHE_KEY)
except RedisError as e:
LOG.error(f"[shorts] cache get: {e}")
cached = None
if cached:
return ErrorType.SUCCESS, json.loads(cached)
return await self.refresh()
async def refresh(self) -> tuple[ErrorType, list[dict]]:
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
try:
async with httpx.AsyncClient(timeout=10) as client:
items = await self._fetch(client)
except (httpx.HTTPError, KeyError, ValueError) as e:
LOG.error(f"[shorts] fetch: {e}")
return ErrorType.EXTERNAL_API_ERROR, []
try:
await REDIS.conn.set(CACHE_KEY, json.dumps(items, ensure_ascii=False), ex=CACHE_SEC)
except RedisError as e:
LOG.error(f"[shorts] cache set: {e}")
return ErrorType.SUCCESS, items
async def _fetch(self, client: httpx.AsyncClient) -> list[dict]:
if settings.youtube_api_key:
found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS)
return [{"id": v["id"], "title": v["title"]} for v in found]
ids = [i.strip() for i in settings.youtube_shorts.split(",") if i.strip()][:MAX_ITEMS]
titles = await asyncio.gather(*(youtube.video_title(client, i) for i in ids))
return [{"id": i, "title": t} for i, t in zip(ids, titles) if t]
+1 -1
View File
@@ -43,7 +43,7 @@ def anyio_backend():
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
)
+26 -1
View File
@@ -14,7 +14,9 @@ def client():
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
return {"Authorization": f"Bearer {body['access_token']}"}
h = {"Authorization": f"Bearer {body['access_token']}"}
await c.post("/v1/auth/terms", headers=h) # 로그인한 사람은 약관에 동의해야 댓글을 쓴다
return h
@pytest.mark.anyio
@@ -147,3 +149,26 @@ async def test_hero_tomorrow_and_tomorrow_slots(offline):
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
assert res["day"] == hero["tomorrow"]["day"]
@pytest.mark.anyio
async def test_anon_comment_can_be_reported_not_blocked(offline):
"""로그인 없이 쓴 댓글도 신고는 되고(신고한 사람에겐 숨김), 차단할 사람이 없어 차단은 안 된다. 다른 사람을 차단해도 익명 댓글은 그대로 보인다."""
async with client() as c:
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
url = f"/v1/reaction/post/{post_id}/comment"
listing = f"{url}/list"
anon_id = (await c.post(url, headers=IP_A, json={"body": "익명 댓글"})).json()["comment"]["comment_id"]
writer = await _login(c, "anon_mod_01")
writer_id = (await c.post(url, headers=writer, json={"body": "회원 댓글"})).json()["comment"]["comment_id"]
viewer = await _login(c, "anon_mod_02")
blocked = (await c.post(f"/v1/reaction/comment/{writer_id}/block", headers=viewer)).json()
assert blocked["result"]["success"] is True
ids = [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
assert anon_id in ids and writer_id not in ids
assert (await c.post(f"/v1/reaction/comment/{anon_id}/block", headers=viewer)).json()["result"]["desc"] == "INVALID_INPUT"
assert (await c.post(f"/v1/reaction/comment/{anon_id}/report", headers=viewer, json={"reason": 1})).json()["result"]["success"] is True
assert anon_id not in [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
assert anon_id in [x["comment_id"] for x in (await c.get(listing, headers=IP_B)).json()["comments"]]
+121 -2
View File
@@ -10,8 +10,12 @@ def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def _signup(c, login_id="mina_01", nickname="망원동주민"):
return (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
async def _signup(c, login_id="mina_01", nickname="망원동주민", agree=True):
"""가입하고, 댓글을 쓸 수 있게 이용약관에도 동의한다 (agree=False 면 안 함)."""
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
if agree and body.get("access_token"):
await c.post("/v1/auth/terms", headers={"Authorization": f"Bearer {body['access_token']}"})
return body
@pytest.mark.anyio
@@ -122,3 +126,118 @@ async def test_logout_invalidates_access_and_refresh_tokens():
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
again = (await c.post("/v1/auth/login", json={"login_id": "mina_out", "password": "password1"})).json()
assert (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {again['access_token']}"})).status_code == 200
@pytest.mark.anyio
async def test_withdraw_deletes_account_and_reactions(offline):
async with client() as c:
body = await _signup(c, login_id="mina_bye")
h = {"Authorization": f"Bearer {body['access_token']}"}
other = {"Authorization": f"Bearer {(await _signup(c, 'other_bye', '남는사람'))['access_token']}"}
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)
await c.post(f"/v1/reaction/post/{post_id}/save", headers=h)
mine = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "곧 떠나요"})).json()["comment"]
kept = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=other, json={"body": "남아요"})).json()["comment"]
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/like", headers=h)
await c.post(f"/v1/reaction/comment/{mine['comment_id']}/like", headers=other)
assert (await c.delete("/v1/auth/me")).status_code == 401
assert (await c.delete("/v1/auth/me", headers=h)).json()["result"]["success"] is True
assert (await c.get("/v1/auth/me", headers=h)).status_code == 401
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
assert (await c.post("/v1/auth/login", json={"login_id": "mina_bye", "password": "password1"})).json()["result"]["desc"] == "AUTH_FAILED"
comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"]
assert [x["body"] for x in comments] == ["남아요"] and comments[0]["like_count"] == 0
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
assert p["like_count"] == 0 and p["comment_count"] == 1
# 같은 아이디로 다시 가입할 수 있다
assert (await _signup(c, login_id="mina_bye"))["result"]["success"] is True
def _h(body):
return {"Authorization": f"Bearer {body['access_token']}"}
async def _comment(c, post_id, h, text):
return (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": text})).json()
async def _bodies(c, post_id, h=None):
return [x["body"] for x in (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=h or {})).json()["comments"]]
@pytest.mark.anyio
async def test_comment_needs_terms_agreement(offline):
async with client() as c:
h = _h(await _signup(c, agree=False))
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
assert (await c.get("/v1/auth/me", headers=h)).json()["me"]["terms_agreed"] is False
assert (await _comment(c, post_id, h, "안녕"))["result"]["desc"] == "TERMS_REQUIRED"
assert (await c.post("/v1/auth/terms", headers=h)).json()["me"]["terms_agreed"] is True
assert (await _comment(c, post_id, h, "안녕"))["comment"]["body"] == "안녕"
@pytest.mark.anyio
async def test_report_hides_for_reporter_then_for_all_at_three(offline):
async with client() as c:
writer = _h(await _signup(c, "writer_1", "쓴사람"))
r = [_h(await _signup(c, f"reporter_{i}", f"신고자{i}")) for i in range(3)]
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
bad = (await _comment(c, post_id, writer, "광고입니다"))["comment"]
url = f"/v1/reaction/comment/{bad['comment_id']}/report"
assert (await c.post(url, headers=writer, json={"reason": 2})).json()["result"]["desc"] == "INVALID_INPUT"
assert (await c.post(url, headers=r[0], json={"reason": 9})).status_code == 422
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True # 두 번 신고해도 한 번
assert await _bodies(c, post_id, r[0]) == [] and await _bodies(c, post_id, r[1]) == ["광고입니다"]
await c.post(url, headers=r[1], json={"reason": 1})
assert await _bodies(c, post_id) == ["광고입니다"]
await c.post(url, headers=r[2], json={"reason": 1})
assert await _bodies(c, post_id) == [] and await _bodies(c, post_id, writer) == []
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
assert p["comment_count"] == 0
# 숨긴 댓글을 지워도 댓글 수가 한 번 더 줄지 않는다
assert (await c.delete(f"/v1/reaction/comment/{bad['comment_id']}", headers=writer)).json()["result"]["success"] is True
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
assert p["comment_count"] == 0
@pytest.mark.anyio
async def test_block_hides_author_comments_and_can_be_undone(offline):
async with client() as c:
me = _h(await _signup(c))
other = _h(await _signup(c, "rude_1", "무례한"))
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
rude = (await _comment(c, post_id, other, "흥"))["comment"]
mine = (await _comment(c, post_id, me, "좋아요"))["comment"]
assert (await c.post(f"/v1/reaction/comment/{mine['comment_id']}/block", headers=me)).json()["result"]["desc"] == "INVALID_INPUT"
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block")).status_code == 401
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block", headers=me)).json()["result"]["success"] is True
assert await _bodies(c, post_id, me) == ["좋아요"] and await _bodies(c, post_id) == ["흥", "좋아요"]
blocked = (await c.get("/v1/reaction/block/list", headers=me)).json()["users"]
assert [u["nickname"] for u in blocked] == ["무례한"]
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["success"] is True
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["desc"] == "NOT_FOUND"
assert await _bodies(c, post_id, me) == ["흥", "좋아요"]
@pytest.mark.anyio
async def test_withdraw_removes_reports_and_blocks(offline):
async with client() as c:
leaver = _h(await _signup(c, "leaver_1", "떠날사람"))
stay = _h(await _signup(c, "stay_1", "남는사람"))
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
kept = (await _comment(c, post_id, stay, "남아요"))["comment"]
gone = (await _comment(c, post_id, leaver, "떠나요"))["comment"]
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/report", headers=leaver, json={"reason": 4})
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/block", headers=leaver)
await c.post(f"/v1/reaction/comment/{gone['comment_id']}/block", headers=stay)
assert (await c.delete("/v1/auth/me", headers=leaver)).json()["result"]["success"] is True
assert (await c.get("/v1/reaction/block/list", headers=stay)).json()["users"] == []
assert await _bodies(c, post_id, stay) == ["남아요"]
+1
View File
@@ -84,6 +84,7 @@ async def test_like_in_one_sido_not_seen_in_another(offline):
async with client() as c:
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
h = {"Authorization": f"Bearer {token}"}
await c.post("/v1/auth/terms", headers=h)
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
+73
View File
@@ -0,0 +1,73 @@
import json
import httpx
import pytest
from common.cache.redis_client import REDIS
from common.enums import ErrorType
from services import shorts_service
from services.external.youtube import channel_shorts, seconds, video_title
from services.shorts_service import CACHE_KEY, ShortsService
def test_seconds_parses_iso_duration():
assert seconds("PT45S") == 45
assert seconds("PT1M5S") == 65
assert seconds("PT1H") == 3600
assert seconds("P1D") is None
def _api(videos: list[dict]) -> httpx.MockTransport:
def handle(req: httpx.Request) -> httpx.Response:
if req.url.path.endswith("/channels"):
return httpx.Response(200, json={"items": [{"contentDetails": {"relatedPlaylists": {"uploads": "UUtest"}}}]})
if req.url.path.endswith("/playlistItems"):
assert req.url.params["playlistId"] == "UUtest"
return httpx.Response(200, json={"items": [{"contentDetails": {"videoId": v["id"]}} for v in videos]})
return httpx.Response(200, json={"items": videos})
return httpx.MockTransport(handle)
def _video(vid: str, duration: str, published: str, embeddable: bool = True, privacy: str = "public") -> dict:
return {"id": vid, "snippet": {"title": f"제목 {vid}", "publishedAt": published}, "contentDetails": {"duration": duration},
"status": {"embeddable": embeddable, "privacyStatus": privacy}}
@pytest.mark.anyio
async def test_channel_shorts_keeps_public_embeddable_short_videos_newest_first():
videos = [
_video("old", "PT30S", "2026-10-20T00:00:00Z"),
_video("new", "PT58S", "2026-10-26T00:00:00Z"),
_video("long", "PT10M", "2026-10-25T00:00:00Z"),
_video("noembed", "PT20S", "2026-10-24T00:00:00Z", embeddable=False),
_video("private", "PT20S", "2026-10-23T00:00:00Z", privacy="unlisted"),
]
async with httpx.AsyncClient(transport=_api(videos)) as client:
found = await channel_shorts(client, "key", "UCtest", 10)
assert [v["id"] for v in found] == ["new", "old"]
@pytest.mark.anyio
async def test_video_title_none_when_embedding_blocked():
def handle(req: httpx.Request) -> httpx.Response:
if "blocked" in req.url.params["url"]:
return httpx.Response(401)
return httpx.Response(200, content=json.dumps({"title": "오늘 자전거각"}))
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:
assert await video_title(client, "ok") == "오늘 자전거각"
assert await video_title(client, "blocked") is None
@pytest.mark.anyio
async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch):
calls = []
async def fake_fetch(self, client):
calls.append(1)
return [{"id": "abc", "title": "오늘 자전거각"}]
monkeypatch.setattr(shorts_service.ShortsService, "_fetch", fake_fetch)
await REDIS.conn.delete(CACHE_KEY)
assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}])
assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}])
assert len(calls) == 1
+5 -2
View File
@@ -5,7 +5,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler
from common.database.db_session_manager import DB_SESSION_MNG
from common.logger import LOG
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_events, refresh_openmeteo_weather, refresh_weekend_rank
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_events, refresh_openmeteo_weather, refresh_shorts, refresh_weekend_rank
async def daily() -> None:
@@ -24,8 +24,11 @@ async def main() -> None:
scheduler.add_job(refresh_events, "cron", day_of_week="mon", hour=4, minute=0, max_instances=1, coalesce=True)
scheduler.add_job(refresh_events, kwargs={"only_if_missing": True}, max_instances=1)
scheduler.add_job(refresh_openmeteo_weather, "cron", hour="3,9,15,21", minute=10, max_instances=1, coalesce=True)
# 오늘 화면 쇼츠 줄: 하루 1~2개 올라오니 하루 3번이면 충분하다. 켤 때도 한 번.
scheduler.add_job(refresh_shorts, "cron", hour="7,12,18", minute=10, max_instances=1, coalesce=True)
scheduler.add_job(refresh_shorts, max_instances=1)
scheduler.start()
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST, openmeteo job at 03·09·15·21:10 KST")
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST, openmeteo job at 03·09·15·21:10 KST, shorts at 07·12·18:10 KST")
stop = asyncio.Event()
loop = asyncio.get_running_loop()
+7 -3
View File
@@ -4,7 +4,8 @@ services:
# 운영형: docker compose up --build → http://localhost:8080
frontend:
build:
context: ./frontend
context: .
dockerfile: frontend/Dockerfile
target: prod
args:
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
@@ -19,13 +20,16 @@ services:
frontend-dev:
profiles: ["dev"]
build:
context: ./frontend
context: .
dockerfile: frontend/Dockerfile
target: dev
ports:
- "5173:5173"
volumes:
- ./frontend:/app
- ./frontend:/app/frontend
- ./shared:/app/shared
- /app/node_modules
- /app/frontend/node_modules
environment:
- CHOKIDAR_USEPOLLING=true
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
+186
View File
@@ -0,0 +1,186 @@
# 구글 검색 정책 리서치
조사일: 2026-10-19 (사이트 이름, 방문자 수·광고와 순위는 2026-10-20 추가)
원칙: 공식 문서에 적힌 것만 쓴다. 문장 끝 `[번호]`는 맨 아래 출처 번호다. 문서에 없는 건 "문서에 없음"으로 따로 적었다.
## 0. 채널별로 어떤 규칙을 따르나
날씨각은 채널마다 사용자가 찾아오는 곳과 순위를 정하는 주체가 다르다. 이 문서의 1~5장(구글 검색 정책)은 **웹** 칸에만 해당한다.
| 채널 | 사용자가 찾는 곳 | 순위·노출을 정하는 것 (공식 문서) | 구글 검색 정책 적용 |
|---|---|---|---|
| 웹 (weather.o2o.kr, 지역 페이지 `/today/…`) | 구글 검색 | 의미·관련성·품질·사용성·맥락(위치) [2]. 링크와 sitemap으로 페이지를 찾는다 [1] | 적용 (1~5장) |
| 안드로이드 앱 · Wear OS 워치 앱/워치 페이스 (`watch/`) | Google Play 검색 | 평점·리뷰·다운로드 수 등 여러 요인이 함께 작용한다. 비중은 공개하지 않는다 [8] | 앱 안의 화면은 웹이 아니다. 앱 화면이 **내가 가진 웹페이지와 대응하고** Android App Links(딥링크 + 웹사이트 소유 확인)를 설정하면, 구글 검색 결과에서 앱으로 바로 열 수 있다 [9] |
| 토스 인앱 (앱인토스 미니앱) | 토스 앱 안 검색, 공유 링크, 미니앱 스토어·전체탭 | 출시 → 추천 → 부스팅 3단계. 추천은 UX·실사용 지표(재방문율·전환율)·리뷰·성능 네 가지를 모두 충족해야 하고, 검색 결과에서 우선 노출된다 [10] | 미니앱이 구글 검색에 색인되는지는 **문서에 없음** [10][11] |
| 알림 (앱 푸시 등) | 검색으로 찾는 대상이 아님 | — | 구글 검색은 웹페이지를 크롤링·색인한다 [1]. 알림 정책은 각 앱 플랫폼(Play, 토스) 문서를 따로 봐야 하며, 이 문서에서는 조사하지 않았다 |
- 앱인토스 노출 정책 시행일은 "10월 22일"로만 적혀 있고 연도는 없다. [10]
- 토스 미니앱 검색 키워드가 순위를 어떻게 정하는지는 문서에 없다. 추천 미니앱이 "검색 결과에서 우선 노출"된다는 문장만 있다. [10]
- 구글 Play 문서는 제목을 고유하고 앱 내용을 분명히 보여 주게 쓰라고 권하지만, 제목이 순위 요인이라고 적지는 않았다. [8]
## 1. 구글 검색이 동작하는 단계
- 구글은 크롤링 → 색인 → 검색 결과 제공의 세 단계로 동작한다. [1]
- 크롤링: Googlebot이 페이지를 찾아 내려받는다. 찾은 페이지를 모두 크롤링하지는 않는다. [1]
- 색인: 페이지 내용을 분석하고, 거의 같은 페이지는 묶어서 대표 페이지(canonical)를 정한다. 색인된다는 보장은 없다. [1]
- 검색 결과 제공: 색인에서 가장 관련 있고 품질 높다고 판단한 페이지를 보여 준다. [1]
- 구글은 페이지를 두 가지 방법으로 찾는다. 이미 아는 페이지의 **링크**를 따라가거나, 사이트 주인이 낸 **sitemap**을 읽는다. [1]
- 돈을 받고 더 자주 크롤링하거나 순위를 올려 주지 않는다. 순위는 프로그램이 정한다. [1]
## 2. 순위를 정할 때 보는 신호
검색어에 따라 각 신호의 비중이 달라진다. [2]
| 신호 | 내용 |
|---|---|
| 의미 | 검색어의 의도를 파악한다. 오타 교정, 비슷한 말 처리 포함 [2] |
| 관련성 | 페이지의 제목·본문이 검색어와 맞는지 본다 [2] |
| 품질 | 전문성·권위·신뢰를 본다. 다른 유명 사이트가 링크를 거는지가 예시로 나온다 [2] |
| 사용성 | 다른 조건이 비슷하면 모바일에서 잘 보이고 빠른 페이지가 유리할 수 있다 [2] |
| 맥락 | 위치, 언어, 검색 기록, 설정으로 결과를 맞춘다 [2] |
### 위치
- 구글은 사용자 위치 같은 정보로 무엇이 가장 관련 있는지 정한다. [2]
- 많은 검색어에 지역 의도가 있음을 알아본다. 예: '피자'를 치면 근처 배달 가게, 런던에서 'football'을 치면 축구 결과. [2]
- 같은 검색어도 사용자 위치·언어·기기에 따라 결과가 다르다. 예: '자전거 수리점'은 파리와 홍콩에서 결과가 다르다. [1]
### 날씨
- **한국과 일본에서는 구글 날씨 예보를 제공하지 않는다.** [6]
- 다른 나라에서 구글 날씨 예보는 각국 기상기관(NOAA, ECMWF, Met Office 등)의 모델과 관측을 쓰는 구글 자체 예보 시스템으로 만든다. [6]
### 광고비를 내면 순위가 오르나 → 아니다
- "검색 결과는 검색어만으로 정해지고, 기업·개인·단체가 광고를 사는지에 영향받지 않는다." [2]
- "검색 알고리즘이 순위를 매길 때 광고주를 특별 대우하지 않으며, 누구도 그렇게 해 달라고 돈을 낼 수 없다." [2]
- 검색 목록에 넣어 주는 데 돈을 받지 않는다. 광고나 관계없는 사업 제휴 같은 개인적·금전적 관계로 순위를 올려 주지 않는다. [13]
- "구글 검색 결과는 구글 광고 프로그램과 독립돼 있다." [14]
- 정리: 구글 광고(Google Ads)를 하면 광고 칸에 따로 뜰 뿐, 그 아래 일반 검색 결과 순위는 오르지 않는다.
### 방문자가 많으면 순위가 오르나 → 문서에 그런 말은 없다
- 사이트 방문자 수(트래픽)를 순위 신호로 쓴다는 문장은 공식 문서에 없다.
- 문서에 있는 것: "검색 결과가 검색어와 관련 있는지 평가하려고, 모아서 익명 처리한 상호작용 데이터를 쓴다." [2] 검색 결과에서 사람들이 어떻게 반응하는지를 관련성 평가에 쓴다는 말이고, 방문자 수를 그대로 순위에 쓴다는 말은 아니다.
- 인기와 가까운 신호로 문서에 나오는 것은 링크다: 품질을 볼 때 "다른 유명 사이트가 그 콘텐츠를 링크하거나 언급하는지"를 본다. [2] 링크로 페이지가 무엇에 대한 것인지·얼마나 도움이 되는지 판단한다. [3]
### 그럼 상위에 오르는 건 무엇으로 정해지나 (문서 기준)
- 검색어 의도에 맞는지(의미), 제목·본문에 검색어와 같은 말이 있는지(관련성), 도움이 되는 내용인지·다른 사이트가 링크·언급하는지(품질), 보기 쉬운지(사용성), 검색한 사람 위치·언어(맥락). 검색어마다 비중이 다르다. [2]
- 검색 결과 다른 페이지들과 비교해 충분한 가치를 주는지, 자기만의 정보가 있는지를 스스로 점검하라고 한다. [15]
- 판단(우리에게 적용): '분당구 오늘 날씨'는 제목·본문에 '분당구'가 있는 구 주소가 있어야 관련성에서 경쟁할 수 있다(10/20 구 주소 39장 배포). 그다음은 각 점수처럼 다른 날씨 사이트에 없는 정보, 그리고 다른 사이트의 링크·언급이다. 광고비나 방문자 수로 올리는 길은 문서상 없다.
## 3. 구글이 공개한 순위 시스템
[3]에 나온 것 중 우리와 관련 있는 것만 적었다.
| 시스템 | 내용 |
|---|---|
| BERT, RankBrain, Neural matching | 검색어와 페이지의 뜻을 이해한다. 검색어 단어가 그대로 없어도 관련 페이지를 찾는다 [3] |
| Passage ranking | 페이지의 개별 구간도 따로 평가한다 [3] |
| Freshness | 최신 내용이 필요한 검색어에는 새 내용을 보여 준다 [3] |
| Link analysis, PageRank | 페이지끼리의 링크로 무엇에 대한 페이지인지, 얼마나 도움이 되는지 판단한다 [3] |
| Exact match domain | 검색어와 똑같이 만든 도메인에 주는 점수를 제한한다 [3] |
| Reliable information | 권위 있는 페이지를 올리고 품질 낮은 내용을 내린다 [3] |
| Original content | 원본 내용을 인용만 한 페이지보다 우선한다 [3] |
| Site diversity | 상위 결과에 같은 사이트는 보통 2개까지만 보여 준다 [3] |
| Deduplication | 매우 비슷한 페이지가 많으면 가장 관련 있는 것만 보여 준다 [3] |
| Spam detection (SpamBrain) | 스팸을 찾는다. 정기적으로 업데이트된다 [3] |
| Helpful content | 2024년 3월부터 핵심 순위 시스템에 포함됐다 [3] |
## 4. 스팸 정책 (우리와 관련 있는 것)
### 관문 페이지 (Doorway abuse)
- 정의: 비슷한 특정 검색어로 순위를 얻으려고 만든 사이트나 페이지. [4]
- 예시: 특정 지역이나 도시를 노린 도메인·페이지를 여러 개 만들어 한 페이지로 몰아가는 것. [4]
### 대량 생성 (Scaled content abuse)
- 정의: 주로 검색 순위를 조작하려고 많은 페이지를 만드는 것. [4]
- 예시: 생성형 AI 같은 도구로 사용자에게 가치를 더하지 않는 페이지를 많이 만드는 것. [4]
### 숨긴 텍스트·링크 (Hidden text and link abuse)
- 정의: 검색엔진만을 위해 페이지에 내용을 넣는 것. [4]
- 예시: 흰 배경에 흰 글씨, 이미지 뒤에 숨기기, CSS로 화면 밖에 두기, 글자 크기나 투명도를 0으로, 작은 글자 하나에만 링크 걸기. [4]
- 위반이 아닌 것: 탭·아코디언처럼 눌러서 펼치는 내용, 슬라이드, 마우스를 올리면 나오는 툴팁, 스크린리더 전용 텍스트. [4]
- 고치는 방법: URL 검사 도구로 구글에는 보이고 사람에게는 안 보이는 내용을 찾아, 사람과 크롤러가 똑같이 볼 수 있게 지우거나 스타일을 바꾼다. [5]
### 위반했을 때
- 정책을 위반한 사이트는 순위가 내려가거나 검색 결과에 아예 나오지 않을 수 있다. [4]
- 구글은 자동 시스템과, 필요하면 사람 검토로 위반을 찾는다. 사람 검토는 수동 조치로 이어질 수 있다. [4]
- 수동 조치: 구글 직원이 정책 위반이라고 판단해 내리는 조치다. [5]
- 알림: 서치 콘솔의 "수동 조치" 보고서와 메시지 센터로 온다. [5]
- 범위: 일부 페이지 또는 사이트 전체. [5]
- 결과: 순위가 내려가거나 결과에서 빠진다. 사용자에게는 아무 표시가 없다. [5]
- 일부 페이지만 고치면 일부만 복구되지 않는다. [5]
- 복구: 해당 페이지를 모두 고친 뒤 "검토 요청"을 보낸다. 검토에 며칠에서 몇 주 걸린다. 검토 중에는 다시 보내지 않는다. [5]
## 5. 지도·지역 업체 순위 (참고)
웹페이지가 아니라 Google 비즈니스 프로필(지도의 가게 목록) 기준이다.
- 관련성: 프로필이 검색어와 얼마나 맞는지. [7]
- 거리: 검색하는 사람과 업체 사이의 거리. 위치를 공유하지 않았으면 구글이 아는 위치 정보를 쓴다. [7]
- 인지도: 얼마나 잘 알려졌는지. 다른 사이트의 링크, 리뷰 수와 평점이 포함된다. [7]
## 6. 사이트 이름 (검색 결과에 링크 위에 붙는 이름)
- 사이트 이름은 구글이 자동으로 정한다. 홈페이지 내용과 웹에서 그 사이트를 가리키는 언급을 함께 본다. [12]
- 구글이 보는 곳: 홈의 `WebSite` 구조화 데이터, `og:site_name`, `<title>`, 제목 태그(h1 등) 등. [12]
- 도메인(o2o.kr)과 서브도메인(weather.o2o.kr) 단위로 각각 정할 수 있다. 하위 경로(o2o.kr/weather) 단위는 안 된다. [12]
- 서브도메인 홈에 구조화 데이터가 없으면, 상위 도메인의 사이트 이름을 대신 쓸 수 있다. [12]
- `WebSite` 구조화 데이터는 홈에 있어야 한다. 필수는 `name`, `url`. `alternateName`은 선택이고 여러 개를 선호 순서대로 적을 수 있다. [12]
- 구글은 자동으로 정한 이름을 사람이 직접 바꿔 주지 않는다. [12]
- 원하는 이름이 안 나올 때 문서가 권하는 것: [12]
- 구조화 데이터와 홈의 다른 이름 표기(제목, og 등)가 서로 맞는지 확인
- 리디렉션, http·https 버전 모두 같은 이름인지 확인
- 서치 콘솔에서 홈 재크롤링 요청. 반영까지 며칠에서 몇 주.
- 그래도 안 되면 `alternateName`에 도메인 이름(소문자)을 넣어 대체 이름으로 둔다. 도메인 이름을 대표 이름으로 쓰는 건 마지막 수단.
- 사이트 이름이 순위에 영향을 주는지는 문서에 없다. 문서에 적힌 목적은 "각 결과의 출처를 잘 나타내는 것"뿐이다. [12]
### 우리 상황 (2026-10-20 확인)
- 구글 '날씨각' 검색 결과에 weather.o2o.kr 사이트 이름이 '날씨각'이 아니라 '에이아이오투오'로 나온다.
- weather.o2o.kr 홈: `WebSite` 구조화 데이터 `name` "날씨각", `alternateName` "날씨 각"·"Nalssigak", `og:site_name` "날씨각", `<title>` "날씨각 · …"으로 모두 같다.
- o2o.kr 홈의 `<title>`은 "에이아이오투오"다.
- 판단(문서에 없는 추정): 구글이 weather.o2o.kr의 이름을 아직 정하지 못해 상위 도메인 o2o.kr 이름을 쓰고 있을 가능성이 크다. 확인 방법은 서치 콘솔 URL 검사로 홈의 구조화 데이터가 인식됐는지 보는 것.
- 판단: 순위 영향은 문서에 없다. 다만 '날씨각'을 검색한 사람에게 다른 이름이 보이면 우리 사이트인지 알아보기 어렵다. 할 일은 서치 콘솔에서 홈 재크롤링 요청 후 몇 주 지켜보는 것.
## 7. 공식 문서에 없는 것
- 앱(JS)이 뜨면서 화면에서 사라지는 첫 HTML 속 링크·텍스트가 숨긴 텍스트 위반인지는 문서에 없다. 위반 예시에도, 예외에도 없다.
- '오늘 날씨' 같은 검색어에 구글이 사용자 위치를 어떻게 붙여 검색하는지 구체적인 방식은 문서에 없다. 문서에는 "위치를 쓴다", "지역 의도를 알아본다"까지만 있다. [2]
- 새 페이지가 순위에 오르기까지 걸리는 기간은 문서에 없다.
- 사이트 이름이 순위에 영향을 주는지는 문서에 없다. [12]
- 사이트 방문자 수가 순위에 영향을 주는지는 문서에 없다. 있는 건 검색 결과에 대한 상호작용 데이터를 관련성 평가에 쓴다는 문장뿐이다. [2]
## 8. 직접 확인한 검색 결과 (2026-10-19, 구글, 한국어·한국 설정)
공식 문서가 아니라 한 번 직접 검색해 본 결과다. 사람·위치·시간마다 다를 수 있다.
- '날씨각': weather.o2o.kr 홈이 3위. 1위는 성남 AccuWeather(검색한 위치가 성남으로 잡힘), 2위는 기상청.
- `site:weather.o2o.kr`: 홈, `/week`, `/gak`, `/season`과 지역 페이지 일부(광주 남구, 서울 중구, 동해, 이천, 완도, 영동)가 색인돼 있음.
- '성남 날씨각', '완도 날씨각': 10위 안에 없음. 두 검색 모두 결과에 "누락된 검색어: 각"이 표시됨.
- 2026-10-20 재확인: '날씨각' 3위 그대로, 사이트 이름은 '에이아이오투오'. '마포구 오늘 날씨'·'마포구 날씨'·'강남구 오늘 날씨'·'오늘 날씨'·'세차하기 좋은 날'·'오늘 노을 시간'은 20위 안에 없음.
- 서버 로그(지난 7일): Googlebot이 지역 페이지 235개 중 39개를 가져감. sitemap은 2번 가져감.
## 출처
1. [How Google Search works — Google Search Central](https://developers.google.com/search/docs/fundamentals/how-search-works)
2. [Ranking results — How Search Works](https://www.google.com/search/howsearchworks/how-search-works/ranking-results/)
3. [A guide to Google Search ranking systems — Google Search Central](https://developers.google.com/search/docs/appearance/ranking-systems-guide)
4. [Spam policies for Google web search — Google Search Central](https://developers.google.com/search/docs/essentials/spam-policies)
5. [Manual actions report — Search Console 도움말](https://support.google.com/webmasters/answer/9044175)
6. [Forecast information on Google Weather — Google 검색 도움말](https://support.google.com/websearch/answer/13687874)
7. [How Google determines local ranking — Google 비즈니스 프로필 도움말](https://support.google.com/business/answer/7091)
8. [Google Play에서 앱 검색·발견 — Play Console 도움말](https://support.google.com/googleplay/android-developer/answer/4448378?hl=ko)
9. [Enable app content for Google Search (App Links) — Android Developers](https://developer.android.com/training/app-indexing)
10. [미니앱 노출 정책 — 앱인토스 개발자 문서](https://developers-apps-in-toss.toss.im/guide/exposure)
11. [앱인토스란 — 앱인토스 개발자 문서](https://developers-apps-in-toss.toss.im/intro/overview.html)
12. [Provide a site name to Google Search — Google Search Central](https://developers.google.com/search/docs/appearance/site-names) (2025-12-10 갱신)
13. [Our approach to Search — How Search Works](https://www.google.com/search/howsearchworks/our-approach/)
14. [How Google search results differ from ads — Google Ads 도움말](https://support.google.com/google-ads/answer/1722080)
15. [Creating helpful, reliable, people-first content — Google Search Central](https://developers.google.com/search/docs/fundamentals/creating-helpful-content) (2026-10-05 갱신)
-10
View File
@@ -1,10 +0,0 @@
node_modules
dist
.git
*.log
.DS_Store
Dockerfile
.dockerignore
dist-toss
*.ait
.env.toss
+13 -5
View File
@@ -2,13 +2,19 @@
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
FROM node:24-alpine AS deps
# 빌드 대상은 저장소 루트(npm workspaces). 웹에 필요한 frontend·shared 만 설치한다
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY frontend/package.json frontend/
COPY shared/package.json shared/
COPY mobile/package.json mobile/
RUN npm ci -w frontend -w shared
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
FROM deps AS dev
COPY . .
COPY shared shared
COPY frontend frontend
WORKDIR /app/frontend
EXPOSE 5173
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
@@ -18,12 +24,14 @@ ARG VITE_API_BASE_URL=""
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
ARG VITE_SITE_URL=""
ENV VITE_SITE_URL=$VITE_SITE_URL
COPY . .
COPY shared shared
COPY frontend frontend
WORKDIR /app/frontend
RUN npm run build
# ---- prod: nginx로 정적 파일 제공 ----
FROM nginx:1.29-alpine AS prod
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/frontend/dist /usr/share/nginx/html
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
+1 -1
View File
@@ -2,7 +2,7 @@ import { defineConfig } from '@hey-api/openapi-ts'
export default defineConfig({
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
output: 'src/api/client',
output: '../shared/api/client',
parser: {
patch: {
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
-4110
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -13,6 +13,7 @@
},
"dependencies": {
"@apps-in-toss/web-framework": "3.8.0",
"@nalssigak/shared": "*",
"@tailwindcss/vite": "^4.3.3",
"@tanstack/react-query": "^5.104.0",
"embla-carousel-react": "^8.6.0",
+30 -60
View File
@@ -10,83 +10,53 @@
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 class="muted">시행일: 2026년 10월 20일</p>
<p>이 약관은 AIO2O(이하 "회사")가 제공하는 날씨각 서비스의 이용 조건과 절차, 회사와 이용자의 권리·의무를 정합니다.</p>
<p>이 약관은 AIO2O(이하 "회사")가 운영하는 날씨각 웹·앱 서비스(이하 "서비스")를 이용하는 조건을 정합니다. 댓글을 쓰려면 이 약관에 동의해야 합니다.</p>
<h2>1. 용어</h2>
<h2>1. 서비스</h2>
<p>서비스는 지역별 날씨, 하늘·노을 예보, 생활 지수, 주변 행사 같은 정보를 제공합니다. 날씨 정보는 기상청 등 외부 자료를 바탕으로 한 예보이며 실제 날씨와 다를 수 있습니다.</p>
<h2>2. 계정</h2>
<p>웹·앱에서는 아이디·비밀번호나 구글 계정으로, 토스 앱 안의 미니앱에서는 토스 로그인으로 회원이 됩니다.</p>
<p>회원은 자신의 계정을 직접 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다. 회원은 언제든지 내 정보에서 탈퇴할 수 있고, 탈퇴하면 계정과 남긴 댓글·좋아요·저장·신고·차단 기록이 모두 지워집니다.</p>
<h2>3. 댓글에 쓰면 안 되는 내용</h2>
<p>아래 내용은 댓글로 쓸 수 없습니다.</p>
<ul>
<li>서비스: 회사가 웹(weather.o2o.kr), 토스 앱 안의 미니앱(이하 "토스 미니앱"), Wear OS 워치 앱으로 제공하는 날씨각과 그에 딸린 날씨·각 점수·노을·주말·행사·계절 정보, 좋아요·댓글·저장 기능</li>
<li>이용자: 서비스를 이용하는 모든 사람</li>
<li>회원: 웹에서 아이디·비밀번호로 가입했거나, 토스 미니앱에서 토스 로그인으로 로그인한 이용자</li>
<li>게시물: 회원이 서비스에 올린 댓글</li>
<li>욕설, 비하, 혐오, 따돌림, 위협</li>
<li>광고, 홍보, 같은 내용 반복 게시</li>
<li>전화번호·주소 등 자신이나 다른 사람의 개인정보</li>
<li>음란하거나 폭력적인 내용, 불법 행위를 부추기는 내용</li>
<li>다른 사람의 권리(저작권·초상권·명예 등)를 침해하는 내용</li>
</ul>
<h2>2. 약관의 효력과 변경</h2>
<p>이 약관은 서비스 화면에 게시해 효력이 생깁니다. 회사는 관련 법령을 어기지 않는 범위에서 약관을 바꿀 수 있으며, 바꿀 때는 시행 7일 전(이용자에게 불리한 변경은 30일 전)부터 서비스 안에서 알립니다.</p>
<p>바뀐 약관에 동의하지 않으면 이용을 그만두고 탈퇴할 수 있습니다. 알린 시행일 뒤에도 계속 이용하면 바뀐 약관에 동의한 것으로 봅니다.</p>
<h2>4. 신고·차단과 조치</h2>
<p>회원은 댓글마다 신고하거나 그 댓글을 쓴 사람을 차단할 수 있습니다. 신고한 댓글과 차단한 사람의 댓글은 본인에게 더는 보이지 않습니다. 신고가 여러 건 쌓인 댓글은 자동으로 숨겨지고, 회사가 확인해 3항을 어긴 댓글은 숨기거나 지우며, 반복해서 어긴 회원은 서비스 이용을 제한할 수 있습니다. 조치에 이의가 있으면 아래 연락처로 알려 주세요.</p>
<h2>3. 회원가입과 로그인</h2>
<p>웹에서는 아이디, 비밀번호, 닉네임을 입력하고 가입합니다. 토스 미니앱에서는 토스 로그인에 동의하면 회원이 됩니다. 가입하거나 토스 로그인을 하면 이 약관과 <a href="/privacy">개인정보처리방침</a>에 동의한 것으로 봅니다.</p>
<p>만 14세 미만은 회원이 될 수 없습니다. 다른 사람의 정보를 쓰거나 다른 사람을 사칭하는 닉네임을 쓸 수 없습니다.</p>
<h2>5. 게시물의 권리와 책임</h2>
<p>댓글의 권리와 책임은 작성한 회원에게 있습니다. 회사는 서비스 화면에 댓글을 보여 주는 범위에서만 이를 사용합니다.</p>
<h2>4. 서비스 이용</h2>
<p>날씨와 각 점수, 노을, 주말·행사, 계절 정보는 로그인 없이 무료로 볼 수 있습니다. 좋아요, 댓글, 저장은 로그인한 뒤에 쓸 수 있습니다.</p>
<p>회사는 운영상·기술상 필요에 따라 서비스의 내용을 바꾸거나 일부 또는 전부를 중단할 수 있으며, 중요한 변경이나 중단은 미리 알립니다. 다만 미리 알릴 수 없는 사정이 있으면 나중에 알릴 수 있습니다.</p>
<h2>6. 서비스 변경·중단</h2>
<p>회사는 운영상 필요하면 서비스 내용을 바꾸거나 중단할 수 있으며, 중요한 변경은 미리 서비스 안에 알립니다.</p>
<h2>5. 날씨 정보와 면책</h2>
<p>서비스의 날씨, 미세먼지, 각 점수, 노을 판정, 주말 순위, 행사 정보는 공공 데이터와 외부 예보를 바탕으로 회사가 계산하거나 정리한 참고 정보입니다. 예보는 실제 날씨와 다를 수 있고, 외부 제공처의 사정으로 늦거나 빠질 수 있습니다.</p>
<p>회사는 이 정보의 정확성이나 이 정보를 근거로 한 결정의 결과를 보증하지 않습니다. 야외 활동, 여행, 행사 참석 같은 결정은 이용자 스스로 판단하며, 기상특보나 행사 일정은 기상청과 각 주최 측의 공식 안내를 함께 확인해 주세요.</p>
<p>회사의 고의나 중대한 과실로 생긴 손해는 이 면책에서 제외합니다.</p>
<h2>7. 책임의 한계</h2>
<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>8. 개인정보</h2>
<p>개인정보 처리는 <a href="/privacy.html">개인정보처리방침</a>을 따릅니다.</p>
<h2>7. 회원의 의무와 이용 제한</h2>
<p>회원은 자신의 계정을 스스로 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다.</p>
<p>자동화된 수단으로 정보를 대량으로 가져가거나, 서비스 운영을 방해하거나, 이 약관을 어기면 회사는 해당 게시물을 지우고 서비스 이용을 제한할 수 있습니다.</p>
<h2>9. 문의</h2>
<p>운영자: AIO2O<br />이메일: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></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>
<h2>10. 약관 변경</h2>
<p>이 약관이 바뀌면 시행 7일 전부터 이 페이지에 알립니다.</p>
</main>
</body>
</html>
+2
View File
@@ -3,6 +3,7 @@ import { BLayout } from './b/BLayout'
import { FoliagePage } from './b/FoliagePage'
import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage'
import { ShortsPage } from './b/Shorts'
import { SkyPage } from './b/SkyPage'
import { TalkPage } from './b/TalkPage'
import { TodayPage } from './b/TodayPage'
@@ -22,6 +23,7 @@ export default function App() {
<Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} />
<Route path="talk" element={<TalkPage />} />
<Route path="shorts/:id?" element={<ShortsPage />} />
<Route path="*" element={<TodayPage />} />
</Route>
</Routes>
-4
View File
@@ -1,4 +0,0 @@
// This file is auto-generated by @hey-api/openapi-ts
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, toss, tossUnlink, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type LiLine truncated
+9 -67
View File
@@ -1,72 +1,14 @@
import { client } from './client/client.gen'
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
import { configureApi } from '@nalssigak/shared/api/setup'
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
type Refresh = 'ok' | 'rejected' | 'unreachable'
// 401이 한꺼번에 와도 갱신은 한 번만
let refreshing: Promise<Refresh> | null = null
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
function refreshTokens(): Promise<Refresh> {
refreshing ??= (async (): Promise<Refresh> => {
const token = getRefreshToken()
if (!token) return 'rejected'
const res = await fetch(`${API_BASE_URL}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
if (res.status >= 500) return 'unreachable'
const body = res.ok ? await res.json() : null
if (!body?.result?.success || !body.access_token) return 'rejected'
setTokens(body.access_token, body.refresh_token ?? token)
return 'ok'
})()
.catch((): Refresh => 'unreachable')
.finally(() => {
refreshing = null
})
return refreshing
}
const NO_REFRESH = ['/v1/auth/login', '/v1/auth/signup', '/v1/auth/refresh']
/** 같은 요청을 토큰만 바꿔(null 이면 빼고) 다시 보낼 수 있게 복사한다 */
function withToken(request: Request, token: string | null) {
const copy = request.clone()
if (token) copy.headers.set('Authorization', `Bearer ${token}`)
else copy.headers.delete('Authorization')
return copy
}
/**
* 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보낸다.
* 갱신이 거절되면 토큰을 지우고, 로그인 없이 되는 요청은 그냥 다시 보내고, 로그인이 꼭 필요한 요청만 로그인 창을 띄운다.
*/
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const request = input instanceof Request && !init ? input : new Request(input, init)
const retry = request.clone()
const response = await fetch(request)
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
if (request.headers.has('Authorization')) {
const result = await refreshTokens()
if (result === 'unreachable') return response
if (result === 'ok') {
const again = await fetch(withToken(retry, getAccessToken()))
if (again.status !== 401) return again
}
if (getAccessToken()) clearTokens()
const anonymous = await fetch(withToken(retry, null))
if (anonymous.status !== 401) return anonymous
}
// 로그인 창은 사람이 한 동작(글쓰기·댓글 등)에만 띄운다. 화면이 알아서 받는 GET(내 정보 등)이나 로그아웃이 만료로 401이면 조용히 로그아웃 상태로 둔다
if (request.method !== 'GET' && new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
return response
}
client.setConfig({ baseUrl: API_BASE_URL, throwOnError: true, fetch: authFetch })
client.interceptors.request.use((request) => {
const token = getAccessToken()
if (token) request.headers.set('Authorization', `Bearer ${token}`)
return request
// 사파리 프라이빗 모드 등에서는 localStorage 를 읽는 것만으로 에러가 나서 쓸 때마다 꺼낸다
configureApi({
baseUrl: API_BASE_URL,
storage: {
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
},
})
+2 -2
View File
@@ -1,10 +1,10 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from './lib'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
import './b.css'
import { AuthProvider } from './auth'
import { RegionProvider } from './region'
+3 -3
View File
@@ -1,9 +1,9 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { kst, loadOf, MEDALS, seasonOf } from './lib'
import { kst, loadOf, MEDALS, seasonOf } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
+6 -5
View File
@@ -1,13 +1,14 @@
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
import { createPortal } from 'react-dom'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type ImageSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type ImageSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '@nalssigak/shared/api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { cardBg, clockShort, fall } from './lib'
import type { SlideBg } from './types'
import { deg } from './weatherText'
import { cardBg, clockShort } from '@nalssigak/shared/lib'
import { fall } from './lib'
import type { SlideBg } from '@nalssigak/shared/lib/types'
import { deg } from '@nalssigak/shared/lib/weatherText'
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
+4 -3
View File
@@ -1,9 +1,10 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
import { ArticleCategory } from '../api/client/types.gen'
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
import { ARTICLE_CAT, fall } from './lib'
import { useSheet } from './sheetContext'
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
+250 -28
View File
@@ -1,10 +1,12 @@
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
import regionPages from '../../seo/region.json'
import { setTokens, subscribeAuth } from '../api/auth'
import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
import { SITE_URL } from '../api/setup'
import {
addCommentMutation,
agreeTermsMutation,
blockAuthorMutation,
deleteCommentMutation,
getArticleOptions,
getFeedQueryKey,
@@ -12,24 +14,30 @@ import {
getSeasonWeekOptions,
likeCommentMutation,
listCommentsInfiniteOptions,
listBlockedOptions,
listBlockedQueryKey,
listCommentsInfiniteQueryKey,
listRegionsOptions,
meQueryKey,
reportCommentMutation,
unblockMutation,
unlikeCommentMutation,
updateMeMutation,
} from '../api/client/@tanstack/react-query.gen'
import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.gen'
withdrawMutation,
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { AuthProvider, ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics'
import { IS_TOSS, 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'
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { WeatherWhySheet } from './weatherWhy'
import { ARTICLE_CAT } from './lib'
import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
@@ -642,8 +650,88 @@ function ShareSheet({ share }: { share: SharePayload }) {
/* ---------- 댓글 ---------- */
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
const REPORT_REASONS = [
[ReportReason.ABUSE, '욕설·비하'],
[ReportReason.AD, '광고'],
[ReportReason.PRIVACY, '개인정보 노출'],
[ReportReason.OTHER, '기타'],
] as const
const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments'
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed')
const [failed, setFailed] = useState(false)
const report = useMutation(reportCommentMutation())
const block = useMutation(blockAuthorMutation())
const pending = report.isPending || block.isPending
const finish = (notice: string) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
setStep('closed')
onNotice(notice)
queryClient.invalidateQueries({ predicate: isCommentList })
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() })
},
onError: () => setFailed(true),
})
const go = (next: typeof step) => {
setFailed(false)
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } })
setStep(next)
}
const btn = 'cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50'
return (
<>
<button type="button" onClick={() => go(step === 'closed' ? 'menu' : 'closed')} aria-expanded={step !== 'closed'} aria-label="댓글 메뉴" className="ml-1.5 cursor-pointer px-1 font-extrabold text-(--ink3)">
⋯
</button>
{step !== 'closed' && (
<span className="mt-2 flex flex-wrap items-center gap-1.5" role="group" aria-label="댓글 메뉴">
{step === 'menu' && (
<>
<button type="button" className={btn} onClick={() => go('report')}>
신고하기
</button>
<button type="button" className={btn} onClick={() => go('block')}>
이 사람 차단하기
</button>
</>
)}
{step === 'report' &&
REPORT_REASONS.map(([reason, label]) => (
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))}>
{label}
</button>
))}
{step === 'block' && (
<>
<span className="w-full text-[13px] font-bold text-(--ink)">{c.nickname}님 댓글을 더는 안 볼까요?</span>
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))}>
차단하기
</button>
<button type="button" disabled={pending} className={btn} onClick={() => go('closed')}>
취소
</button>
</>
)}
{failed && (
<span className="w-full text-[13px] font-bold text-(--heart)" role="alert">
잠시 뒤에 다시 해 주세요.
</span>
)}
</span>
)}
</>
)
}
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
const { region } = useRegion()
const queryClient = useQueryClient()
const [liked, setLiked] = useState(c.liked)
@@ -725,6 +813,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
</button>
</>
)}
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
</small>
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
@@ -744,13 +833,21 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
const add = useMutation(addCommentMutation())
const agree = useMutation(agreeTermsMutation())
const [addFailed, setAddFailed] = useState(false)
const [askTerms, setAskTerms] = useState(false)
const [notice, setNotice] = useState('')
const [text, setText] = useState(draft ?? '')
const inputRef = useRef<HTMLInputElement>(null)
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
const submit = (e: FormEvent) => {
e.preventDefault()
useEffect(() => {
if (!notice) return
const t = setTimeout(() => setNotice(''), 3000)
return () => clearTimeout(t)
}, [notice])
const send = () => {
const body = text.trim()
if (!body || add.isPending) return
setAddFailed(false)
@@ -758,6 +855,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
{ path: { post_id: postId }, body: { body, region: region.code } },
{
onSuccess: (res) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
setAddFailed(!res.result?.success)
if (!res.result?.success) return
setText('')
@@ -769,13 +867,35 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
)
}
// 로그인했으면 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
const submit = (e: FormEvent) => {
e.preventDefault()
if (me && !me.terms_agreed) return setAskTerms(true)
send()
}
const agreeAndSend = () => {
setAddFailed(false)
agree.mutate(
{},
{
onSuccess: (res) => {
if (!res.result?.success) return setAddFailed(true)
queryClient.setQueryData(meQueryKey(), res)
setAskTerms(false)
send()
},
onError: () => setAddFailed(true),
},
)
}
return (
<>
<Body>
{comments.length ? (
<>
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} />)}
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />)}
{list.hasNextPage && (
<button type="button" onClick={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 w-full cursor-pointer text-center text-sm font-bold text-(--ink3) disabled:opacity-50">
{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}
@@ -788,24 +908,38 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
)}
</Body>
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
{EMOJIS.map((e) => (
<button
key={e}
type="button"
disabled={add.isPending}
className="cursor-pointer disabled:opacity-40"
onClick={() => {
setText((t) => (t + e).slice(0, 60))
inputRef.current?.focus()
}}
>
{e}
</button>
))}
</div>
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
{askTerms ? (
<div className="mx-3 flex flex-col gap-2 rounded-[16px] bg-[#f3f6fb] p-3" role="dialog" aria-label="이용약관 동의">
<p className="m-0 text-[13px] font-bold text-(--ink)">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</p>
<div className="flex gap-2">
<a href="/terms.html" target="_blank" rel="noopener" className="flex-1 rounded-[12px] bg-white p-2.5 text-center text-[13px] font-extrabold text-(--ink)">
이용약관 보기
</a>
<button type="button" onClick={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 cursor-pointer rounded-[12px] bg-(--orange) p-2.5 text-[13px] font-extrabold text-white disabled:opacity-60">
동의하고 쓰기
</button>
</div>
</div>
) : (
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
{EMOJIS.map((e) => (
<button
key={e}
type="button"
disabled={add.isPending}
className="cursor-pointer disabled:opacity-40"
onClick={() => {
setText((t) => (t + e).slice(0, 60))
inputRef.current?.focus()
}}
>
{e}
</button>
))}
</div>
)}
<p className={cx('h-4 px-4 text-center text-xs leading-4 font-bold', addFailed ? 'text-(--heart)' : 'text-(--ink2)')} role="alert">
{addFailed ? '댓글을 올리지 못했어요. 다시 해 주세요.' : notice}
</p>
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
@@ -870,7 +1004,93 @@ function TossNoLoginSheet({ onDone }: { onDone: () => void }) {
)
}
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃·탈퇴 ---------- */
/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */
function Withdraw({ onDone }: { onDone: () => void }) {
const withdraw = useMutation(withdrawMutation())
const [asking, setAsking] = useState(false)
const [failed, setFailed] = useState(false)
if (!asking)
return (
<button type="button" onClick={() => setAsking(true)} className="cursor-pointer self-center p-1 text-[13px] font-semibold text-(--ink3)">
탈퇴하기
</button>
)
const run = () => {
setFailed(false)
withdraw.mutate(
{},
{
onSuccess: (res) => {
if (!res.result?.success) return setFailed(true)
clearTokens()
onDone()
},
onError: () => setFailed(true),
},
)
}
return (
<div className="flex flex-col gap-2.5 rounded-[18px] bg-[#fff1f3] p-3.5" role="alert">
<p className="m-0 text-center text-sm font-bold text-(--ink)">
탈퇴하면 계정과 남긴 댓글·좋아요가
<br />
모두 지워져요. 되돌릴 수 없어요.
</p>
<div className="flex gap-2">
<button type="button" onClick={() => setAsking(false)} disabled={withdraw.isPending} className="flex-1 cursor-pointer rounded-[14px] bg-white p-3 text-sm font-extrabold text-(--ink)">
그만둘게요
</button>
<button type="button" onClick={run} disabled={withdraw.isPending} className="flex-1 cursor-pointer rounded-[14px] bg-(--heart) p-3 text-sm font-extrabold text-white disabled:opacity-60">
탈퇴할게요
</button>
</div>
{failed && <p className="m-0 text-center text-[13px] font-bold text-(--heart)">탈퇴하지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div>
)
}
/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */
function Blocked() {
const queryClient = useQueryClient()
const list = useQuery(listBlockedOptions())
const unblock = useMutation(unblockMutation())
const [failed, setFailed] = useState(false)
const users = list.data?.users ?? []
if (!users.length) return null
const release = (user_id: string) => {
setFailed(false)
unblock.mutate(
{ path: { user_id } },
{
onSuccess: (res) => {
if (!res.result?.success) return setFailed(true)
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() })
queryClient.invalidateQueries({ predicate: isCommentList })
},
onError: () => setFailed(true),
},
)
}
return (
<section aria-label="차단한 사람">
<h4 className="m-0 mb-2 text-sm font-extrabold">차단한 사람</h4>
<ul className="m-0 flex list-none flex-col gap-2 p-0">
{users.map((u) => (
<li key={u.user_id} className="flex items-center gap-2.5">
<Avatar character={u.character} color={u.color} />
<span className="flex-1 text-sm font-bold">{u.nickname}</span>
<button type="button" onClick={() => release(u.user_id)} disabled={unblock.isPending} className="cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50">
풀기
</button>
</li>
))}
</ul>
{failed && <p className="m-0 mt-1.5 text-[13px] font-bold text-(--heart)">잠시 뒤에 다시 해 주세요.</p>}
</section>
)
}
function MeSheet({ onDone }: { onDone: () => void }) {
const install = useInstall()
const installable = useInstallable()
@@ -997,6 +1217,8 @@ function MeSheet({ onDone }: { onDone: () => void }) {
>
로그아웃
</button>
<Blocked />
<Withdraw onDone={onDone} />
</Body>
)
}
+338
View File
@@ -0,0 +1,338 @@
import { useQuery } from '@tanstack/react-query'
import { type CSSProperties, type PointerEvent as ReactPointerEvent, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router'
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ShortItem } from '@nalssigak/shared/api/client'
import { cx } from '../lib/utils'
import { Rail, Skel, SkelRail, TAP44 } from './ui'
// 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다.
// 위 로고·아래 제목 줄이 작은 카드에서 겹쳐 보이지 않게 가운데를 1.4배로 키워 위아래를 잘라 낸다
const CARD_W = 120
const PLAYER_W = 200
const SCALE = (CARD_W / PLAYER_W) * 1.4
// 쇼츠 페이지의 영상 칸: 위 헤더(54px)·버튼 줄(48px)과 아래 탭 바(--shorts-tab) 사이 높이와 화면 너비 안에 9:16으로 맞춘다
const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 54px - 48px - var(--shorts-tab, 0px)) * 9 / 16))', aspectRatio: '9 / 16' }
/** 아래 탭 바 높이 (기기마다 안전 영역이 달라 실제로 잰다) */
function useTabBarHeight() {
const [h, setH] = useState(0)
useLayoutEffect(() => {
const nav = document.querySelector<HTMLElement>('nav.b-tabbar')
if (!nav) return
const ro = new ResizeObserver(() => setH(nav.offsetHeight))
ro.observe(nav)
return () => ro.disconnect()
}, [])
return h
}
const YT_ORIGIN = 'https://www.youtube-nocookie.com'
function embed(id: string) {
const q = new URLSearchParams({
autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1',
enablejsapi: '1', origin: window.location.origin,
})
return `${YT_ORIGIN}/embed/${id}?${q}`
}
type Func = 'playVideo' | 'pauseVideo' | 'seekTo' | 'mute' | 'unMute'
/** 이미 띄운 플레이어에 명령 (IFrame API 메시지) */
function command(frame: HTMLIFrameElement | null | undefined, func: Func, args: unknown[] = []) {
frame?.contentWindow?.postMessage(JSON.stringify({ event: 'command', func, args }), YT_ORIGIN)
}
const PLAYING = 1
// 마우스로 이만큼 끌면 다음·이전 영상으로 넘긴다
const SWIPE_PX = 30
/** 화면에 보이는 동안만 true */
function useVisible<T extends Element>(threshold = 0.5) {
const [el, ref] = useState<T | null>(null)
const [visible, setVisible] = useState(false)
useEffect(() => {
if (!el) return
const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold })
io.observe(el)
return () => io.disconnect()
}, [el, threshold])
return [ref, visible] as const
}
/** 오늘 화면 히어로 아래 쇼츠 줄: 첫 카드만 소리 없이 재생, 누르면 쇼츠 페이지(/shorts/영상ID)에서 위아래로 넘겨 본다 */
export function ShortsRail() {
const q = useQuery(listShortsOptions())
const items = q.data?.items ?? []
const [ref, visible] = useVisible<HTMLElement>()
if (q.isPending) {
return (
<section aria-hidden="true">
<SkelRail>
{[0, 1, 2, 3].map((i) => (
<Skel key={i} className="aspect-[9/16] w-[120px] rounded-xl" />
))}
</SkelRail>
</section>
)
}
if (!items.length) return null
return (
<section ref={ref} aria-label="날씨각 쇼츠">
<Rail label="쇼츠 목록">
{items.map((s, i) => (
<ShortCard key={s.id} s={s} playing={i === 0 && visible} />
))}
</Rail>
</section>
)
}
function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) {
return (
<Link to={`/shorts/${s.id}`} aria-label={`${s.title} 보기`} className="relative block aspect-[9/16] w-[120px] cursor-pointer overflow-hidden rounded-xl bg-[#1d2233] p-0 text-left text-white">
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" loading="lazy" className="absolute inset-0 size-full object-cover" />
{playing && (
<iframe
src={embed(s.id)}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
tabIndex={-1}
className="pointer-events-none absolute top-1/2 left-1/2 border-0"
style={{ width: PLAYER_W, height: (PLAYER_W * 16) / 9, transform: `translate(-50%, -50%) scale(${SCALE})` }}
/>
)}
<span className="b-keep-bg absolute inset-0 bg-[linear-gradient(180deg,transparent_55%,rgba(0,0,0,.65))]" aria-hidden="true" />
<span className="absolute inset-x-2 bottom-2 line-clamp-3 text-[12px] leading-[1.3] font-bold">{s.title}</span>
</Link>
)
}
/** 쇼츠 페이지(/shorts/영상ID): 그 영상부터 위아래로 넘겨 보고, 넘기면 주소도 그 영상으로 바뀌어 그대로 공유할 수 있다 */
export function ShortsPage() {
const { id } = useParams()
const navigate = useNavigate()
const q = useQuery(listShortsOptions())
// 처음 들어온 영상만 시작점으로 쓴다 (넘기며 주소가 바뀌어도 다시 맞추지 않는다)
const [firstId] = useState(id)
const listed = q.data?.items ?? []
const items = firstId && listed.length && !listed.some((s) => s.id === firstId) ? [{ id: firstId, title: '' }, ...listed] : listed
const start = Math.max(0, items.findIndex((s) => s.id === firstId))
// 앱 안에서 들어왔으면 뒤로, 링크로 바로 들어왔으면 오늘 화면으로
const close = () => ((window.history.state as { idx?: number } | null)?.idx ? navigate(-1) : navigate('/', { replace: true }))
if (!items.length) return <div className="fixed inset-0 z-[70] bg-[#1d2233]" aria-busy={q.isPending} />
return <ShortsViewer items={items} start={start} onClose={close} onAt={(s) => navigate(`/shorts/${s.id}`, { replace: true })} />
}
/**
* 처음 열 때·넘길 때 검은 화면이 보이지 않게, 첫 장면을 받을 때까지는 표지를 보이고 앞뒤 영상도 소리 없이 틀어 첫 장면을 받아 둔 뒤 멈춰 두고, 보이는 것만 처음부터 재생한다
*/
function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; start: number; onClose: () => void; onAt: (s: ShortItem) => void }) {
const list = useRef<HTMLDivElement>(null)
const [at, setAt] = useState(start)
const [sound, setSound] = useState(false)
const tabH = useTabBarHeight()
// 첫 장면을 받은 플레이어. 그 전엔 플레이어의 검은 화면 대신 표지를 보인다
const [ready, setReady] = useState<ReadonlySet<number>>(new Set())
const frames = useRef(new Map<number, HTMLIFrameElement>())
const atRef = useRef(start)
const soundRef = useRef(false)
// 누르기로 멈춘 상태. 다른 영상으로 넘어가면 다시 재생 중으로
const paused = useRef(false)
// 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다
const startRef = useRef(start)
useEffect(() => {
// scrollIntoView 는 바깥 칸까지 굴려 버튼 줄이 헤더 밑으로 숨으므로 목록만 옮긴다
const box = list.current
if (box) box.scrollTop = box.clientHeight * startRef.current
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
return () => {
root.style.overflow = before
}
}, [])
const onEscape = useEffectEvent((e: KeyboardEvent) => e.key === 'Escape' && onClose())
useEffect(() => {
window.addEventListener('keydown', onEscape)
return () => window.removeEventListener('keydown', onEscape)
}, [])
useEffect(() => {
const box = list.current
if (!box) return
const io = new IntersectionObserver(
(entries) => {
for (const e of entries) if (e.isIntersecting) setAt(Number((e.target as HTMLElement).dataset.i))
},
{ root: box, threshold: 0.6 },
)
for (const c of box.children) io.observe(c)
return () => io.disconnect()
}, [])
// 미리 띄운 영상이 재생되기 시작하면(첫 장면을 받음) 보이는 영상이 아닐 때 멈추고 처음으로
useEffect(() => {
const onMessage = (e: MessageEvent) => {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string') return
let msg: { info?: { playerState?: number } }
try {
msg = JSON.parse(e.data)
} catch {
return
}
if (msg.info?.playerState !== PLAYING) return
for (const [i, f] of frames.current) {
if (f.contentWindow !== e.source) continue
setReady((r) => (r.has(i) ? r : new Set(r).add(i)))
if (i === atRef.current) continue
command(f, 'pauseVideo')
command(f, 'seekTo', [0, true])
}
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [])
const moved = useEffectEvent((s: ShortItem) => onAt(s))
useEffect(() => {
if (atRef.current !== at) moved(items[at])
atRef.current = at
paused.current = false
for (const [i, f] of frames.current) {
if (i === at) {
command(f, soundRef.current ? 'unMute' : 'mute')
command(f, 'playVideo')
} else {
command(f, 'pauseVideo')
command(f, 'mute')
}
}
}, [at, items])
// 마우스로도 끌어 넘긴다: 영상 위는 유튜브 iframe 이 마우스를 가져가서, 그 위에 투명한 판을 깔고 끈 만큼 목록을 옮긴다.
// 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 재생·일시정지
const drag = useRef<{ y: number; top: number; moved: boolean } | null>(null)
const lastPointer = useRef('')
const [dragging, setDragging] = useState(false)
const togglePause = () => {
paused.current = !paused.current
command(frames.current.get(atRef.current), paused.current ? 'pauseVideo' : 'playVideo')
}
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
lastPointer.current = e.pointerType
const box = list.current
if (e.pointerType !== 'mouse' || !box) return
e.currentTarget.setPointerCapture(e.pointerId)
drag.current = { y: e.clientY, top: box.scrollTop, moved: false }
setDragging(true)
}
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current
const box = list.current
if (!d || !box) return
const dy = e.clientY - d.y
if (Math.abs(dy) > 6) d.moved = true
box.scrollTop = d.top - dy
}
const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current
const box = list.current
drag.current = null
setDragging(false)
if (!d || !box) return
if (!d.moved) return togglePause()
// 30px 만 끌어도 다음·이전 영상으로, 그보다 덜 끌면 제자리로
const h = box.clientHeight
const dy = e.clientY - d.y
const base = Math.round(d.top / h)
const target = Math.min(items.length - 1, Math.max(0, base + (dy < -SWIPE_PX ? 1 : dy > SWIPE_PX ? -1 : 0)))
box.scrollTo({ top: target * h, behavior: 'smooth' })
}
const toggleSound = () => {
const on = !sound
soundRef.current = on
setSound(on)
command(frames.current.get(at), on ? 'unMute' : 'mute')
}
return (
// 헤더·탭 바는 그대로 두고 그 사이를 채운다. 흐린 배경은 반투명 헤더·탭 바 뒤까지 깐다
<div
role="region"
aria-label="날씨각 쇼츠"
className="fixed inset-0 flex flex-col overflow-hidden bg-[#1d2233] pt-[calc(54px+env(safe-area-inset-top,0px))] pb-(--shorts-tab) text-white"
style={{ '--shorts-tab': `${tabH}px` } as CSSProperties}
>
{/* 배경: 지금 영상 표지를 크게 흐려 깔아 영상 색이 번져 보이게 */}
<img
key={items[at].id}
src={`https://i.ytimg.com/vi/${items[at].id}/hqdefault.jpg`}
alt=""
aria-hidden="true"
className="absolute inset-0 size-full scale-125 object-cover opacity-70 blur-3xl"
/>
<div className="absolute inset-0 bg-black/35" aria-hidden="true" />
<div className="relative mx-auto flex h-12 w-full max-w-[440px] shrink-0 items-center justify-between px-3">
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-xl text-white', TAP44)}>
×
</button>
<button type="button" onClick={toggleSound} aria-pressed={sound} className="h-9 cursor-pointer rounded-full bg-white/15 px-3.5 text-[13px] font-bold text-white">
{sound ? '소리 끄기' : '소리 켜기'}
</button>
</div>
<div ref={list} className={cx('relative min-h-0 flex-1 overflow-y-auto [scrollbar-width:none]', !dragging && 'snap-y snap-mandatory')}>
{items.map((s, i) => (
<div key={s.id} data-i={i} className="relative grid h-full snap-start place-items-center">
<div className="relative" style={FIT}>
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" className="absolute inset-0 size-full object-cover" />
{Math.abs(i - at) <= 1 && (
<iframe
ref={(f) => {
if (f) frames.current.set(i, f)
else frames.current.delete(i)
}}
src={embed(s.id)}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => {
e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)
// 앞뒤 밖으로 밀려나 내려갔다 다시 뜬 플레이어는 첫 장면을 새로 받을 때까지 다시 숨긴다
setReady((r) => {
if (!r.has(i)) return r
const next = new Set(r)
next.delete(i)
return next
})
}}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', !ready.has(i) && 'opacity-0')}
/>
)}
<div
aria-hidden="true"
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={() => {
drag.current = null
setDragging(false)
}}
onClick={() => lastPointer.current !== 'mouse' && togglePause()}
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab')}
/>
</div>
</div>
))}
</div>
</div>
)
}
+3 -3
View File
@@ -1,9 +1,9 @@
import { useQuery } from '@tanstack/react-query'
import { useState, type ReactNode } from 'react'
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { clockShort, loadOf } from './lib'
import { clockShort, loadOf } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { MapLink, Sec, Skel, StateBox } from './ui'
+1 -1
View File
@@ -1,5 +1,5 @@
import { useSearchParams } from 'react-router'
import type { TalkTopic } from '../api/client/types.gen'
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { TalkCard } from './talk'
import { TOPICS, useTopicTalks } from './talkState'
+7 -4
View File
@@ -1,7 +1,7 @@
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
import { Link, useLocation } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import {
PostType,
RainType,
@@ -15,15 +15,17 @@ import {
type TalkData,
type TopIndex,
type WeatherSlot,
} from '../api/client/types.gen'
} from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
import { fall } from './lib'
import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { ShortsRail } from './Shorts'
import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk'
import { topicName, useTalkGroups } from './talkState'
import { useRegion } from './regionContext'
@@ -32,7 +34,7 @@ import { useSky } from './skyContext'
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
import { deg, slotAt } from './weatherText'
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'
type Mode = 'now' | TimeKind
@@ -639,6 +641,7 @@ export function TodayPage() {
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<ShortsRail />
<FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} />
{mine.map((t) => (
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
+2 -2
View File
@@ -1,8 +1,8 @@
import { useRef, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils'
import { cardBg, dateRange, loadOf, shortDay } from './lib'
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
+13 -4
View File
@@ -1,8 +1,8 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth'
import { meOptions } from '../api/client/@tanstack/react-query.gen'
import { logout as logoutOnServer } from '../api/client/sdk.gen'
import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth'
import { meOptions, meQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen'
import { AuthContext } from './authContext'
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
@@ -18,7 +18,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const me = useQuery({ ...meOptions(), enabled: !!token })
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
useEffect(() => subscribeAuth((reason) => reason === 'change' && queryClient.invalidateQueries()), [queryClient])
// 로그아웃·탈퇴 땐 내 정보 캐시를 먼저 버린다. 남겨 두면 다시 받다가 401 이 나서 로그인 창이 뜬다
useEffect(
() =>
subscribeAuth((reason) => {
if (reason !== 'change') return
if (!getAccessToken()) queryClient.removeQueries({ queryKey: meQueryKey() })
void queryClient.invalidateQueries()
}),
[queryClient],
)
const mePending = !!token && me.isPending
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending])
+1 -1
View File
@@ -1,5 +1,5 @@
import { createContext, use } from 'react'
import type { Me } from '../api/client/types.gen'
import type { Me } from '@nalssigak/shared/api/client/types.gen'
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
+1 -1
View File
@@ -1,6 +1,6 @@
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
import data from '../../seo/foliage_2026.json'
import { kst } from './lib'
import { kst } from '@nalssigak/shared/lib'
export type Kind = 'maple' | 'ginkgo'
export type Stage = 'before' | 'first' | 'peak' | 'gone'
+1 -1
View File
@@ -1,7 +1,7 @@
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import { cx } from '../lib/utils'
import type { PostReaction } from '../api/client/types.gen'
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
import { useCarousel } from './carousel'
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage'
import { PostFrame } from './Post'
+2 -2
View File
@@ -1,7 +1,7 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '../api/client/@tanstack/react-query.gen'
import type { ResAuth } from '../api/client/types.gen'
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
+2 -131
View File
@@ -1,4 +1,5 @@
import type { CSSProperties } from 'react'
import { ARTICLE_LABEL } from '@nalssigak/shared/lib'
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
@@ -10,136 +11,6 @@ export function iconSrc(name: string) {
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
}
export const MEDALS = ['gold', 'silver', 'bronze'] as const
/** 고를 수 있는 프로필 캐릭터 (백엔드 CHARACTERS 와 같아야 한다) */
export const CHARACTERS = [
['rabbit', '토끼'],
['bear', '곰'],
['dog', '강아지'],
['sun', '해님'],
['moon', '달님'],
['cloud', '구름'],
] as const
/** 프로필 배경색 (백엔드 COLORS 와 같아야 한다) */
export const AVATAR_COLORS: Record<string, string> = { orange: '#ff8e4e', blue: '#4f97e3', green: '#1f9d62', purple: '#7a5cd6', pink: '#d6457a', brown: '#a8643a' }
/** 오늘 기분 (백엔드 MOODS 와 같아야 한다) */
export const MOODS = [
['clear', '☀️', '맑음'],
['partly', '⛅', '구름 조금'],
['cloudy', '☁️', '흐림'],
['rain', '🌧️', '비'],
['thunder', '⚡', '번개'],
['snow', '❄️', '눈'],
['fog', '🌫️', '안개'],
['rainbow', '🌈', '무지개'],
] as const
export const moodEmoji = (mood?: string | null) => MOODS.find(([k]) => k === mood)?.[1]
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
// 달(1~12) → 계절 이름과 아이콘. 봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2 (서버 각 제철 기준과 같다)
const SEASONS: [string, string][] = [['겨울', 'snow'], ['봄', 'garden'], ['여름', 'sun'], ['가을', 'maple']]
export const seasonOf = (month: number) => SEASONS[Math.floor((month % 12) / 3)]
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
export function kst(input: string | Date) {
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
}
const h12 = (h: number) => h % 12 || 12
/** 18:25 → "18:25" (포스트·플랜과 같은 24시간제) */
export function clockShort(iso: string) {
const t = kst(iso)
return `${t.h}:${String(t.mi).padStart(2, '0')}`
}
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
/** 방위각 → 16방위 이름. 263 → "서" */
/** 네이버 지도에서 장소 이름(또는 주소)으로 찾기 */
export const naverMap = (query: string) => `https://map.naver.com/p/search/${encodeURIComponent(query)}`
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
export function timeWords(iso: string) {
const t = kst(iso)
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
}
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
export function ago(iso: string | null | undefined, now = Date.now()) {
if (!iso) return '오늘'
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
if (min < 5) return '방금'
if (min < 60) return `${min}분 전`
return `${Math.floor(min / 60)}시간 전`
}
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
export function dayLabel(date: string, index: number) {
if (index === 0) return '오늘'
if (index === 1) return '내일'
const [, m, d] = date.split('-').map(Number)
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
return `${WEEKDAYS[wd]} ${m}.${d}`
}
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
const at = h + minute / 60
const sunset = SUNSET_HOUR[month - 1]
if (at >= 5 && at < 11) return 'morning'
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
return 'night'
}
/** "서울 마포구" → "서울" */
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
export function dateRange(start: string, end: string) {
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
}
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', popup: 'peach', exhibition: 'lilac', concert: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
export function cardBg(icon: string, index: number) {
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
}
/** "2026-09-23" → "9.23" */
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: ['계절 소식', 'text-[#1f9d62]'], 2: ['날씨 상식', 'text-[#7a5cd6]'], 3: ['각 원리', 'text-(--orange)'] }
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_CAT[a.category]?.[0] ?? '읽을거리'} · ${a.read_minutes}분`
export type Load = 'loading' | 'error' | 'retrying' | 'ready'
type QueryLike = { data?: unknown; isPending: boolean; isError: boolean; isFetching: boolean; errorUpdateCount: number }
/** 데이터가 있으면 ready. 실패 뒤 다시 받는 중(retrying)은 처음 불러오기(loading)와 구분한다 */
export function loadOf(q: QueryLike): Load {
if (q.data !== undefined) return 'ready'
if (q.isError) return q.isFetching ? 'retrying' : 'error'
return q.isFetching && q.errorUpdateCount > 0 ? 'retrying' : 'loading'
}
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
+1 -1
View File
@@ -1,5 +1,5 @@
import { useState, type ReactNode } from 'react'
import type { MyGakPreset, MyGakRule, MyGakScore } from '../api/client/types.gen'
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { useRegion } from './regionContext'
+3 -3
View File
@@ -1,9 +1,9 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useSyncExternalStore } from 'react'
import { SITE_URL } from '../api/setup'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '../api/client/@tanstack/react-query.gen'
import { scoreMyGak } from '../api/client/sdk.gen'
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { scoreMyGak } from '@nalssigak/shared/api/client/sdk.gen'
import type { MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
+2 -2
View File
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import type { PostReaction, ResFeed } from '../api/client/types.gen'
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen'
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
+2 -2
View File
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useLocation, useNavigate } from 'react-router'
import regionPages from '../../seo/region.json'
import { nearestRegion } from '../api/client/sdk.gen'
import type { RegionData } from '../api/client/types.gen'
import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen'
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics'
import { IS_TOSS, tossLocation } from '../lib/platform'
import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
+2 -2
View File
@@ -1,12 +1,12 @@
import { createContext, use } from 'react'
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
import regionPages from '../../seo/region.json'
import type { RegionData } from '../api/client/types.gen'
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
export { DEFAULT_REGION } from '@nalssigak/shared/lib'
/** 구 하나만 보여 주는 지역 페이지: 일반 시군구, 또는 구로 나뉜 시의 구 페이지 */
export const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code)
+2 -2
View File
@@ -1,9 +1,9 @@
import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import { cx } from '../lib/utils'
import type { TopIndex } from '../api/client/types.gen'
import type { TopIndex } from '@nalssigak/shared/api/client/types.gen'
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
import { MEDALS, type TimeKind } from './lib'
import { MEDALS, type TimeKind } from '@nalssigak/shared/lib'
import { Ic } from './ui'
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
+1 -1
View File
@@ -1,5 +1,5 @@
import type { MyGak } from './myGakState'
import type { TalkData } from '../api/client/types.gen'
import type { TalkData } from '@nalssigak/shared/api/client/types.gen'
import type { WeatherWhyPayload } from './weatherWhy'
import { createContext, use } from 'react'
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides) */
+1 -1
View File
@@ -1,5 +1,5 @@
import { createContext, use } from 'react'
import type { TimeKind } from './lib'
import type { TimeKind } from '@nalssigak/shared/lib'
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
+3 -2
View File
@@ -2,9 +2,10 @@ type P = { className?: string }
const line = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' } as const
// 좋아요·댓글·보내기 세 아이콘이 나란히 놓일 때 크기가 같아 보이게: 하트는 원래 그림이 작아 10% 키우고(보이는 칸을 좁힘), 보내기는 커서 5% 줄인다
export function HeartIcon({ className }: P) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
<svg viewBox="1.1 2.75 21.8 21.8" className={className} aria-hidden="true">
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
</svg>
)
@@ -20,7 +21,7 @@ export function CommentIcon({ className }: P) {
export function SendIcon({ className }: P) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
<svg viewBox="-0.65 -0.65 25.3 25.3" className={className} aria-hidden="true">
<path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
</svg>
)
+4 -4
View File
@@ -8,14 +8,14 @@ import {
likeTalkMutation,
reportTalkMutation,
unlikeTalkMutation,
} from '../api/client/@tanstack/react-query.gen'
import { uploadTalkImage } from '../api/client/sdk.gen'
import { TalkReport, TalkTopic, type TalkData } from '../api/client/types.gen'
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen'
import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, kst } from './lib'
import { ago, kst } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { topicName, TOPICS, useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
+2 -2
View File
@@ -1,6 +1,6 @@
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '../api/client/@tanstack/react-query.gen'
import { TalkTopic, type TalkData } from '../api/client/types.gen'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
import { useRegion } from './regionContext'
// 글 주제와 피드 묶음 이름
+2 -1
View File
@@ -3,7 +3,8 @@ 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'
import { AVATAR_COLORS, moodEmoji, naverMap, type Load } from '@nalssigak/shared/lib'
import { iconSrc } from './lib'
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
+1 -1
View File
@@ -1,4 +1,4 @@
import type { WeatherWhy } from '../api/client/types.gen'
import type { WeatherWhy } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
+5
View File
@@ -0,0 +1,5 @@
{
"enabledPlugins": {
"expo@claude-plugins-official": true
}
}
+4
View File
@@ -0,0 +1,4 @@
# 앱이 부를 API 주소. 실기기에서는 localhost 대신 PC의 내부 IP (예: http://192.168.0.10:9810)
EXPO_PUBLIC_API_BASE_URL=http://localhost:9810
# 사진 경로(/season/..)를 붙일 사이트 주소
EXPO_PUBLIC_SITE_URL=https://weather.o2o.kr
+43
View File
@@ -0,0 +1,43 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo
.expo/
dist/
web-build/
expo-env.d.ts
# Native
.kotlin/
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
example
# generated native folders
/ios
/android
+41
View File
@@ -0,0 +1,41 @@
This is an Expo/React Native mobile application. Prioritize mobile-first patterns, performance, and cross-platform compatibility.
## Expo has changed — do not trust your training data
Expo ships breaking changes every SDK release. APIs you remember are likely renamed, moved, or removed. Before writing any code that touches an Expo, EAS, or React Native API:
1. Read the major version of the `expo` package in `package.json`.
2. Fetch the matching versioned docs: `https://docs.expo.dev/versions/v<major>.0.0/`
3. For anything else, fetch https://docs.expo.dev/llms.txt — an index of all Expo docs with corrections to common LLM misconceptions. Follow its links to the specific page you need; never answer from memory.
## Commands
Use `bunx` instead of `npx` if the project uses bun (`bun.lock` present).
```bash
npx expo install <package> # ALWAYS use instead of npm/yarn/pnpm/bun add — resolves SDK-compatible versions
npx expo start # start the dev server
npx expo lint # lint
npx tsc --noEmit # typecheck
npx expo-doctor # diagnose dependency and config issues
npx expo install --fix # fix incompatible package versions
```
Run lint and typecheck before declaring any task done.
## Navigation & Routing
- Use **Expo Router** for all navigation. Routes live in `src/app/` — every file there is a screen, `_layout.tsx` files define navigators. Keep non-route code (components, hooks, utils) outside `src/app/`.
- Import `Link`, `router`, and `useLocalSearchParams` from `expo-router`.
- Docs: https://docs.expo.dev/router/introduction.md
## Building with EAS
Use EAS to build, sign, and submit the app in the cloud (`eas build`, `eas submit`) and to ship over-the-air updates (`eas update`) — no local Xcode or Android Studio required. Run EAS CLI as `bunx eas-cli <command>` in Bun projects, or `npx eas-cli@latest <command>` otherwise; substitute that for bare `eas` in docs examples.
Docs: https://docs.expo.dev/eas/index.md
## Rules
- If `ios/` and `android/` directories do not exist, they are generated (Continuous Native Generation). Never create or edit them by hand — configure native behavior in `app.json` and config plugins.
- Expo Go only includes its bundled native modules. After adding a library with native code, the app needs a development build: `npx expo run:ios|android` locally, or `eas build --profile development`.
- Prefer recommended Expo modules over third-party libraries, and check your available skills before adding dependencies. Docs: https://docs.expo.dev/versions/latest/index.md
+65
View File
@@ -0,0 +1,65 @@
{
"expo": {
"name": "날씨각",
"slug": "nalssigak",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "nalssigak",
"userInterfaceStyle": "automatic",
"ios": {
"icon": "./assets/images/icon.png",
"infoPlist": {
"ITSAppUsesNonExemptEncryption": false
}
},
"android": {
"versionCode": 1000,
"adaptiveIcon": {
"backgroundColor": "#bbeafd",
"foregroundImage": "./assets/images/android-icon-foreground.png",
"backgroundImage": "./assets/images/android-icon-background.png",
"monochromeImage": "./assets/images/android-icon-monochrome.png"
},
"predictiveBackGestureEnabled": false,
"permissions": [
"android.permission.ACCESS_COARSE_LOCATION"
],
"package": "kr.o2o.nalssigak",
"blockedPermissions": [
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.SYSTEM_ALERT_WINDOW",
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"
]
},
"web": {
"output": "static",
"favicon": "./assets/images/favicon.png"
},
"plugins": [
"expo-router",
[
"expo-splash-screen",
{
"backgroundColor": "#bbeafd",
"image": "./assets/images/splash-icon.png",
"imageWidth": 200
}
],
"expo-secure-store",
"expo-sharing",
[
"expo-location",
{
"locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요."
}
],
"@react-native-google-signin/google-signin"
],
"experiments": {
"typedRoutes": true,
"reactCompiler": true
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 705 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

+29
View File
@@ -0,0 +1,29 @@
{
"cli": {
"version": ">= 16.0.0",
"appVersionSource": "remote"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal",
"env": {
"EXPO_PUBLIC_API_BASE_URL": "https://weather.o2o.kr",
"EXPO_PUBLIC_SITE_URL": "https://weather.o2o.kr"
}
},
"production": {
"autoIncrement": true,
"env": {
"EXPO_PUBLIC_API_BASE_URL": "https://weather.o2o.kr",
"EXPO_PUBLIC_SITE_URL": "https://weather.o2o.kr"
}
}
},
"submit": {
"production": {}
}
}
+10
View File
@@ -0,0 +1,10 @@
// https://docs.expo.dev/guides/using-eslint/
const { defineConfig } = require('eslint/config');
const expoConfig = require("eslint-config-expo/flat");
module.exports = defineConfig([
expoConfig,
{
ignores: ["dist/*"],
}
]);
+19
View File
@@ -0,0 +1,19 @@
const path = require('path');
const { getDefaultConfig } = require('expo/metro-config');
const { withUniwindConfig } = require('uniwind/metro');
const config = getDefaultConfig(__dirname);
// 루트 node_modules 에는 웹용 react 가 따로 있어, RN 렌더러와 맞는 앱의 react 만 쓰게 고정한다
const PINNED = ['react', 'react-dom'];
const resolveRequest = config.resolver.resolveRequest;
config.resolver.resolveRequest = (context, moduleName, platform) => {
const pinned = PINNED.find((name) => moduleName === name || moduleName.startsWith(`${name}/`));
const next = pinned ? { ...context, originModulePath: path.join(__dirname, 'package.json') } : context;
return (resolveRequest ?? context.resolveRequest)(next, moduleName, platform);
};
module.exports = withUniwindConfig(config, {
cssEntryFile: './src/global.css',
dtsFile: './src/uniwind-types.d.ts',
});
+58
View File
@@ -0,0 +1,58 @@
{
"name": "mobile",
"main": "expo-router/entry",
"version": "1.0.0",
"dependencies": {
"@expo-google-fonts/bagel-fat-one": "^0.4.0",
"@expo-google-fonts/gowun-batang": "^0.4.1",
"@expo-google-fonts/jua": "^0.4.1",
"@expo/ui": "~57.0.23",
"@nalssigak/shared": "*",
"@react-native-google-signin/google-signin": "^16.1.5",
"@tanstack/react-query": "^5.104.2",
"expo": "~57.0.28",
"expo-constants": "~57.0.21",
"expo-device": "~57.0.2",
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-image": "~57.0.5",
"expo-linear-gradient": "~57.0.2",
"expo-linking": "~57.0.12",
"expo-location": "~57.0.21",
"expo-router": "~57.0.26",
"expo-secure-store": "~57.0.4",
"expo-sharing": "~57.0.23",
"expo-splash-screen": "~57.0.10",
"expo-status-bar": "~57.0.1",
"expo-symbols": "~57.0.3",
"expo-system-ui": "~57.0.4",
"expo-web-browser": "~57.0.3",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.86.3",
"react-native-gesture-handler": "~2.32.0",
"react-native-reanimated": "4.5.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "~4.26.0",
"react-native-svg": "15.15.4",
"react-native-view-shot": "5.1.0",
"react-native-web": "~0.21.0",
"react-native-worklets": "0.10.1",
"tailwindcss": "^4.3.3",
"uniwind": "^1.12.2"
},
"devDependencies": {
"@types/react": "~19.2.2",
"eslint": "^9.0.0",
"eslint-config-expo": "~57.0.2",
"typescript": "~6.0.3"
},
"scripts": {
"start": "expo start",
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web",
"lint": "expo lint"
},
"private": true
}
+63
View File
@@ -0,0 +1,63 @@
import '@/lib/api';
import { BagelFatOne_400Regular } from '@expo-google-fonts/bagel-fat-one';
import { GowunBatang_400Regular } from '@expo-google-fonts/gowun-batang';
import { Jua_400Regular, useFonts } from '@expo-google-fonts/jua';
import { QueryClientProvider } from '@tanstack/react-query';
import { Tabs } from 'expo-router/tabs';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect } from 'react';
import { View } from 'react-native';
import '@/global.css';
import { SkyBg } from '@/components/sky-bg';
import { TabBar } from '@/components/tab-bar';
import { FirstLoad } from '@/components/first-load';
import { SheetProvider } from '@/components/sheets';
import { TopBar } from '@/components/top-bar';
import { AuthProvider } from '@/lib/auth';
import { queryClient } from '@/lib/query-client';
import { RegionProvider } from '@/lib/region';
import { SkyProvider, useSky } from '@/lib/sky';
SplashScreen.preventAutoHideAsync();
function Shell() {
const { kind } = useSky();
return (
<View className="flex-1">
<SkyBg />
<StatusBar style={kind === 'night' ? 'light' : 'dark'} />
<Tabs initialRouteName="index" tabBar={(props) => <TabBar {...props} />} screenOptions={{ header: () => <TopBar />, sceneStyle: { backgroundColor: 'transparent' } }}>
{/* 메인인 오늘 탭을 가운데에 */}
<Tabs.Screen name="sky" />
<Tabs.Screen name="gak" />
<Tabs.Screen name="index" />
<Tabs.Screen name="week" />
<Tabs.Screen name="season" />
</Tabs>
<FirstLoad />
</View>
);
}
export default function RootLayout() {
const [loaded, error] = useFonts({ Jua_400Regular, BagelFatOne_400Regular, GowunBatang_400Regular });
useEffect(() => {
if (loaded || error) SplashScreen.hideAsync();
}, [loaded, error]);
if (!loaded && !error) return null;
return (
<QueryClientProvider client={queryClient}>
<SkyProvider>
<AuthProvider>
<RegionProvider>
<SheetProvider>
<Shell />
</SheetProvider>
</RegionProvider>
</AuthProvider>
</SkyProvider>
</QueryClientProvider>
);
}
+65
View File
@@ -0,0 +1,65 @@
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen';
import { kst, loadOf, seasonOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { Text } from '@/components/text';
import { GakGrid, GridSkel } from '@/components/gak/grid';
import { Podium, PodiumSkel } from '@/components/gak/podium';
import { Chips, Ic, Sec, StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core';
// 마지막 칩은 지금 계절의 제철 각 (예: 가을 각)
const CATS: readonly (readonly [Cat, string])[] = [
['all', '전체'],
['out', '밖에서 놀기'],
['food', '먹고 마시기'],
['home', '집안일'],
['life', '생활 고민'],
['core', `${seasonOf(kst(new Date()).mo)[0]} 각`],
];
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE };
export default function GakScreen() {
const { region } = useRegion();
const { open } = useSheet();
const [cat, setCat] = useState<Cat>('all');
const q = useQuery(listIndicesOptions({ query: { region: region.code, category: CAT_PARAM[cat], core: cat === 'core' ? true : undefined } }));
const articles = useQuery(listArticlesOptions({ query: { category: ArticleCategory.GAK } }));
const top = q.data?.top3 ?? [];
const items = q.data?.items ?? [];
const day = q.data?.day?.split('-').map(Number);
const load = loadOf(q);
const howto = articles.data?.articles?.find((a) => a.code === 'howgak');
return (
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={q.isRefetching && !q.isPlaceholderData} onRefresh={() => q.refetch()} />}>
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name}`} />
{top.length === 3 ? <Podium top={top} dim={q.isPlaceholderData} /> : load === 'loading' ? <PodiumSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} />}
<Chips items={CATS} value={cat} onChange={setCat} />
{load === 'loading' ? (
<GridSkel />
) : !items.length ? (
// 실패 안내·다시 시도는 위 받침대 자리에 한 번만
<StateBox load="ready" empty={load === 'ready' ? '이 분야는 오늘 계산된 각이 없어요.' : '각 목록을 불러오지 못했어요.'} hold={<GridSkel />} boxClassName="inset-3" />
) : (
<GakGrid items={items} dim={q.isPlaceholderData} />
)}
{howto && load !== 'loading' && (
<Pressable onPress={() => open({ type: 'article', articleId: howto.article_id })} className="mx-3 mt-1.5 flex-row items-center gap-3 rounded-[22px] bg-[#ece7ff] p-3.5">
<Ic name="bulb" size={44} />
<View className="flex-1">
<Text className="font-jua text-[17px] text-[#28304a]">각 점수는 어떻게 매길까?</Text>
<Text className="text-[12.5px] font-semibold text-[#5a6380]">기온·비·바람·습도·공기·시간대 6가지로 계산해요</Text>
</View>
</Pressable>
)}
</ScrollView>
);
}
+71
View File
@@ -0,0 +1,71 @@
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { kst, loadOf } from '@nalssigak/shared/lib';
import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today';
import { useQuery } from '@tanstack/react-query';
import { Fragment, type ReactNode } from 'react';
import { RefreshControl, ScrollView } from 'react-native';
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
import { Hero } from '@/components/today/hero';
import { EventsBand, SeasonBand, Stories, StoriesSkel, TopBand } from '@/components/today/rails';
import { Sec, StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
import { useSky } from '@/lib/sky';
export default function TodayScreen() {
const { region } = useRegion();
const feed = useQuery(getFeedOptions({ query: { region: region.code } }));
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }));
const { preview } = useSky();
const f = feed.data;
const posts = (f?.posts ?? []).filter(isAppPost);
const stories = atSlot(f?.stories ?? [], preview);
const sloted = preview != null && stories !== f?.stories;
const bands = f?.bands;
const nowAt = f?.hero?.now_at;
const load = loadOf(feed);
const refresh = () => Promise.all([feed.refetch(), today.refetch()]);
// 웹처럼 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand events={bands.events} /> : null],
[6, bands?.top5?.length ? <TopBand items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null],
];
return (
// 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}>
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more="/gak" />
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} boxClassName="inset-x-3 top-3 bottom-1" />}
{load === 'loading' && (
<>
<PostCardSkel />
<PostCardSkel />
</>
)}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다. 다시 시도는 위 각 줄에 한 번만 */}
{load !== 'loading' && !posts.length && (
<StateBox
load="ready"
empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'}
hold={
<>
<PostCardSkel />
<PostCardSkel />
</>
}
boxClassName="inset-x-3 top-3.5"
/>
)}
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{bandAt.find(([at]) => at === i + 1)?.[1]}
</Fragment>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</ScrollView>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen';
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { RefreshControl, ScrollView, View } from 'react-native';
import { ArticleRow, HeadSkel, RowsSkel, SeasonHead } from '@/components/season/parts';
import { Chips, StateBox } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
const CATS = [
['all', '전체'],
['season', '계절 소식'],
['tip', '날씨 상식'],
['gak', '각 원리'],
] as const;
const CAT_PARAM = { season: ArticleCategory.SEASON, tip: ArticleCategory.TIP, gak: ArticleCategory.GAK } as const;
export default function SeasonScreen() {
const { open } = useSheet();
const [cat, setCat] = useState<(typeof CATS)[number][0]>('all');
const week = useQuery(getSeasonWeekOptions());
const arts = useQuery(listArticlesOptions(cat === 'all' ? undefined : { query: { category: CAT_PARAM[cat] } }));
const w = week.data;
const list = arts.data?.articles ?? [];
const weekLoad = loadOf(week);
const artLoad = loadOf(arts);
const refresh = () => Promise.all([week.refetch(), arts.refetch()]);
return (
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={(week.isRefetching || arts.isRefetching) && !arts.isPlaceholderData} onRefresh={refresh} />}>
{w?.headline ? <SeasonHead week={w} onPress={() => open({ type: 'seasonWeek' })} /> : weekLoad === 'loading' ? <HeadSkel /> : <StateBox load={weekLoad} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." hold={<HeadSkel />} />}
<Chips items={CATS} value={cat} onChange={setCat} />
<View className="mt-1.5" style={{ opacity: arts.isPlaceholderData ? 0.6 : 1 }}>
{artLoad === 'loading' && <RowsSkel />}
{artLoad !== 'loading' && !list.length && <StateBox load={artLoad} onRetry={() => arts.refetch()} empty="읽을거리가 아직 없어요." hold={<RowsSkel />} boxClassName="inset-3" />}
{list.map((a) => (
<ArticleRow key={a.article_id} article={a} onPress={() => open({ type: 'article', articleId: a.article_id })} />
))}
</View>
</ScrollView>
);
}
+101
View File
@@ -0,0 +1,101 @@
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { RefreshControl, ScrollView, View } from 'react-native';
import { DayTiles, Li, LiSkel, ScoreHelp, SkyHero, Timeline } from '@/components/sky/parts';
import { Sec, Skel, StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
const THREE = [0, 1, 2];
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i);
/** 히어로 글자 자리 (실패·빈 안내를 같은 높이로 띄우려고) */
function HeroHold() {
return (
<View>
<Skel className="h-7 w-[230px]" />
<Skel className="mt-2 w-[180px]" />
</View>
);
}
function LiSkels({ n }: { n: number[] }) {
return (
<View className="mx-3 mt-1.5">
{n.map((i) => (
<LiSkel key={i} last={i === n.length - 1} />
))}
</View>
);
}
export default function SkyScreen() {
const { region } = useRegion();
const sky = useQuery(getSkyOptions({ query: { region: region.code } }));
const ranking = useQuery(getSkyRankingOptions());
const load = loadOf(sky);
const rankLoad = loadOf(ranking);
const plans = sky.data?.plans ?? [];
const [picked, setPicked] = useState<string>();
// 타일을 누르면 그날, 아니면 다음에 오는 날
const plan = plans.find((p) => p.day === picked) ?? sky.data?.plan ?? undefined;
const spots = (sky.data?.spots ?? []).slice(0, 3);
const items = (ranking.data?.items ?? []).slice(0, 8);
const rise = plan?.kind === 'sunrise';
const refresh = () => Promise.all([sky.refetch(), ranking.refetch()]);
return (
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={sky.isRefetching && !sky.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: sky.isPlaceholderData ? 0.6 : 1 }}>
{plan || load === 'loading' ? (
<SkyHero plan={plan} />
) : (
<SkyHero>
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroHold />} boxClassName="inset-x-0 top-1.5 bottom-0" />
</SkyHero>
)}
{plans.length > 1 && <DayTiles plans={plans} day={plan?.day} onPick={setPicked} />}
{plan && <ScoreHelp plan={plan} />}
<Sec title="언제 보면 좋을까" />
{plan?.timeline?.length || load === 'loading' ? <Timeline rows={plan?.timeline} kind={plan?.kind} /> : <StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} />}
{!rise && <Sec title="가까운 노을 명소" sub="가까운 순 · 방향은 내 동네에서 본 쪽" />}
{rise ? null : spots.length ? (
<View className="mx-3 mt-1.5">
{spots.map((p, i) => (
<Li key={p.no} no={p.no} title={p.name} sub={p.direction ? `${p.direction}쪽` : null} right={`${p.distance_km}km`} place={p.name} last={i === 2} />
))}
{/* 3곳이 안 되면 빈 줄로 높이를 지켜 아래 순위가 밀리지 않게 */}
{THREE.slice(spots.length).map((i) => (
<LiSkel key={`ghost-${i}`} ghost last={i === 2} />
))}
</View>
) : load === 'loading' ? (
<View className="mx-3 mt-1.5">
{THREE.map((i) => (
<LiSkel key={i} last={i === 2} />
))}
</View>
) : (
// 실패 안내·다시 시도는 위 히어로에 한 번만
<StateBox load="ready" empty={load === 'ready' ? '근처에 등록된 노을 명소가 없어요.' : '명소 정보를 불러오지 못했어요.'} hold={<LiSkels n={THREE} />} />
)}
<Sec title="전국 노을 순위" sub={ranking.data?.summary ?? '오늘 기준'} />
{items.length ? (
<View className="mx-3 mt-1.5">
{items.map((r, i) => (
<Li key={r.region_code} no={r.rank} title={r.name} sub={[r.note, r.situation_label].filter(Boolean).join(' · ')} right={`${r.score}점`} mine={r.region_code === region.code} last={i === items.length - 1} />
))}
</View>
) : rankLoad === 'loading' ? (
<View className="mx-3 mt-1.5">
{RANK_SKELS.map((i) => (
<LiSkel key={i} last={i === RANK_SKELS.length - 1} />
))}
</View>
) : (
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." hold={<LiSkels n={RANK_SKELS} />} boxClassName="inset-x-3 top-1.5 bottom-0" />
)}
</ScrollView>
);
}
+152
View File
@@ -0,0 +1,152 @@
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { loadOf, shortDay } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useRef, useState } from 'react';
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { Text } from '@/components/text';
import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/week/sections';
import { DaysSkel, EventsSkel, PickSkel, PlacesSkel, RankSkel } from '@/components/week/skels';
import { Chips, Rail, Sec, Skel, StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
import { shareView } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
const RANK_TABS_HOLD = [
['토', '토요일'],
['일', '일요일'],
] as const;
export default function WeekScreen() {
const { region } = useRegion();
const week = useQuery(getWeekOptions({ query: { region: region.code } }));
const days = week.data?.days ?? [];
const [picked, setPicked] = useState<string | null>(null);
// 지역을 바꾸면 동네 고르기는 전체로 돌아간다
const [areaPick, setAreaPick] = useState({ region: region.code, area: '전체' });
const area = areaPick.region === region.code ? areaPick.area : '전체';
// 처음에는 이번 토요일을 고른다
const sel = days.find((d) => d.day === picked) ?? days.find((d) => d.weekday === '토') ?? days[0];
const places = useQuery({ ...listPlacesOptions({ query: { region: region.code, day: sel?.day, area: area === '전체' ? undefined : area } }), enabled: !!sel });
const events = useQuery(listEventsOptions({ query: { region: region.code } }));
const ranking = useQuery(getWeekRankingOptions());
const rankDays = ranking.data?.days ?? [];
const [rankPick, setRankPick] = useState<string | null>(null);
const rankDay = rankDays.find((d) => d.day === rankPick) ?? rankDays[0];
const rankItems = (rankDay?.items ?? []).slice(0, 10);
const rankLoad = loadOf(ranking);
const areas = places.data?.areas ?? [];
const rainy = places.data?.rainy ?? sel?.is_rainy;
const placeList = places.data?.places ?? [];
const eventList = events.data?.events ?? [];
const weekLoad = loadOf(week);
const eventLoad = loadOf(events);
// 날씨(고른 날)가 와야 명소를 부를 수 있다
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready';
const refresh = () => Promise.all([week.refetch(), events.refetch(), ranking.refetch(), sel ? places.refetch() : null]);
const pickShot = useRef<View>(null);
// 고른 날 추천 카드를 이미지로
const sendPlan = () => {
if (!sel) return;
const message = [`${sel.weekday}요일 일정 · ${region.name}`, sel.headline, sel.summary, sel.pick, `날씨각 ${SITE_URL}`].filter(Boolean).join('\n');
void shareView(pickShot, { title: `${sel.weekday}요일 일정`, message });
};
const placeSub = sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? undefined : '날씨에 맞춰 골라 보여 줘요';
return (
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={week.isRefetching && !week.isPlaceholderData} onRefresh={refresh} />}>
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
{days.length ? (
<DayStrip days={days} selected={sel?.day} onPick={setPicked} dim={week.isPlaceholderData} />
) : weekLoad === 'loading' ? (
<>
<DaysSkel />
<PickSkel />
</>
) : (
<StateBox
load={weekLoad}
onRetry={() => week.refetch()}
empty="날씨가 아직 없어요."
hold={
<>
<DaysSkel />
<PickSkel />
</>
}
/>
)}
{sel && (
<View ref={pickShot} collapsable={false}>
<PickCard day={sel} />
</View>
)}
{(sel || weekLoad !== 'ready') && (
<>
<Text className="mx-4 mt-3.5 text-[13.5px] font-bold text-ink2">30km 안 · 데이트 명소</Text>
<Chips items={['전체', ...areas].map((a) => [a, a] as const)} value={area} onChange={(a) => setAreaPick({ region: region.code, area: a })} disabled={!areas.length} />
</>
)}
{/* 명소 데이터가 없으면 칸 전체를 숨긴다 */}
{!(placeLoad === 'ready' && !placeList.length) && (
<>
<View className="-mt-2.5">
<Sec title="날씨 맞춤 데이트 명소" sub={placeSub} />
</View>
{!placeSub && <Skel className="mx-4 w-56" />}
{placeList.length ? (
<View style={{ opacity: places.isPlaceholderData ? 0.6 : 1 }}>
<Rail>
{placeList.map((p, i) => (
<PlaceCard key={p.place_id} place={p} index={i} />
))}
</Rail>
</View>
) : placeLoad === 'loading' ? (
<PlacesSkel />
) : (
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? '30km 안에 데이트 명소가 아직 없어요.' : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} />
)}
</>
)}
<Sec title="이번 주말 전국 날씨 순위" sub="낮 10~17시 나들이 날씨 · 대표 지역 30곳 중 10위까지" />
{rankDays.length ? (
<Chips items={rankDays.map((d) => [d.day, `${d.weekday}요일 ${shortDay(d.day)}`] as const)} value={rankDay?.day ?? ''} onChange={setRankPick} />
) : (
<Chips items={RANK_TABS_HOLD} value="토" onChange={() => undefined} disabled />
)}
{rankItems.length ? (
<View className="mx-3 mt-1.5" style={{ opacity: ranking.isPlaceholderData ? 0.6 : 1 }}>
{rankItems.map((r) => (
<RankRow key={r.region_code} item={r} mine={r.region_code === region.code} />
))}
</View>
) : rankLoad === 'loading' ? (
<RankSkel />
) : (
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="주말 예보가 아직 없어요." hold={<RankSkel />} boxClassName="inset-x-3 top-1.5 bottom-0" />
)}
<Sec title="가까운 축제·행사" sub="30km 안 · 앞으로 30일 · 그날 날씨까지 같이 봐요" />
{eventList.length ? (
<View style={{ opacity: events.isPlaceholderData ? 0.6 : 1 }}>
{eventList.map((e, i) => (
<EventRow key={e.event_id} event={e} index={i} />
))}
</View>
) : eventLoad === 'loading' ? (
<EventsSkel />
) : (
<StateBox load={eventLoad} onRetry={() => events.refetch()} empty="30km 안에 열리는 행사가 아직 없어요. 다른 지역을 골라 보세요." hold={<EventsSkel />} boxClassName="inset-x-3 top-2.5 bottom-0" />
)}
{/* 행사 수가 정해진 뒤에 붙여 목록이 늘어날 때 밀리지 않게 */}
{eventLoad !== 'loading' && (
<Pressable onPress={sendPlan} disabled={!sel} className="mx-3 mt-4 items-center rounded-full border-b-[5px] border-orange-deep bg-orange p-[13px] disabled:opacity-60">
<Text className="font-jua text-[17px] text-white">이번 주말 일정 보내기</Text>
</Pressable>
)}
</ScrollView>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { useEffect, type ReactNode } from 'react';
import type { ViewStyle } from 'react-native';
import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
/** 하늘에서 떨어진 뒤 둥둥 (웹 b-fall: b-drop 1.05초 뒤 b-float 무한). d·f 는 밀리초 */
export function Fall({ d, f, amp = 9, style, children }: { d: number; f: number; amp?: number; style?: ViewStyle; children: ReactNode }) {
const reduce = useReducedMotion();
const drop = useSharedValue(reduce ? 1 : 0);
const float = useSharedValue(0);
useEffect(() => {
if (reduce) return;
drop.value = withDelay(d, withTiming(1, { duration: 1050, easing: Easing.bezier(0.22, 0.9, 0.3, 1) }));
float.value = withDelay(d + 1050, withRepeat(withTiming(1, { duration: f / 2, easing: Easing.inOut(Easing.ease) }), -1, true));
return () => {
cancelAnimation(drop);
cancelAnimation(float);
};
}, [reduce, d, f, drop, float]);
const anim = useAnimatedStyle(() => {
const p = drop.value;
const y = interpolate(p, [0, 0.72, 0.86, 1], [-400, 0, -10, 0]) - amp * float.value;
const rot = interpolate(p, [0, 0.72, 1], [-10, 2, 0]) + 1.2 * float.value;
return {
opacity: interpolate(p, [0, 0.55, 1], [0, 1, 1]),
transform: [{ translateY: y }, { rotate: `${rot}deg` }, { scaleX: interpolate(p, [0, 0.72, 0.86, 1], [1, 1.04, 1, 1]) }, { scaleY: interpolate(p, [0, 0.72, 0.86, 1], [1, 0.96, 1, 1]) }],
};
});
return <Animated.View style={[style, anim]}>{children}</Animated.View>;
}
+76
View File
@@ -0,0 +1,76 @@
import type { TimeKind } from '@nalssigak/shared/lib';
import { useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import { Text } from '@/components/text';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withSequence, withTiming } from 'react-native-reanimated';
import { Ic } from '@/components/ui';
import { useSky } from '@/lib/sky';
// 덮개 색: 시간대별 하늘 맨 위 색을 반쯤 비치게
const COVER: Record<TimeKind, string> = {
morning: 'rgb(255 230 207 / 0.72)',
day: 'rgb(214 235 255 / 0.72)',
sunset: 'rgb(255 216 194 / 0.72)',
night: 'rgb(14 20 51 / 0.72)',
};
/** 캐릭터가 통통 뛴다 (웹 b-hop) */
function Hop({ name }: { name: string }) {
const reduce = useReducedMotion();
const t = useSharedValue(0);
useEffect(() => {
if (reduce) return;
const ease = Easing.bezier(0.3, 0, 0.4, 1);
t.value = withRepeat(withSequence(withTiming(1, { duration: 405, easing: ease }), withTiming(0, { duration: 495, easing: ease })), -1);
return () => cancelAnimation(t);
}, [reduce, t]);
const style = useAnimatedStyle(() => ({
transform: [{ translateY: -22 * t.value }, { scaleX: 1.06 - 0.09 * t.value }, { scaleY: 0.94 + 0.09 * t.value }],
transformOrigin: 'bottom',
}));
return (
<Animated.View style={style}>
<Ic name={name} size={88} />
</Animated.View>
);
}
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */
export function FirstLoad() {
const queryClient = useQueryClient();
const { kind } = useSky();
const [done, setDone] = useState(false);
const [gone, setGone] = useState(false);
// 받기 시작했다가 받는 게 없어지면 끝. 느린 망에서도 10초 넘게 막지 않는다 (그 뒤는 화면 안 스켈레톤이 맡는다)
useEffect(() => {
let seen = false;
const unsubscribe = queryClient.getQueryCache().subscribe(() => {
if (queryClient.isFetching() > 0) seen = true;
else if (seen) setDone(true);
});
const id = setTimeout(() => setDone(true), 10000);
return () => {
unsubscribe();
clearTimeout(id);
};
}, [queryClient]);
const shown = useSharedValue(1);
useEffect(() => {
if (!done) return;
shown.value = withTiming(0, { duration: 400 });
const id = setTimeout(() => setGone(true), 400);
return () => clearTimeout(id);
}, [done, shown]);
const fade = useAnimatedStyle(() => ({ opacity: shown.value }));
if (gone) return null;
return (
<Animated.View pointerEvents={done ? 'none' : 'auto'} accessibilityRole="progressbar" accessibilityLabel="날씨 불러오는 중" style={[StyleSheet.absoluteFill, { zIndex: 50, backgroundColor: COVER[kind] }, fade]}>
<View className="flex-1 items-center justify-center gap-3">
<Hop name={kind === 'night' ? 'bear' : 'rabbit'} />
<Text className="font-jua text-[19px] text-ink">날씨 불러오는 중…</Text>
</View>
</Animated.View>
);
}
+52
View File
@@ -0,0 +1,52 @@
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Skel } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
const CELL = 'w-[32%] items-center rounded-[22px] border-b-[5px] border-shade bg-card px-1.5 pt-3 pb-2.5';
const SKELS = Array.from({ length: 9 }, (_, i) => i);
export function GridSkel() {
return (
<View className="flex-row flex-wrap justify-between gap-y-2 p-3">
{SKELS.map((i) => (
<View key={i} className={`${CELL} gap-1.5`}>
<View className="size-[50px] rounded-full bg-skel" />
<Skel className="w-14" />
<Skel className="h-5 w-8" />
</View>
))}
</View>
);
}
/** 3칸 바둑판. 지금 시간대가 아니거나 제철이 아닌 각은 흐리게 */
export function GakGrid({ items, dim }: { items: IndexSummary[]; dim: boolean }) {
const { open } = useSheet();
return (
<View className="flex-row flex-wrap gap-y-2 p-3" style={{ columnGap: '2%', opacity: dim ? 0.6 : 1 }}>
{items.map((g) => (
<Pressable
key={g.index_id}
onPress={() => open({ type: 'gak', indexId: g.index_id })}
accessibilityLabel={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, ${g.in_season === false ? '제철 아님' : '지금 시간대 아님'}`}
className={`${CELL} ${g.active ? '' : 'opacity-55'}`}
>
{g.active && <Text className="absolute top-[7px] left-[9px] font-jua text-[13px] text-ink3">{g.rank}</Text>}
{g.season && <Text className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</Text>}
<Ic name={g.icon} size={50} />
<Text numberOfLines={1} className="mt-1 font-jua text-[15px] text-ink">
{g.name}
</Text>
{g.active ? (
<Text className={`font-bagel text-[22px] leading-[24px] ${g.score < 50 ? 'text-ink3' : 'text-orange'}`}>{g.score}</Text>
) : (
<Text className="py-1 text-[12px] leading-[14px] font-extrabold text-ink3">{g.in_season === false ? '제철 아님' : '지금 아님'}</Text>
)}
</Pressable>
))}
</View>
);
}
+57
View File
@@ -0,0 +1,57 @@
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
import { MEDALS } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Skel } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
// 가운데가 높은 3칸: 2위 · 1위 · 3위
const ORDER = [1, 0, 2] as const;
const FLEX = [1.15, 1, 1];
/** 1~3위 받침대와 같은 칸의 스켈레톤 */
export function PodiumSkel() {
return (
<View className="flex-row gap-1.5 px-3 pt-3">
{ORDER.map((k) => (
<View key={k} style={{ flex: FLEX[k] }} className={`items-center gap-1.5 rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
<View className={`aspect-square rounded-full bg-skel ${k === 0 ? 'w-20' : 'w-[62px]'}`} />
<Skel className="w-16" />
<Skel className="h-6 w-10" />
<Skel className="w-full" />
</View>
))}
</View>
);
}
export function Podium({ top, dim }: { top: IndexSummary[]; dim: boolean }) {
const { open } = useSheet();
const { kind } = useSky();
return (
<View className="flex-row gap-1.5 px-3 pt-3" style={{ opacity: dim ? 0.6 : 1 }}>
{ORDER.map((k) => {
const g = top[k];
return (
<Pressable key={g.index_id} style={{ flex: FLEX[k] }} onPress={() => open({ type: 'gak', indexId: g.index_id })} className={`items-center overflow-hidden rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
{k === 0 && kind !== 'night' && <LinearGradient colors={['#fff1c4', '#ffffff']} style={{ position: 'absolute', inset: 0 }} />}
<View>
<Ic name={g.icon} size={k === 0 ? 80 : 62} />
<Ic name={MEDALS[k]} size={28} style={{ position: 'absolute', top: -6, left: -12 }} />
</View>
<View className="mt-1.5 flex-1 justify-center">
<Text className="text-center font-jua text-base text-ink">
{k + 1}위 {g.name}
</Text>
</View>
<Text className="font-bagel text-[30px] leading-[32px] text-orange">{g.score}</Text>
{g.summary && <Text className="text-center text-[11.5px] font-semibold text-ink2">{g.summary}</Text>}
</Pressable>
);
})}
</View>
);
}
+29
View File
@@ -0,0 +1,29 @@
import Svg, { Path } from 'react-native-svg';
export const HEART = 'M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z';
type P = { size: number; color: string };
export function HeartIcon({ size, color, filled }: P & { filled: boolean }) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill={filled ? color : 'none'} stroke={color} strokeWidth={1.9}>
<Path d={HEART} />
</Svg>
);
}
export function CommentIcon({ size, color }: P) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinejoin="round">
<Path d="M20.5 12a8.5 8.5 0 0 1-12.6 7.4L3.5 20.5l1.2-4.2A8.5 8.5 0 1 1 20.5 12z" />
</Svg>
);
}
export function SendIcon({ size, color }: P) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
<Path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
</Svg>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { useEffect } from 'react';
import { View } from 'react-native';
import Animated, { Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withTiming } from 'react-native-reanimated';
import Svg, { Path } from 'react-native-svg';
import { HEART } from '@/components/post/icons';
// 튀어 나가는 작은 하트: x·y 이동, 회전, 색 (웹 BURST)
const BURST: [number, number, number, string][] = [
[-86, -60, -24, '#ff3b5c'],
[84, -66, 22, '#ff8e4e'],
[-104, 18, -40, '#ffc86e'],
[102, 24, 36, '#ff3b5c'],
[-48, -104, -8, '#ff8aa0'],
[52, -100, 12, '#ffc86e'],
];
function Bit({ dx, dy, rot, color }: { dx: number; dy: number; rot: number; color: string }) {
const p = useSharedValue(0);
useEffect(() => {
p.value = withDelay(80, withTiming(1, { duration: 900, easing: Easing.bezier(0.2, 0.8, 0.3, 1) }));
}, [p]);
const style = useAnimatedStyle(() => ({
opacity: interpolate(p.value, [0, 0.25, 1], [0, 1, 0]),
transform: [{ translateX: dx * p.value }, { translateY: dy * p.value }, { scale: interpolate(p.value, [0, 1], [0.4, 1.1]) }, { rotate: `${rot * p.value}deg` }],
}));
return (
<Animated.View style={[{ position: 'absolute' }, style]}>
<Svg viewBox="0 0 24 24" width={20} height={20} fill={color}>
<Path d={HEART} />
</Svg>
</Animated.View>
);
}
function Toast() {
const p = useSharedValue(0);
useEffect(() => {
p.value = withTiming(1, { duration: 1300, easing: Easing.bezier(0.2, 0.9, 0.3, 1) });
}, [p]);
const style = useAnimatedStyle(() => ({
opacity: interpolate(p.value, [0, 0.18, 0.78, 1], [0, 1, 1, 0]),
transform: [{ translateY: interpolate(p.value, [0, 0.18, 0.78, 1], [14, 0, 0, -8]) }, { scale: interpolate(p.value, [0, 0.18, 0.3, 1], [0.85, 1.06, 1, 1]) }],
}));
return (
<Animated.View className="absolute top-[58%] rounded-full bg-white px-4 py-2" style={[{ boxShadow: '0 8px 18px rgb(40 48 74 / 0.18)' }, style]}>
<Animated.Text className="font-jua text-[17px] text-heart">좋아요했어요!</Animated.Text>
</Animated.View>
);
}
/** 좋아요 때 하트 조각이 튀어 나가고 '좋아요했어요!' 가 떴다 사라진다 */
export function LikeBurst() {
const reduce = useReducedMotion();
if (reduce) return null;
return (
<View pointerEvents="none" className="absolute inset-0 items-center justify-center" accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
{BURST.map(([dx, dy, rot, color], k) => (
<Bit key={k} dx={dx} dy={dy} rot={rot} color={color} />
))}
<Toast />
</View>
);
}
+29
View File
@@ -0,0 +1,29 @@
import type { ReactNode } from 'react';
import { ScrollView, View, type NativeScrollEvent, type NativeSyntheticEvent } from 'react-native';
/** 옆으로 한 장씩 넘기는 슬라이드 (웹 Embla 캐러셀 대신 가로 paging ScrollView) */
export function Pager({ width, height, onIndex, children }: { width: number; height: number; onIndex: (i: number) => void; children: ReactNode[] }) {
const onEnd = (e: NativeSyntheticEvent<NativeScrollEvent>) => onIndex(Math.round(e.nativeEvent.contentOffset.x / width));
return (
<ScrollView horizontal pagingEnabled showsHorizontalScrollIndicator={false} scrollEnabled={children.length > 1} onMomentumScrollEnd={onEnd} style={{ width, height }}>
{children.map((c, i) => (
<View key={i} style={{ width, height }}>
{c}
</View>
))}
</ScrollView>
);
}
/** 슬라이드 위치 점 */
export function Dots({ n, index }: { n: number; index: number }) {
if (n < 2) return null;
const items = Array.from({ length: n }, (_, i) => i);
return (
<View className="flex-row justify-center gap-1.5 pt-2" accessibilityElementsHidden>
{items.map((i) => (
<View key={i} className={`h-1.5 rounded-full ${i === index ? 'w-4 bg-orange' : 'w-1.5 bg-ink3/40'}`} />
))}
</View>
);
}
+237
View File
@@ -0,0 +1,237 @@
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { PostType, type PostData, type ResFeed } from '@nalssigak/shared/api/client/types.gen';
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect, useRef, useState } from 'react';
import { Animated, Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import Svg, { Path } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
import { CommentIcon, HEART, HeartIcon, SendIcon } from '@/components/post/icons';
import { LikeBurst } from '@/components/post/like-burst';
import { Dots, Pager } from '@/components/post/pager';
import { slideBg, SlideView, type Slide } from '@/components/post/slides';
import { Ic, Skel } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { useSheet } from '@/lib/sheet';
import { shareView } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
const ACCOUNTS: Partial<Record<PostType, readonly [string, string]>> = {
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
[PostType.GAK]: ['오늘의 각', 'rabbit'],
[PostType.SUNSET]: ['노을', 'sunset'],
[PostType.SEASON]: ['계절 소식', 'maple'],
[PostType.EVENT]: ['가까운 행사', 'fireworks'],
[PostType.TIP]: ['날씨 상식', 'bulb'],
[PostType.WEEK]: ['주말 예보', 'calendar'],
[PostType.ALERT]: ['생활 알림', 'umbrella'],
[PostType.TOMORROW]: ['내일 미리보기', 'moon'],
[PostType.QUOTE]: ['오늘의 한 문장', 'letter'],
[PostType.WEEKEND_PLAN]: ['주말 플랜', 'calendar'],
[PostType.AIR]: ['미세먼지', 'vent'],
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
};
const isSlide = (s: PostData['slides'][number]): s is Slide => s.kind !== 'image';
/** 앱이 그릴 줄 아는 글만 (웹 전용 글 종류·이미지 슬라이드가 든 글은 뺀다) */
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS && p.slides.every(isSlide);
type PostProps = { post: PostData };
/** 받아 둔 피드 데이터에도 좋아요를 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */
function patchFeed(queryClient: QueryClient, postId: number, patch: Partial<PostData>) {
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
feed?.posts ? { ...feed, posts: feed.posts.map((p) => (p.post_id === postId ? { ...p, ...patch } : p)) } : feed,
);
}
/** 한 줄 카드 (흐린 날 노을처럼 큰 그림이 필요 없는 소식) */
function LineCard({ post }: PostProps) {
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
return (
<View className="mx-3 mt-3.5 flex-row items-center gap-3 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3" accessibilityLabel={post.title}>
<Ic name={post.icon || avatar} size={40} />
<View className="flex-1">
<Text className="text-xs font-bold text-ink3">{account}</Text>
<Text className="text-sm text-ink2">
<Text className="font-jua text-base text-ink">{post.title}</Text> {post.caption}
</Text>
</View>
</View>
);
}
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
export function PostCard({ post }: PostProps) {
return post.size === 'line' ? <LineCard post={post} /> : <FullCard post={post} />;
}
/** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */
export function PostCardSkel() {
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityElementsHidden>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full bg-skel" />
<View className="gap-1.5">
<Skel className="w-12" />
<Skel className="w-16" />
</View>
</View>
<View className="aspect-[4/5] bg-skel" />
<View className="flex-row gap-3.5 px-3 pt-2.5 pb-1">
<View className="size-7 rounded-full bg-skel" />
<View className="size-7 rounded-full bg-skel" />
<View className="size-7 rounded-full bg-skel" />
</View>
<View className="gap-2 px-3 pt-1 pb-3">
<Skel className="w-20" />
<Skel className="w-4/5" />
<Skel className="w-32" />
<Skel className="w-8" />
</View>
</View>
);
}
/** 좋아요 때 가운데에 커졌다 사라지는 하트 */
function HeartPop() {
const [v] = useState(() => new Animated.Value(0));
useEffect(() => {
Animated.timing(v, { toValue: 1, duration: 800, useNativeDriver: true }).start();
}, [v]);
const opacity = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0, 1, 1, 0] });
const scale = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0.3, 1.1, 1, 1] });
return (
<Animated.View pointerEvents="none" className="absolute inset-0 items-center justify-center" style={{ opacity, transform: [{ scale }] }}>
<Svg viewBox="0 0 24 24" width={112} height={112} fill="#ff3b5c">
<Path d={HEART} />
</Svg>
</Animated.View>
);
}
function FullCard({ post }: PostProps) {
const { open } = useSheet();
const { loggedIn } = useAuth();
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const liked = !!post.liked;
const likeCount = post.like_count;
const queryClient = useQueryClient();
const like = useMutation(likePostMutation());
const unlike = useMutation(unlikePostMutation());
const [width, setWidth] = useState(0);
const [index, setIndex] = useState(0);
const [pop, setPop] = useState(0);
const [likeFailed, setLikeFailed] = useState(0);
const lastTap = useRef(0);
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
const n = post.slides.length;
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values);
const comments = () => open({ type: 'comments', postId: post.post_id });
const shot = useRef<View>(null);
// 지금 보고 있는 슬라이드를 이미지로
const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` });
useEffect(() => {
if (!likeFailed) return;
const t = setTimeout(() => setLikeFailed(0), 2500);
return () => clearTimeout(t);
}, [likeFailed]);
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
const setLike = (on: boolean) => {
if (!loggedIn) return open({ type: 'login' });
if (on === liked || like.isPending || unlike.isPending) return;
if (on) setPop((p) => p + 1);
setLikeFailed(0);
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) });
const revert = () => {
patch({ liked, like_count: likeCount });
setLikeFailed(Date.now());
};
(on ? like : unlike).mutate(
{ path: { post_id: post.post_id } },
{
onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()),
onError: revert,
},
);
};
const onTap = () => {
const now = Date.now();
if (now - lastTap.current < 320) {
if (liked && loggedIn) setPop((p) => p + 1);
else setLike(true);
}
lastTap.current = now;
};
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={post.title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full p-0.5">
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
<View className="flex-1 items-center justify-center rounded-full bg-card">
<Ic name={avatar} size={22} />
</View>
</View>
<View>
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
<Text className="text-xs font-semibold text-ink2">{account}</Text>
</View>
</View>
<Pressable onPress={onTap} onLayout={(e) => setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}>
<View ref={shot} collapsable={false}>
{width > 0 && (
<Pager width={width} height={(width * 5) / 4} onIndex={setIndex}>
{post.slides.filter(isSlide).map((s, i) => (
<SlideView key={i} slide={s} bg={slideBg(post, s)} />
))}
</Pager>
)}
</View>
{n > 1 && (
<View pointerEvents="none" className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px]">
<Text className="text-xs font-extrabold text-white">
{index + 1}/{n}
</Text>
</View>
)}
{pop > 0 && <HeartPop key={pop} />}
{pop > 0 && <LikeBurst key={`b${pop}`} />}
{likeFailed > 0 && (
<View pointerEvents="none" className="absolute inset-x-0 bottom-4 items-center px-4" accessibilityRole="alert">
<Text className="overflow-hidden rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</Text>
</View>
)}
</Pressable>
<Dots n={n} index={index} />
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
<Pressable onPress={() => setLike(!liked)} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={liked ? heart : ink} filled={liked} />
</Pressable>
<Pressable onPress={comments} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
<CommentIcon size={26} color={ink} />
</Pressable>
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
<SendIcon size={26} color={ink} />
</Pressable>
</View>
<Text className="px-3 py-0.5 text-sm font-extrabold text-ink">좋아요 {likeCount.toLocaleString()}개</Text>
<Text className="px-3 py-0.5 text-sm text-ink">
<Text className="font-extrabold">날씨각 </Text>
{post.caption}
</Text>
<Pressable onPress={comments}>
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">오늘</Text>
</View>
);
}
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more