Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
872d68e738 | ||
|
|
90773081c2 | ||
|
|
e22564bc20 | ||
|
|
fb2e6c4fac | ||
|
|
512ae6b591 | ||
|
|
01263f4149 | ||
|
|
387929683c | ||
|
|
a875dfabe6 | ||
|
|
096d1effb0 | ||
|
|
928e9053cf | ||
|
|
e1b5efc01b | ||
|
|
a6251db762 | ||
|
|
814e64931d |
No files matched your search
@@ -1,16 +1,16 @@
|
|||||||
---
|
---
|
||||||
description: 오늘 날씨 타로·코디 카드를 만들어 검수하고 킹서버에 승인 대기로 저장한다 (올리지는 않는다)
|
description: 오늘 날씨 타로·코디 카드를 둘 다 만들어 검수하고 날씨각 피드와 인스타에 올린다 (/daily-tarot + /daily-ootd)
|
||||||
argument-hint: <타로 주제> <코디 스타일: casual|semi|formal|street|minimal>
|
argument-hint: "<타로 주제> <코디 스타일> 예) 건강 운동 minimal"
|
||||||
---
|
---
|
||||||
|
|
||||||
오늘 인스타 카드를 만든다. 인자: `$ARGUMENTS` (앞은 타로 주제, 마지막 단어는 코디 스타일. 비어 있으면 타로 주제는 비우고 코디는 casual).
|
오늘 인스타 카드를 만든다. 인자: `$ARGUMENTS` — 앞은 타로 주제(비어 있으면 Claude 가 오늘 날씨에 맞는 주제를 고른다), 마지막 단어가 casual·semi·formal·street·minimal 중 하나면 코디 스타일(없으면 minimal=꾸안꾸). 코디 포스트 하나는 스타일 하나: 네 사람 모두 같은 스타일.
|
||||||
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. **인스타·날씨각 피드에 올리지 않는다** — 승인 대기 저장까지만.
|
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 타로는 `/daily-tarot` 의 순서대로, 코디는 `/daily-ootd` 의 순서대로 각각 만들고 검수한 뒤 올린다(두 명령 파일의 단계를 그대로 따른다).
|
||||||
|
|
||||||
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||||
2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다.
|
2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다.
|
||||||
3. 타로: `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait`.
|
3. 타로: `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait`.
|
||||||
출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||||
4. 코디: `{"style":"<스타일>","theme":"sky"}` 를 base64url 로 만들어 `npm run card -- ootd --copy <값> --post-wait`. 빠진 그림은 자동 생성된다(장당 1~5분).
|
4. 코디(그날 코디): `npm run card -- ootd --daily --style <스타일> --color sky --post-wait`. 무신사 인기 스냅 중 그 스타일 태그(꾸안꾸·오피스룩·캐주얼·스트릿·정장)가 붙은 것에서 사람 4명(20-30대·40대~ 여·남) 코디를 고르고, Claude 가 옷 목록을 뽑고, Codex 가 참고 사진대로 플랫레이 그림을 그린다(사람당 2~4분). 고른 스냅 주소와 옷 목록이 출력된다. "스냅이 없어요"·"저장하지 못했어요" 가 나오면 멈추고 보고한다.
|
||||||
5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 옷 목록 줄의 옷이 그림에 전부 있고 추가 옷이 없는지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다.
|
5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 그림 아래 옷 목록의 옷이 그림에 전부 있고 추가 옷이 없는지, 스냅 사진(`out/<날짜>/snaps/<사람>/snap.jpg`)과 옷·색이 같은지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다.
|
||||||
6. 새 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/ootd admin/src/assets/tarot-bg` 후 `feat: <날짜> 카드 그림(…)` 로 커밋한다 (Claude 서명 없이).
|
6. 새 타로 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/tarot-bg` 후 `feat: <날짜> 각 카드 그림(…)` 로 커밋한다 (Claude 서명 없이). 코디 그림(`admin/public/daily`)은 커밋하지 않는다.
|
||||||
7. 보고(한국어, 짧게): 킹서버 카드 번호 2개(승인 대기), 만든 JPEG 경로, 새 그림 수, 검수에서 고친 것, 남은 이슈. 올리는 건 사용자가 관리자 '만든 카드' 탭이나 "올려" 로 한다.
|
7. 보고(한국어, 짧게): 킹서버 카드 번호 2개(승인 대기), 만든 JPEG 경로, 참고한 스냅 주소 4개, 검수에서 고친 것, 남은 이슈. 올리는 건 사용자가 관리자 '만든 카드' 탭이나 "올려" 로 한다.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
description: 오늘의 코디 카드 4장(20-30대·40대~ 여·남, 스타일 하나)을 무신사 인기 스냅으로 만들어 검수하고 날씨각 피드와 인스타에 올린다
|
||||||
|
argument-hint: "<스타일> minimal(꾸안꾸)·casual·semi(오피스)·formal·street (비우면 minimal)"
|
||||||
|
---
|
||||||
|
|
||||||
|
오늘의 코디 카드를 만들어 올린다. 인자: `$ARGUMENTS` — 코디 스타일 하나(minimal=꾸안꾸, casual=캐주얼, semi=세미정장·오피스, formal=정장, street=스트릿). 비어 있으면 minimal. 포스트 하나는 스타일 하나: 네 사람 모두 같은 스타일.
|
||||||
|
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 검수를 통과한 뒤에만 올린다(올린 건 되돌릴 수 없다).
|
||||||
|
|
||||||
|
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||||
|
2. 만들기(승인 대기로 저장까지): `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- ootd --daily --style <스타일> --color sky --post-wait`. 출력 끝의 `카드 N` 번호를 적어 둔다.
|
||||||
|
무신사 인기 스냅 중 그 스타일 태그가 붙은 것에서 사람 4명 코디를 고르고(최근 14일에 쓴 스냅 제외), Claude 가 옷 목록을 뽑고, Codex 가 스냅 사진·상품 썸네일을 참고해 플랫레이 그림을 그린다(사람당 2~4분, 총 10~15분). 고른 스냅 주소·옷 목록이 출력된다. "스냅이 없어요"·"저장하지 못했어요"·"Codex 실행이 실패" 가 나오면 멈추고 보고한다. 로그의 `rmcp … AuthRequired` 는 Codex 내부 경고라 무시한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||||
|
3. 검수(예외 없음): 만든 JPEG 4장을 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 그림이 비어 있지 않은지, 그림 아래 옷 목록의 옷이 그림에 전부 있고 추가 옷이 없는지, 그림 속 사람·얼굴·글자, 스냅 사진(`admin/out/<날짜>/snaps/<사람>/snap.jpg`)과 옷·색이 같은지, 이름표 줄이 날씨 줄과 겹치지 않는지, 날씨 줄 수치가 예보(`https://weather.o2o.kr/v1/weather/today?region=1114000000`)와 맞는지. 틀리면 고치고 다시 만들어(2번, 새 카드 번호) 다시 본다. 못 고치면 올리지 말고 보고한다.
|
||||||
|
4. 올리기(검수 통과 시): `curl -s -X POST "http://localhost:5175/api/cards/<카드 N>/publish?target=king"` → `post_id` 확인, 이어서 `curl -s -X POST --max-time 600 "http://localhost:5175/api/cards/<카드 N>/instagram?target=king"` → `ig_media_id`. 인스타 링크: `~/projects/o2o-weather/.env` 의 `INSTAGRAM_ACCESS_TOKEN` 으로 `GET https://graph.instagram.com/v24.0/<ig_media_id>?fields=permalink` (토큰 값은 출력하지 않는다).
|
||||||
|
5. TODO.md 인스타 홍보 표에 한 줄(카드·포스트 번호, 인스타 링크, 참고 스냅 4개) 적고 `docs:` 커밋, `git push origin sns:main`. 코디 그림(`admin/public/daily`)은 커밋하지 않는다.
|
||||||
|
6. 보고(한국어, 짧게): 인스타 링크, 킹서버 카드·포스트 번호, 참고한 스냅 주소 4개, 검수에서 고친 것, 남은 이슈.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
description: 오늘의 날씨 타로 카드 5장을 만들어 검수하고 날씨각 피드와 인스타에 올린다
|
||||||
|
argument-hint: "<타로 주제> 예) 건강 운동 · 연애 썸 · 경제 주식 (비우면 Claude가 고름)"
|
||||||
|
---
|
||||||
|
|
||||||
|
오늘의 날씨 타로 카드를 만들어 올린다. 인자: `$ARGUMENTS` — 타로 주제(대주제 소주제). 비어 있으면 Claude 가 오늘 날씨에 맞는 주제를 고른다.
|
||||||
|
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 검수를 통과한 뒤에만 올린다(올린 건 되돌릴 수 없다).
|
||||||
|
|
||||||
|
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
|
||||||
|
2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다.
|
||||||
|
3. 만들기(승인 대기로 저장까지): `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait` (주제가 없으면 `--topic` 없이). 출력 끝의 `카드 N` 번호를 적어 둔다.
|
||||||
|
출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). 빠진 각 카드 그림은 Codex 가 자동으로 만든다(장당 1~5분). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||||
|
4. 검수(예외 없음): 만든 JPEG 5장을 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 카드 그림 누락, 그림 속 사람·글자, 리딩 문구의 수치·하늘 묘사가 예보와 맞는지, 말투(3문장, "~할 수 있어요" 남발·덕담 금지). 틀리면 고치고 다시 만들어(3번, 새 카드 번호) 다시 본다. 못 고치면 올리지 말고 보고한다.
|
||||||
|
5. 올리기(검수 통과 시): `curl -s -X POST "http://localhost:5175/api/cards/<카드 N>/publish?target=king"` → `post_id` 확인, 이어서 `curl -s -X POST --max-time 600 "http://localhost:5175/api/cards/<카드 N>/instagram?target=king"` → `ig_media_id`. 인스타 링크: `~/projects/o2o-weather/.env` 의 `INSTAGRAM_ACCESS_TOKEN` 으로 `GET https://graph.instagram.com/v24.0/<ig_media_id>?fields=permalink` (토큰 값은 출력하지 않는다).
|
||||||
|
6. 새 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/tarot-bg` 후 `feat: <날짜> 각 카드 그림(…)` 로 커밋한다 (Claude 서명 없이). TODO.md 인스타 홍보 표에 한 줄(카드·포스트 번호, 인스타 링크) 적고 `docs:` 커밋, `git push origin sns:main`.
|
||||||
|
7. 보고(한국어, 짧게): 인스타 링크, 킹서버 카드·포스트 번호, 새 그림 수, 검수에서 고친 것, 남은 이슈.
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 저장소 루트를 빌드 대상으로 쓰는 건 frontend 이미지뿐이라 frontend·shared·루트 package 파일만 넘긴다
|
|
||||||
*
|
|
||||||
!package.json
|
|
||||||
!package-lock.json
|
|
||||||
!frontend
|
|
||||||
!shared
|
|
||||||
!mobile/package.json
|
|
||||||
**/node_modules
|
|
||||||
**/dist
|
|
||||||
**/*.log
|
|
||||||
**/.DS_Store
|
|
||||||
@@ -4,9 +4,6 @@
|
|||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
|
||||||
# npm workspaces 의존성 (frontend·mobile·shared 가 루트 하나를 같이 쓴다)
|
|
||||||
node_modules/
|
|
||||||
|
|
||||||
# Python 바이트코드/캐시
|
# Python 바이트코드/캐시
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|||||||
@@ -268,52 +268,13 @@
|
|||||||
| [ ] | 인스타 릴스(20초, 2.5D: Codex 3D 렌더풍 배경 + 카메라 패럴랙스, 무료 BGM, API로 업로드) — 백엔드에 mp4 공개 주소 + REELS 게시 추가 필요 | 사용자 요청 (10/24) | `backend/services/external/instagram.py` |
|
| [ ] | 인스타 릴스(20초, 2.5D: Codex 3D 렌더풍 배경 + 카메라 패럴랙스, 무료 BGM, API로 업로드) — 백엔드에 mp4 공개 주소 + REELS 게시 추가 필요 | 사용자 요청 (10/24) | `backend/services/external/instagram.py` |
|
||||||
| [ ] | 인스타에 올라간 불량 게시물 삭제(앱에서만 가능): 소개 카드 De3SUTtoDGR·De3ycbAIPVw(스샷 잘림)·De31G7VIBEc(7·8번 장 치우침), 릴스 18152745022535272(폰 잘림), 10/25 꾸안꾸 코디 De58VfXINy0(20-30대와 40대~ 옷이 같음)·De5-8gboL-c(40대 여자 롱가디건·여름 옷)·De6B2gwIMXF(이름표 자리 어긋남) — 킹서버 포스트 3961·3962·3963은 deleted=true로 숨김 | 10/24·10/25 검수 실패 | — |
|
| [ ] | 인스타에 올라간 불량 게시물 삭제(앱에서만 가능): 소개 카드 De3SUTtoDGR·De3ycbAIPVw(스샷 잘림)·De31G7VIBEc(7·8번 장 치우침), 릴스 18152745022535272(폰 잘림), 10/25 꾸안꾸 코디 De58VfXINy0(20-30대와 40대~ 옷이 같음)·De5-8gboL-c(40대 여자 롱가디건·여름 옷)·De6B2gwIMXF(이름표 자리 어긋남) — 킹서버 포스트 3961·3962·3963은 deleted=true로 숨김 | 10/24·10/25 검수 실패 | — |
|
||||||
| [ ] | 소개 카드 최종본(`admin/out/2026-10-24/소개카드_1~8.jpg`, 10/24 21:54 — 8장 1:1 검수 완료, 모서리 캐릭터는 1번만·4·6·8번은 3D 스틸 안 캐릭터)과 3D 릴스(`admin/out/2026-10-24/릴스_3D.mp4`·표지 `릴스_3D_표지.jpg`, 21프레임 검수 완료) — 사용자가 "올려"라고 할 때만 올림. 릴스 음악은 HeyGen 로그인(`~/.local/bin/heygen auth login --oauth`) 뒤 `npx hyperframes media-use resolve --type bgm` | 10/24 | `admin/reels/intro3d/` |
|
| [ ] | 소개 카드 최종본(`admin/out/2026-10-24/소개카드_1~8.jpg`, 10/24 21:54 — 8장 1:1 검수 완료, 모서리 캐릭터는 1번만·4·6·8번은 3D 스틸 안 캐릭터)과 3D 릴스(`admin/out/2026-10-24/릴스_3D.mp4`·표지 `릴스_3D_표지.jpg`, 21프레임 검수 완료) — 사용자가 "올려"라고 할 때만 올림. 릴스 음악은 HeyGen 로그인(`~/.local/bin/heygen auth login --oauth`) 뒤 `npx hyperframes media-use resolve --type bgm` | 10/24 | `admin/reels/intro3d/` |
|
||||||
| [ ] | 코디 옷 데이터 — 세미정장·정장·스트릿·꾸안꾸 4스타일은 7개 기온 구간 전부 20-30대와 40대~ 옷이 같음(캐주얼만 다름, warm·꾸안꾸는 10/25 고침). 40대~ 여/남 옷 목록 54개를 새로 써서 검토받고 반영 | 10/25 발견 | `admin/image-prompts/ootd.json` |
|
| [x] | 코디 옷 데이터 — 세미정장·정장·스트릿·꾸안꾸 4스타일은 7개 기온 구간 전부 20-30대와 40대~ 옷이 같음(캐주얼만 다름, warm·꾸안꾸는 10/25 고침). 40대~ 여/남 옷 목록 54개를 새로 써서 검토받고 반영 — 10/26 그날 코디(--daily)로 대체해 고정 데이터는 예비용만 | 10/25 발견 | `admin/image-prompts/ootd.json` |
|
||||||
|
| [x] | 코디 카드 매일 다르게 — 고정 옷 데이터 대신 무신사 스냅 공개 API에서 오늘 구간 인기 코디를 사람별(40대~ 단정 태그 우선)로 골라 Claude가 옷 목록 추출, Codex가 참고 사진 첨부로 플랫레이 생성(`npm run card -- ootd --daily`, `/daily-cards`). 10/26 4장 검수 통과. 에이블리는 공개 API 없음(앱 전용)이라 미사용 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs`, `snap.mjs`, `outfit.mjs`, `codex-image.mjs` |
|
||||||
|
| [x] | 10/26 세미정장 코디(그날 코디 첫 게시) — 킹서버 카드 12→포스트 4275, 인스타 https://www.instagram.com/p/De8O2kqATrl/. 무신사 스냅 4개 참고, 4장 1:1 검수 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs` |
|
||||||
|
| [x] | 10/26 몸 컨디션 타로(건강: 등산각·자전거각·산책각) — 킹서버 카드 13→포스트 4276, 인스타 https://www.instagram.com/p/De8Zw7MIEVW/. 기획에서 3번 산책각 비 시점 틀린 것 피드백으로 고침. card.mjs --post-wait 가 ECONNRESET 으로 두 번 실패해 post-king.py 로 저장 | 사용자 요청 (10/26) | `admin/scripts/card.mjs` |
|
||||||
|
| [x] | 각 카드 그림 미리 생성 — 가을에 나올 만한 28장(피크닉·캠핑·놀이공원·빨래·단풍·억새·테니스·골프·군고구마·붕어빵·군밤·사진산책·별보기·환기·세차·이불빨래·데이트·치맥·막걸리·파전·우산·넷플릭스·집콕·한강밤바람·멍뭉산책·센치·감성노래·낚시) + 기존 8 = 36/68. 여름·한겨울 전용 32장은 철 되면 생성 | 사용자 요청 (10/26) | `admin/src/assets/gak-card/` |
|
||||||
|
| [ ] | 카드 자동화 다음 단계 — ① 생성 직후 자동 검사(Claude 비전: 옷 개수·사람·글자·추가 옷, 불합격 1회 재생성) ② 승인 대기 카드 메일/Teams 알림 + 서명 토큰 승인 링크(`GET /v1/card/{id}/approve`) ③ 맥 launchd 매일 06:30 `claude -p "/daily-cards"` ④ 그림 세트가 차면 킹서버로 이전 | 사용자 요청 (10/26) | `backend/router/v1/card/card.py`, `admin/scripts/` |
|
||||||
| [ ] | 앱 헤더가 400~448px 폭에서 컨테이너를 넘쳐 로그인 버튼이 잘림(`frontend/src/b/BLayout.tsx` TopBar). 캡처는 456px로 찍어 피했지만 실제 폰(430·440px)에서도 잘릴 수 있음 | 10/24 캡처 중 발견 | `frontend/src/b/BLayout.tsx` |
|
| [ ] | 앱 헤더가 400~448px 폭에서 컨테이너를 넘쳐 로그인 버튼이 잘림(`frontend/src/b/BLayout.tsx` TopBar). 캡처는 456px로 찍어 피했지만 실제 폰(430·440px)에서도 잘릴 수 있음 | 10/24 캡처 중 발견 | `frontend/src/b/BLayout.tsx` |
|
||||||
| [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` |
|
| [ ] | `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` |
|
| [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` |
|
|
||||||
@@ -25,3 +25,6 @@ dist-ssr
|
|||||||
|
|
||||||
# npm run card 결과
|
# npm run card 결과
|
||||||
out
|
out
|
||||||
|
|
||||||
|
# 그날 코디 그림 (scripts/daily-ootd.mjs 가 만들고 카드가 /daily/... 로 읽는다)
|
||||||
|
public/daily
|
||||||
@@ -55,6 +55,25 @@ VITE_API_BASE_URL=http://localhost:9810 npm run card -- tarot --topic 주식 [--
|
|||||||
- 관리자 서버가 비밀값을 `/api/post`·`/api/cards`에서만 붙인다. 브라우저엔 안 나간다. 킹서버 키는 킹서버 `.env`의 `ADMIN_API_KEY`와 같은 값.
|
- 관리자 서버가 비밀값을 `/api/post`·`/api/cards`에서만 붙인다. 브라우저엔 안 나간다. 킹서버 키는 킹서버 `.env`의 `ADMIN_API_KEY`와 같은 값.
|
||||||
- 켜는 예: `VITE_API_BASE_URL=http://localhost:9810 ADMIN_API_KEY=… KING_ADMIN_API_KEY=… npm run dev`
|
- 켜는 예: `VITE_API_BASE_URL=http://localhost:9810 ADMIN_API_KEY=… KING_ADMIN_API_KEY=… npm run dev`
|
||||||
|
|
||||||
|
## 그날 코디 (무신사 인기 스냅 → 옷 추출 → 참고 사진대로 그림)
|
||||||
|
|
||||||
|
코디 카드는 고정 데이터(`image-prompts/ootd.json` 구간×스타일 옷) 대신 **그날 무신사 인기 스냅**으로 만든다. 같은 날씨라도 매일 다른 코디가 나온다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
VITE_API_BASE_URL=https://weather.o2o.kr npm run card -- ootd --daily --style minimal --color sky --post-wait
|
||||||
|
```
|
||||||
|
|
||||||
|
포스트 하나는 스타일 하나(`--style`, 기본 minimal=꾸안꾸): 네 사람 모두 그 스타일 태그(`scripts/snap.mjs STYLE_TAGS`)가 붙은 스냅에서 고르고 제목도 그 스타일로 통일한다.
|
||||||
|
|
||||||
|
흐름(`scripts/daily-ootd.mjs`):
|
||||||
|
1. 오늘 예보로 기온 구간을 정한다(`scripts/daily-ootd.mjs weatherToday`).
|
||||||
|
2. `scripts/snap.mjs`: 무신사 스냅 공개 API에서 구간에 맞는 태그(가을코디·간절기코디·겨울코디…)와 단정 키워드(오피스룩·댄디룩…)로 인기 스냅을 모으고, 상품 카테고리로 상의·하의·신발이 다 있는 것만 남긴 뒤 사람별(40대~ 먼저, 단정 태그 가산점)로 하나씩 고른다. 45일 지난 스냅, 구간에 안 맞는 아우터(패딩·코트 등)·반바지는 뺀다. 사진·상품 썸네일은 `out/<날짜>/snaps/<사람>/`에 참고용으로만 받고 어디에도 올리지 않는다.
|
||||||
|
3. `scripts/outfit.mjs`: Claude CLI(sonnet, Read 로 사진을 봄)가 자리별(top·outer·bottom·shoes·bag) 한글 이름표와 영어 그림 설명을 뽑는다.
|
||||||
|
4. `scripts/codex-image.mjs`: Codex 에 스냅 사진·상품 썸네일을 첨부(`-i`)해 같은 옷·색으로 우리 플랫레이 스타일 그림을 그린다 → `public/daily/<날짜>-<사람>.webp` (git 에 넣지 않음).
|
||||||
|
5. 카드는 `copy.outfits`(JSON 문자열)로 이름표·그림 주소를 받는다(`src/cards/ootd.ts dailyOutfits`). 제목은 Claude 가 정한 스타일 한 단어(꾸안꾸·오피스룩…).
|
||||||
|
|
||||||
|
에이블리는 공개 API가 없어 쓰지 않는다(앱 전용). 고정 데이터 방식(`--daily` 없이)은 그대로 남아 있다.
|
||||||
|
|
||||||
## 카드 그림 만들기 (Codex 이미지 생성)
|
## 카드 그림 만들기 (Codex 이미지 생성)
|
||||||
|
|
||||||
**그림은 그날 만드는 카드에 필요한 것만 그때 만든다.** 조합(기온 구간 × 스타일 × 사람, 타로 78장)을 미리 일괄로 만들지 않는다. Codex 사용량이 한정돼 있다.
|
**그림은 그날 만드는 카드에 필요한 것만 그때 만든다.** 조합(기온 구간 × 스타일 × 사람, 타로 78장)을 미리 일괄로 만들지 않는다. Codex 사용량이 한정돼 있다.
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post).
|
// --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post).
|
||||||
// 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION)
|
// 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION)
|
||||||
import { execFileSync } from 'node:child_process'
|
import { execFileSync } from 'node:child_process'
|
||||||
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||||
import { resolve } from 'node:path'
|
import { resolve } from 'node:path'
|
||||||
|
|
||||||
const SLIDES = { tarot: 5, ootd: 4, intro: 8 }
|
const SLIDES = { tarot: 5, ootd: 4, intro: 8 }
|
||||||
@@ -34,11 +34,14 @@ let copy = flag('--copy')
|
|||||||
const topic = flag('--topic')
|
const topic = flag('--topic')
|
||||||
const feedback = flag('--feedback')
|
const feedback = flag('--feedback')
|
||||||
const color = flag('--color')
|
const color = flag('--color')
|
||||||
|
const styleArg = flag('--style')
|
||||||
const outArg = flag('--out')
|
const outArg = flag('--out')
|
||||||
const take = (name) => args.includes(name) && args.splice(args.indexOf(name), 1).length > 0
|
const take = (name) => args.includes(name) && args.splice(args.indexOf(name), 1).length > 0
|
||||||
const noImages = take('--no-images')
|
let noImages = take('--no-images')
|
||||||
const postNow = take('--post')
|
const postNow = take('--post')
|
||||||
const postWait = take('--post-wait')
|
const postWait = take('--post-wait')
|
||||||
|
// --daily: 코디를 고정 데이터 대신 그날 무신사 인기 스냅에서 뽑아 그린다 (scripts/daily-ootd.mjs)
|
||||||
|
const daily = take('--daily')
|
||||||
const [template] = args
|
const [template] = args
|
||||||
|
|
||||||
if (!SLIDES[template]) fail(`사용: npm run card -- <${Object.keys(SLIDES).join('|')}> [--topic 주제] [--feedback 피드백] [--color ${THEMES.join('|')}] [--copy 값] [--out 폴더]`)
|
if (!SLIDES[template]) fail(`사용: npm run card -- <${Object.keys(SLIDES).join('|')}> [--topic 주제] [--feedback 피드백] [--color ${THEMES.join('|')}] [--copy 값] [--out 폴더]`)
|
||||||
@@ -62,6 +65,16 @@ if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template
|
|||||||
console.log(`주제: ${body.topic}`)
|
console.log(`주제: ${body.topic}`)
|
||||||
for (const [k, v] of Object.entries(body.copy)) console.log(` ${k}: ${v.replaceAll('\n', ' / ')}`)
|
for (const [k, v] of Object.entries(body.copy)) console.log(` ${k}: ${v.replaceAll('\n', ' / ')}`)
|
||||||
copy = Buffer.from(JSON.stringify({ ...current, ...body.copy })).toString('base64url')
|
copy = Buffer.from(JSON.stringify({ ...current, ...body.copy })).toString('base64url')
|
||||||
|
// 타로: 오늘 고른 각을 적어 두면 다음 7일은 다른 각이 나온다 (scripts/plan.mjs recentCodes)
|
||||||
|
if (template === 'tarot') {
|
||||||
|
const file = resolve('out/tarot-history.json')
|
||||||
|
const today = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||||
|
const history = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {}
|
||||||
|
const codes = ['c1', 'c2', 'c3'].map((k) => body.copy[k]).filter(Boolean)
|
||||||
|
history[today] = [...new Set([...(history[today] ?? []), ...codes])]
|
||||||
|
mkdirSync(resolve('out'), { recursive: true })
|
||||||
|
writeFileSync(file, JSON.stringify(history, null, 1))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -72,6 +85,19 @@ if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template
|
|||||||
console.log(`다시 그리거나 피드백할 때: --copy ${copy}`)
|
console.log(`다시 그리거나 피드백할 때: --copy ${copy}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||||
|
const outDir = resolve(outArg ?? `out/${day}`)
|
||||||
|
|
||||||
|
if (daily) {
|
||||||
|
if (template !== 'ootd') fail('--daily 는 ootd 템플릿에서만 써요.')
|
||||||
|
const { runDailyOotd, toCardOutfits } = await import('./daily-ootd.mjs')
|
||||||
|
// 포스트 하나는 스타일 하나: --style <casual|semi|formal|street|minimal>, 없으면 --copy 의 style, 그것도 없으면 꾸안꾸
|
||||||
|
const style = styleArg ?? decode(copy).style ?? 'minimal'
|
||||||
|
const { outfits } = await runDailyOotd({ outDir, style })
|
||||||
|
copy = Buffer.from(JSON.stringify({ ...decode(copy), style, outfits: JSON.stringify(toCardOutfits(outfits)) })).toString('base64url')
|
||||||
|
noImages = true
|
||||||
|
}
|
||||||
|
|
||||||
// 그날 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (관리자 서버 /api/gen-image, 한 장씩)
|
// 그날 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (관리자 서버 /api/gen-image, 한 장씩)
|
||||||
if (!noImages) {
|
if (!noImages) {
|
||||||
const start = await fetch(`${ADMIN_URL}/api/gen-image`, {
|
const start = await fetch(`${ADMIN_URL}/api/gen-image`, {
|
||||||
@@ -94,8 +120,6 @@ if (!noImages) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
|
||||||
const outDir = resolve(outArg ?? `out/${day}`)
|
|
||||||
mkdirSync(outDir, { recursive: true })
|
mkdirSync(outDir, { recursive: true })
|
||||||
|
|
||||||
const files = []
|
const files = []
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// Codex CLI의 이미지 생성 도구로 그림 한 장을 만들어 webp 로 저장한다. gen-image.mjs(고정 데이터 그림)와 daily-ootd.mjs(그날 코디 그림)가 같이 쓴다.
|
||||||
|
import { execFileSync } from 'node:child_process'
|
||||||
|
import { mkdtempSync, readdirSync, rmSync } from 'node:fs'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { join } from 'node:path'
|
||||||
|
|
||||||
|
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다)
|
||||||
|
export const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {{ id: string, prompt: string, outPath: string, images?: string[], log?: (s: string) => void }} job
|
||||||
|
* images: 참고 사진(그 옷·색을 따라 그리게 할 때). 결과는 outPath(webp, 가로 1024).
|
||||||
|
* @returns {'ok' | 'not-saved'} 실패(한도·로그인)는 throw
|
||||||
|
*/
|
||||||
|
export function drawWithCodex({ id, prompt, outPath, images = [], log = console.log }) {
|
||||||
|
const work = mkdtempSync(join(tmpdir(), `gen-${id}-`))
|
||||||
|
const task = [
|
||||||
|
images.length
|
||||||
|
? '첨부한 참고 사진(코디 사진·상품 사진)의 옷·색·소재·실루엣을 그대로 따르되, 아래 프롬프트의 스타일로 새 그림을 내장 이미지 생성 도구로 만든다 (사진을 복사하지 말고, 사람은 절대 그리지 않는다).'
|
||||||
|
: '내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
|
||||||
|
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
|
||||||
|
'통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.',
|
||||||
|
'',
|
||||||
|
prompt,
|
||||||
|
].join('\n')
|
||||||
|
log(`${id}: Codex로 그리는 중…${images.length ? ` (참고 사진 ${images.length}장)` : ''}`)
|
||||||
|
try {
|
||||||
|
// -i 는 파일을 여러 개 받아서 뒤의 프롬프트까지 파일로 읽는다 → 프롬프트는 stdin 으로 준다
|
||||||
|
const imageArgs = images.flatMap((p) => ['-i', p])
|
||||||
|
execFileSync('codex', ['exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', ...imageArgs], { input: task, stdio: ['pipe', 'ignore', 'inherit'] })
|
||||||
|
} catch (e) {
|
||||||
|
rmSync(work, { recursive: true, force: true })
|
||||||
|
throw new Error(`${id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
|
||||||
|
}
|
||||||
|
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
|
||||||
|
if (!png) {
|
||||||
|
log(`${id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
|
||||||
|
return 'not-saved'
|
||||||
|
}
|
||||||
|
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath])
|
||||||
|
rmSync(work, { recursive: true, force: true })
|
||||||
|
log(`${id}: ${outPath}`)
|
||||||
|
return 'ok'
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
// 그날 코디: 오늘 예보 → 무신사 인기 스냅에서 사람별 코디 선정 → Claude 가 옷 목록 추출 → Codex 가 참고 사진대로 플랫레이 그림 → 카드용 copy.
|
||||||
|
// 사용: node scripts/daily-ootd.mjs [--out out/<날짜>] (npm run card -- ootd --daily 가 부른다)
|
||||||
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||||
|
import { join, resolve } from 'node:path'
|
||||||
|
import { drawWithCodex } from './codex-image.mjs'
|
||||||
|
import { extractOutfit } from './outfit.mjs'
|
||||||
|
import { pickSnaps } from './snap.mjs'
|
||||||
|
|
||||||
|
const API_URL = process.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
||||||
|
const REGION = '1114000000' // 서울 중구 (src/cards/data.ts BASE_REGION)
|
||||||
|
const spec = JSON.parse(readFileSync(resolve('image-prompts/ootd.json'), 'utf8'))
|
||||||
|
const PERSONA_ORDER = ['f20', 'm20', 'f40', 'm40']
|
||||||
|
const COUNT_WORD = { 3: 'three', 4: 'four', 5: 'five' }
|
||||||
|
|
||||||
|
/** 오늘 예보 → 아침·낮 기온, 기온 구간 (src/cards/data.ts temps 와 같은 계산) */
|
||||||
|
export async function weatherToday() {
|
||||||
|
const res = await fetch(`${API_URL}/v1/weather/today?region=${REGION}`)
|
||||||
|
const d = await res.json()
|
||||||
|
if (d.result?.success === false || !d.slots?.length) throw new Error(`오늘 예보를 받지 못했어요 (${d.result?.desc ?? '응답 없음'})`)
|
||||||
|
const hour = (s) => new Date(s.at).getHours()
|
||||||
|
const withTemp = d.slots.filter((s) => s.temp_c != null)
|
||||||
|
const day = withTemp.filter((s) => hour(s) >= 6 && hour(s) <= 21)
|
||||||
|
const t = day.length ? day : withTemp
|
||||||
|
const maxC = Math.round(Math.max(...t.map((s) => s.temp_c)))
|
||||||
|
const morningC = Math.round((t.find((s) => hour(s) === 6) ?? t[0]).temp_c)
|
||||||
|
const band = spec.bands.find((b) => maxC >= b.from) ?? spec.bands[spec.bands.length - 1]
|
||||||
|
return { day: d.day, morningC, maxC, band: band.id, layering: band.layering ?? '' }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 카드 이름표 순서(상의·겉옷·하의·신발·가방)와 그림 번호 순서(1 상의·2 하의·3 신발·4 가방·5 겉옷)는 다르다
|
||||||
|
const LABEL_ORDER = ['top', 'outer', 'bottom', 'shoes', 'bag']
|
||||||
|
const DRAW_ORDER = ['top', 'bottom', 'shoes', 'bag', 'outer']
|
||||||
|
|
||||||
|
function layoutFor(slots) {
|
||||||
|
const has = (s) => slots.includes(s)
|
||||||
|
const topRow = has('outer') ? '(1) top-left, the outer layer in the top center, (2) top-right' : '(1) top-left, (2) top-right'
|
||||||
|
const bottomRow = has('bag') ? '(3) bottom-left and (4) bottom-right' : '(3) bottom-center'
|
||||||
|
return `top row: ${topRow}; bottom row: ${bottomRow}. Clearly separate spots, nothing else in between.`
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPrompt(persona, outfit, weather) {
|
||||||
|
const by = Object.fromEntries(outfit.items.map((it) => [it.slot, it]))
|
||||||
|
const drawn = DRAW_ORDER.filter((s) => by[s])
|
||||||
|
const items = drawn.map((s, i) => `(${i + 1}) ${by[s].prompt}${s === 'outer' ? ' as the outer layer' : ''}`).join(', ')
|
||||||
|
return spec.style
|
||||||
|
.replace('{items}', items)
|
||||||
|
.replace('{count}', COUNT_WORD[drawn.length] ?? String(drawn.length))
|
||||||
|
.replace('{layout}', layoutFor(drawn))
|
||||||
|
.replace('{persona}', spec.personas[persona].prompt)
|
||||||
|
.replace('{style}', outfit.style)
|
||||||
|
.replace('{trend}', 'follow the attached reference photos (the outfit photo and the product thumbnails): the same garments, colors, materials and silhouettes')
|
||||||
|
.replace('{layering}', weather.layering)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 포스트 하나는 스타일 하나(기본 꾸안꾸). 네 사람 모두 그 스타일 스냅에서 고르고 제목도 같은 스타일로 간다.
|
||||||
|
* @returns {Promise<{ weather: object, outfits: { persona: string, label: string, style: string, labels: string[], image: string, source: string, items: object[] }[] }>} */
|
||||||
|
export async function runDailyOotd({ outDir, style = 'minimal', log = console.log }) {
|
||||||
|
if (!spec.styles[style]) throw new Error(`스타일은 ${Object.keys(spec.styles).join(', ')} 중 하나예요: ${style}`)
|
||||||
|
const styleLabel = spec.styles[style].label
|
||||||
|
const weather = await weatherToday()
|
||||||
|
log(`오늘 ${weather.day}: 아침 ${weather.morningC}° · 낮 ${weather.maxC}° → 구간 ${weather.band} · 스타일 ${styleLabel}`)
|
||||||
|
mkdirSync(outDir, { recursive: true })
|
||||||
|
const picks = await pickSnaps({ band: weather.band, style, outDir: join(outDir, 'snaps'), log })
|
||||||
|
const dailyDir = resolve('public/daily')
|
||||||
|
mkdirSync(dailyDir, { recursive: true })
|
||||||
|
const outfits = []
|
||||||
|
for (const persona of PERSONA_ORDER) {
|
||||||
|
const pick = picks[persona]
|
||||||
|
log(`${persona}: Claude가 옷 목록을 뽑는 중… (${pick.url})`)
|
||||||
|
const outfit = await extractOutfit(pick, persona, weather)
|
||||||
|
// 제목은 Claude 가 본 분위기가 아니라 포스트 스타일로 통일한다
|
||||||
|
outfit.style = styleLabel
|
||||||
|
const by = Object.fromEntries(outfit.items.map((it) => [it.slot, it]))
|
||||||
|
const labels = LABEL_ORDER.filter((s) => by[s]).map((s) => by[s].label)
|
||||||
|
log(` ${outfit.style}: ${labels.join(' · ')}`)
|
||||||
|
const id = `${weather.day}-${persona}`
|
||||||
|
const outPath = join(dailyDir, `${id}.webp`)
|
||||||
|
const images = [pick.files.image, ...pick.files.thumbs.slice(0, 4).map((t) => t.path)]
|
||||||
|
const prompt = buildPrompt(persona, outfit, weather)
|
||||||
|
let result = drawWithCodex({ id, prompt, outPath, images, log })
|
||||||
|
if (result !== 'ok') result = drawWithCodex({ id, prompt, outPath, images, log })
|
||||||
|
if (result !== 'ok') throw new Error(`${id}: 그림을 두 번 다 저장하지 못했어요`)
|
||||||
|
outfits.push({ persona, label: spec.personas[persona].label, style: outfit.style, labels, image: `/daily/${id}.webp`, source: pick.url, items: outfit.items })
|
||||||
|
}
|
||||||
|
writeFileSync(join(outDir, 'outfits.json'), JSON.stringify({ weather, outfits }, null, 1))
|
||||||
|
return { weather, outfits }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 카드(copy.outfits)에 넣는 꼴: 사람·제목·스타일·이름표·그림 주소 */
|
||||||
|
export const toCardOutfits = (outfits) => outfits.map(({ persona, label, style, labels, image }) => ({ persona, label, style, labels, image }))
|
||||||
|
|
||||||
|
if (process.argv[1]?.endsWith('daily-ootd.mjs')) {
|
||||||
|
const args = process.argv.slice(2)
|
||||||
|
const flag = (n) => (args.includes(n) ? args[args.indexOf(n) + 1] : null)
|
||||||
|
const outArg = flag('--out')
|
||||||
|
const style = flag('--style') ?? 'minimal'
|
||||||
|
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||||
|
const { outfits } = await runDailyOotd({ outDir: resolve(outArg ?? `out/${day}`), style })
|
||||||
|
const copy = Buffer.from(JSON.stringify({ outfits: JSON.stringify(toCardOutfits(outfits)), style, theme: 'sky' })).toString('base64url')
|
||||||
|
console.log(`카드 그리기: npm run card -- ootd --no-images --copy ${copy}`)
|
||||||
|
}
|
||||||
@@ -1,12 +1,9 @@
|
|||||||
// 카드 그림을 프롬프트 템플릿(image-prompts/<종류>.json)대로 Codex 이미지 생성으로 만들어 src/assets/<종류>/<id>.webp 에 넣는다.
|
// 카드 그림을 프롬프트 템플릿(image-prompts/<종류>.json)대로 Codex 이미지 생성으로 만들어 src/assets/<종류>/<id>.webp 에 넣는다.
|
||||||
// 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force]
|
// 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force]
|
||||||
// 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal
|
// 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal
|
||||||
import { execFileSync } from 'node:child_process'
|
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
|
||||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
|
|
||||||
import { tmpdir } from 'node:os'
|
|
||||||
import { join, resolve } from 'node:path'
|
import { join, resolve } from 'node:path'
|
||||||
|
import { drawWithCodex } from './codex-image.mjs'
|
||||||
const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
|
|
||||||
|
|
||||||
function fail(message) {
|
function fail(message) {
|
||||||
console.error(message)
|
console.error(message)
|
||||||
@@ -77,33 +74,14 @@ for (const band of bands) {
|
|||||||
console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`)
|
console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
const prompt = band.prompt
|
let result
|
||||||
const work = mkdtempSync(join(tmpdir(), `gen-${kind}-${band.id}-`))
|
|
||||||
const task = [
|
|
||||||
'내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
|
|
||||||
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
|
|
||||||
`통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.`,
|
|
||||||
'',
|
|
||||||
prompt,
|
|
||||||
].join('\n')
|
|
||||||
console.log(`${band.id}: Codex로 그리는 중…`)
|
|
||||||
try {
|
try {
|
||||||
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다)
|
result = drawWithCodex({ id: band.id, prompt: band.prompt, outPath: outPath(band.id) })
|
||||||
execFileSync('codex', ['exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', task], { stdio: ['ignore', 'ignore', 'inherit'] })
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
rmSync(work, { recursive: true, force: true })
|
fail(e.message)
|
||||||
fail(`${band.id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
|
|
||||||
}
|
}
|
||||||
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
|
|
||||||
// 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤)
|
// 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤)
|
||||||
if (!png) {
|
if (result !== 'ok') failed.push(band.id)
|
||||||
console.error(`${band.id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
|
|
||||||
failed.push(band.id)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath(band.id)])
|
|
||||||
rmSync(work, { recursive: true, force: true })
|
|
||||||
console.log(`${band.id}: ${outPath(band.id)}`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (failed.length) fail(`못 만든 그림: ${failed.join(", ")} — 다시: npm run gen-image -- ${kind} ${failed.join(" ")}`)
|
if (failed.length) fail(`못 만든 그림: ${failed.join(", ")} — 다시: npm run gen-image -- ${kind} ${failed.join(" ")}`)
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// 고른 스냅(사진 + 입은 상품 목록)에서 카드에 쓸 옷 목록을 Claude CLI로 뽑는다: 자리별 한글 이름표와 그림용 영어 설명.
|
||||||
|
import { execFile } from 'node:child_process'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
|
||||||
|
const SLOT_ORDER = ['top', 'outer', 'bottom', 'shoes', 'bag']
|
||||||
|
const PERSONA_TEXT = { f20: '20-30대 여자', m20: '20-30대 남자', f40: '40대 이상 여자', m40: '40대 이상 남자' }
|
||||||
|
|
||||||
|
const schema = {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
style: { type: 'string', description: '이 코디를 한 단어로 (예: 꾸안꾸, 오피스룩, 캐주얼, 미니멀, 스트릿, 데일리)' },
|
||||||
|
items: {
|
||||||
|
type: 'array',
|
||||||
|
minItems: 4,
|
||||||
|
maxItems: 5,
|
||||||
|
items: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
slot: { type: 'string', enum: SLOT_ORDER },
|
||||||
|
label: { type: 'string', description: '카드 이름표. 한글 2~7자 (예: 스트라이프 티, 와이드 슬랙스, 로퍼)' },
|
||||||
|
prompt: { type: 'string', description: '그림용 영어 설명 한 구절: 색(대문자)·소재·실루엣 (예: a CHARCOAL wool single-breasted blazer)' },
|
||||||
|
},
|
||||||
|
required: ['slot', 'label', 'prompt'],
|
||||||
|
additionalProperties: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ['style', 'items'],
|
||||||
|
additionalProperties: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPrompt(pick, persona, weather) {
|
||||||
|
const goods = pick.goods.map((g, i) => `${i + 1}. [${g.category1} > ${g.category2}] ${g.brand} ${g.name}`).join('\n')
|
||||||
|
const files = [pick.files.image, ...pick.files.thumbs.map((t) => t.path)]
|
||||||
|
return [
|
||||||
|
`무신사 스냅 코디 사진과 그 코디에 태그된 상품 목록이다. ${PERSONA_TEXT[persona]} 카드에 쓸 옷 목록을 만든다.`,
|
||||||
|
`오늘 서울 날씨: 아침 ${weather.morningC}도, 낮 최고 ${weather.maxC}도.`,
|
||||||
|
'',
|
||||||
|
'먼저 Read 도구로 이 파일들을 본다(첫 파일이 코디 사진, 나머지는 상품 썸네일):',
|
||||||
|
...files.map((f) => `- ${f}`),
|
||||||
|
'',
|
||||||
|
'태그된 상품:',
|
||||||
|
goods,
|
||||||
|
'',
|
||||||
|
'규칙:',
|
||||||
|
'- 자리(slot)는 top·bottom·shoes 는 반드시, 사진에서 겉옷(outer)을 입거나 걸쳤으면 outer 도, 가방이 있으면 bag 도 넣는다. 최대 5개, 자리마다 하나.',
|
||||||
|
'- 원피스면 top 으로 넣고 bottom 은 생략하지 말고 같은 원피스를 bottom 에 다시 넣지 않는다 → 원피스는 top, bottom 자리에는 사진의 다른 하의가 없으면 shoes·bag 으로 4개를 채운다.',
|
||||||
|
'- 상품 목록에 있는 옷은 그 상품명 기준으로, 없는 옷은 사진에서 보이는 대로. 색은 사진 기준.',
|
||||||
|
'- label 은 카드 이름표라 짧고 쉬운 한글(브랜드·영어 금지). prompt 는 영어 한 구절, 색은 대문자.',
|
||||||
|
'- style 은 코디 분위기 한 단어.',
|
||||||
|
'JSON 으로만 답한다.',
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns {Promise<{ style: string, items: { slot: string, label: string, prompt: string }[] }>} */
|
||||||
|
export function extractOutfit(pick, persona, weather) {
|
||||||
|
const args = ['-p', buildPrompt(pick, persona, weather), '--output-format', 'json', '--json-schema', JSON.stringify(schema), '--tools', 'Read', '--allowedTools', 'Read', '--no-session-persistence', '--model', 'sonnet']
|
||||||
|
return new Promise((done, fail) => {
|
||||||
|
execFile('claude', args, { cwd: tmpdir(), timeout: 240_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
|
||||||
|
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
|
||||||
|
let out
|
||||||
|
try {
|
||||||
|
out = JSON.parse(stdout)
|
||||||
|
} catch {
|
||||||
|
return fail(new Error(`Claude 답을 읽지 못했어요: ${stdout.slice(0, 300)}`))
|
||||||
|
}
|
||||||
|
const result = out.structured_output ?? (typeof out.result === 'string' ? JSON.parse(out.result) : null)
|
||||||
|
if (out.is_error || !result?.items?.length) return fail(new Error(`Claude가 옷 목록을 주지 못했어요: ${String(out.result ?? '').slice(0, 300)}`))
|
||||||
|
const seen = new Set()
|
||||||
|
const items = result.items.filter((it) => SLOT_ORDER.includes(it.slot) && !seen.has(it.slot) && seen.add(it.slot))
|
||||||
|
items.sort((a, b) => SLOT_ORDER.indexOf(a.slot) - SLOT_ORDER.indexOf(b.slot))
|
||||||
|
done({ style: String(result.style ?? '').trim() || '데일리', items })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
// 카드 문구 기획: 템플릿 칸·오늘 날씨·주제·피드백을 Claude CLI(claude -p)에 넘겨 칸별 문구를 받는다.
|
// 카드 문구 기획: 템플릿 칸·오늘 날씨·주제·피드백을 Claude CLI(claude -p)에 넘겨 칸별 문구를 받는다.
|
||||||
// 관리자 서버(/api/plan)와 npm run card --topic 이 같이 쓴다. API 키 없이 이 맥에 로그인된 Claude Code를 쓴다.
|
// 관리자 서버(/api/plan)와 npm run card --topic 이 같이 쓴다. API 키 없이 이 맥에 로그인된 Claude Code를 쓴다.
|
||||||
import { execFile } from 'node:child_process'
|
import { execFile } from 'node:child_process'
|
||||||
import { readdirSync, readFileSync } from 'node:fs'
|
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
||||||
import { tmpdir } from 'node:os'
|
import { tmpdir } from 'node:os'
|
||||||
import { resolve } from 'node:path'
|
import { resolve } from 'node:path'
|
||||||
|
|
||||||
@@ -20,6 +20,19 @@ const questionOf = (topic) => {
|
|||||||
}
|
}
|
||||||
// 날씨 타로 카드 = 날씨각 각 카드 (서비스와 같은 각 목록)
|
// 날씨 타로 카드 = 날씨각 각 카드 (서비스와 같은 각 목록)
|
||||||
const DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../backend/seed/index_definition.json'), 'utf8')).map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description }))
|
const DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../backend/seed/index_definition.json'), 'utf8')).map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description }))
|
||||||
|
// 최근에 쓴 각은 빼서 매일 같은 카드가 나오지 않게 한다 (card.mjs 가 기획할 때마다 적는다)
|
||||||
|
const HISTORY_FILE = resolve(import.meta.dirname, '../out/tarot-history.json')
|
||||||
|
const HISTORY_DAYS = 7
|
||||||
|
function recentCodes() {
|
||||||
|
if (!existsSync(HISTORY_FILE)) return []
|
||||||
|
try {
|
||||||
|
const history = JSON.parse(readFileSync(HISTORY_FILE, 'utf8'))
|
||||||
|
const cutoff = Date.now() - HISTORY_DAYS * 86400_000
|
||||||
|
return [...new Set(Object.entries(history).filter(([day]) => new Date(day).getTime() >= cutoff).flatMap(([, codes]) => codes))]
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
const categoryOf = (topic) => TOPICS.find((c) => topic.includes(c.name) || c.subtopics.some((s) => topic.includes(s)))
|
const categoryOf = (topic) => TOPICS.find((c) => topic.includes(c.name) || c.subtopics.some((s) => topic.includes(s)))
|
||||||
|
|
||||||
const RULES = [
|
const RULES = [
|
||||||
@@ -56,15 +69,25 @@ const TAROT_TONE = [
|
|||||||
'키워드(k)는 4~8자 명사구("같이 걷는 시간", "먼저 보내는 한 줄"). 행운 포인트(l)는 시간·날씨·행동 한 줄 22자 이내("저녁 8시, 17도로 걷기 딱 좋아요").',
|
'키워드(k)는 4~8자 명사구("같이 걷는 시간", "먼저 보내는 한 줄"). 행운 포인트(l)는 시간·날씨·행동 한 줄 22자 이내("저녁 8시, 17도로 걷기 딱 좋아요").',
|
||||||
]
|
]
|
||||||
|
|
||||||
function tarotSection(topic) {
|
/** 오늘 고를 수 있는 각: 최근 7일에 쓴 각은 뺀다 (관리자가 고정한 카드는 남긴다) */
|
||||||
|
function availableDeck(fixed = {}) {
|
||||||
|
const recent = new Set(recentCodes())
|
||||||
|
const keep = new Set(fixed.cards ?? [])
|
||||||
|
return DECK.filter((c) => !recent.has(c.id) || keep.has(c.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
function tarotSection(topic, fixed = {}) {
|
||||||
|
const deck = availableDeck(fixed)
|
||||||
|
const excluded = DECK.filter((c) => !deck.includes(c)).map((c) => c.name)
|
||||||
return [
|
return [
|
||||||
'',
|
'',
|
||||||
'## 각 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)',
|
'## 각 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)',
|
||||||
questionOf(topic) ? `표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}` : '표지 질문(question)은 주제에 맞는 "오늘 ~할까요?" 꼴 질문 하나를 쓴다.',
|
questionOf(topic) ? `표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}` : '표지 질문(question)은 주제에 맞는 "오늘 ~할까요?" 꼴 질문 하나를 쓴다.',
|
||||||
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 각(오늘 실제로 하기 좋은 각) 가운데 질문과 엮을 수 있는 것을 고른다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
|
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 편(상위 15개 안)인 각 가운데 질문과 엮을 수 있는 것을 고른다. 매일 같은 야외 운동 각(산책·자전거·등산·드라이브)만 반복하지 말고 먹거리·계절·집·동네 각도 섞어 날마다 다른 카드가 나오게 한다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
|
||||||
|
excluded.length ? `최근 7일에 쓴 각이라 오늘은 고를 수 없음(목록에서 뺐다): ${excluded.join(', ')}` : '',
|
||||||
...TAROT_TONE,
|
...TAROT_TONE,
|
||||||
'',
|
'',
|
||||||
...DECK.map((c) => `- ${c.id}: ${c.name} — ${c.meaning}`),
|
...deck.map((c) => `- ${c.id}: ${c.name} — ${c.meaning}`),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,23 +109,23 @@ function buildPrompt(ctx, { topic, feedback, fixed = {} }) {
|
|||||||
topic ? `## 주제: ${topic}` : `## 주제: 없음 — 다음 대주제·소주제 중 오늘 날씨와 어울리는 것을 하나 골라 topic에 "대주제 소주제"로 적고 그 주제로 쓴다: ${TOPICS.map((c) => `${c.name}(${c.subtopics.join('·')})`).join(', ')}`,
|
topic ? `## 주제: ${topic}` : `## 주제: 없음 — 다음 대주제·소주제 중 오늘 날씨와 어울리는 것을 하나 골라 topic에 "대주제 소주제"로 적고 그 주제로 쓴다: ${TOPICS.map((c) => `${c.name}(${c.subtopics.join('·')})`).join(', ')}`,
|
||||||
feedback ? `## 피드백 (반드시 반영): ${feedback}` : '',
|
feedback ? `## 피드백 (반드시 반영): ${feedback}` : '',
|
||||||
'',
|
'',
|
||||||
...(isTarot(ctx) ? tarotSection(topic) : []),
|
...(isTarot(ctx) ? tarotSection(topic, fixed) : []),
|
||||||
fixed.question ? `## 질문은 관리자가 정했다(그대로 쓴다): ${fixed.question}` : '',
|
fixed.question ? `## 질문은 관리자가 정했다(그대로 쓴다): ${fixed.question}` : '',
|
||||||
fixed.cards?.length ? `## 카드는 관리자가 골랐다(card1·card2·card3 순서 그대로): ${fixed.cards.join(', ')}` : '',
|
fixed.cards?.length ? `## 카드는 관리자가 골랐다(card1·card2·card3 순서 그대로): ${fixed.cards.join(', ')}` : '',
|
||||||
'모든 칸을 채운 JSON으로만 답한다. topic에는 쓴 주제를 짧게 적는다.',
|
'모든 칸을 채운 JSON으로만 답한다. topic에는 쓴 주제를 짧게 적는다.',
|
||||||
].join('\n')
|
].join('\n')
|
||||||
}
|
}
|
||||||
|
|
||||||
function schema(ctx) {
|
function schema(ctx, fixed = {}) {
|
||||||
const properties = { topic: { type: 'string' } }
|
const properties = { topic: { type: 'string' } }
|
||||||
for (const f of ctx.fields) if (!(isTarot(ctx) && DECK_KEY.test(f.key))) properties[f.key] = { type: 'string' }
|
for (const f of ctx.fields) if (!(isTarot(ctx) && DECK_KEY.test(f.key))) properties[f.key] = { type: 'string' }
|
||||||
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: DECK.map((c) => c.id) }
|
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: availableDeck(fixed).map((c) => c.id) }
|
||||||
return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false }
|
return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
|
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
|
||||||
export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
|
export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
|
||||||
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
|
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx, fixed)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
|
||||||
return new Promise((done, fail) => {
|
return new Promise((done, fail) => {
|
||||||
execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
|
execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
|
||||||
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
|
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
|
||||||
|
|||||||
@@ -0,0 +1,233 @@
|
|||||||
|
// 무신사 스냅(공개 API)에서 오늘 날씨에 맞는 인기 코디를 사람별로 하나씩 고른다. 사진·상품 썸네일은 그림 참고용으로만 내려받고 어디에도 올리지 않는다.
|
||||||
|
// 사용(확인용): node scripts/snap.mjs --band mild --out out/2026-10-26/snaps
|
||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||||
|
import { join, resolve } from 'node:path'
|
||||||
|
|
||||||
|
// 최근에 쓴 스냅은 다시 고르지 않는다 (스타일이 달라도 같은 코디가 또 나오지 않게)
|
||||||
|
const HISTORY_FILE = resolve('out/snap-history.json')
|
||||||
|
const HISTORY_DAYS = 14
|
||||||
|
function loadHistory() {
|
||||||
|
if (!existsSync(HISTORY_FILE)) return {}
|
||||||
|
try {
|
||||||
|
return JSON.parse(readFileSync(HISTORY_FILE, 'utf8'))
|
||||||
|
} catch {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function recentIds(history) {
|
||||||
|
const cutoff = Date.now() - HISTORY_DAYS * 86400_000
|
||||||
|
return new Set(Object.entries(history).filter(([day]) => new Date(day).getTime() >= cutoff).flatMap(([, ids]) => ids))
|
||||||
|
}
|
||||||
|
|
||||||
|
const LIST_URL = 'https://content.musinsa.com/api2/content/snap/v1/snaps'
|
||||||
|
const GOODS_URL = (no) => `https://goods-detail.musinsa.com/api2/goods/${no}`
|
||||||
|
const IMAGE_HOST = 'https://image.msscdn.net'
|
||||||
|
const HEADERS = { 'User-Agent': 'Mozilla/5.0', Accept: 'application/json' }
|
||||||
|
|
||||||
|
/** 카드 사람(페르소나) → 성별과 "40대~"면 단정한 코디를 고르는 기준 */
|
||||||
|
export const PERSONAS = {
|
||||||
|
f20: { gender: 'WOMEN', mature: false },
|
||||||
|
m20: { gender: 'MEN', mature: false },
|
||||||
|
f40: { gender: 'WOMEN', mature: true },
|
||||||
|
m40: { gender: 'MEN', mature: true },
|
||||||
|
}
|
||||||
|
|
||||||
|
// 기온 구간(image-prompts/ootd.json bands 의 id)별로 찾는 태그와 걸러 낼 아우터
|
||||||
|
const HEAVY = /패딩|푸퍼|다운|롱코트|울코트|무스탕|플리스|기모|헤비|퍼 /i
|
||||||
|
const MID = /코트|자켓|재킷|점퍼|블루종|집업/i
|
||||||
|
const SHORTS = /쇼츠|반바지|shorts|숏팬츠|버뮤다/i
|
||||||
|
const SHORT_SLEEVE = /반팔|하프 슬리브|half sleeve|슬리브리스|민소매|sleeveless/i
|
||||||
|
const BAND = {
|
||||||
|
hot: { tags: ['여름코디', '간절기코디'], rejectGoods: [HEAVY, MID], rejectTags: [/겨울|패딩|코트/] },
|
||||||
|
warm: { tags: ['간절기코디', '가을코디'], rejectGoods: [HEAVY, MID], rejectTags: [/겨울|패딩|코트/] },
|
||||||
|
mild: { tags: ['가을코디', '간절기코디'], rejectGoods: [HEAVY, SHORTS], rejectTags: [/겨울|패딩/] },
|
||||||
|
cool: { tags: ['가을코디', '가을아우터'], rejectGoods: [HEAVY, SHORTS, SHORT_SLEEVE], rejectTags: [/겨울/] },
|
||||||
|
chilly: { tags: ['가을코디', '겨울코디'], rejectGoods: [/롱패딩|헤비/, SHORTS, SHORT_SLEEVE], rejectTags: [] },
|
||||||
|
cold: { tags: ['겨울코디'], rejectGoods: [SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔/] },
|
||||||
|
freezing: { tags: ['겨울코디', '롱패딩'], rejectGoods: [SHORTS, SHORT_SLEEVE], rejectTags: [/여름|반팔|가을/] },
|
||||||
|
}
|
||||||
|
// 철 지난 스냅은 뺀다
|
||||||
|
const MAX_AGE_DAYS = 45
|
||||||
|
// 포스트 하나는 스타일 하나: 네 사람 모두 이 태그가 붙은 스냅에서 고른다 (image-prompts/ootd.json styles 의 id)
|
||||||
|
export const STYLE_TAGS = {
|
||||||
|
casual: ['데일리룩', '캐주얼룩', '캐주얼'],
|
||||||
|
semi: ['오피스룩', '출근룩', '비즈니스캐주얼'],
|
||||||
|
formal: ['정장', '수트', '포멀룩'],
|
||||||
|
street: ['스트릿', '스트릿룩', '스트릿패션'],
|
||||||
|
minimal: ['꾸안꾸', '미니멀룩', '미니멀'],
|
||||||
|
}
|
||||||
|
// 40대~ 는 단정한 코디 태그로 한 번 더 모은다
|
||||||
|
const MATURE_KEYWORDS = { WOMEN: ['오피스룩', '출근룩', '미니멀룩'], MEN: ['오피스룩', '댄디룩', '비즈니스캐주얼'] }
|
||||||
|
const MATURE_TAG = /오피스|출근|미니멀|클래식|단정|하객|댄디|비즈니스|포멀|꾸안꾸/
|
||||||
|
const YOUNG_ONLY = /캠퍼스|학생|스트릿|스트리트|힙합|Y2K|고프코어|테크웨어/i
|
||||||
|
|
||||||
|
/** 상품 카테고리 → 카드 자리 */
|
||||||
|
export function slotOf(goods) {
|
||||||
|
const c = `${goods.category1 ?? ''} ${goods.category2 ?? ''}`
|
||||||
|
if (/원피스/.test(c)) return 'onepiece'
|
||||||
|
if (/아우터|가디건|자켓|재킷|코트|점퍼|패딩|블루종/.test(c)) return 'outer'
|
||||||
|
if (/상의|티셔츠|셔츠|니트|블라우스|후드/.test(c)) return 'top'
|
||||||
|
if (/바지|스커트|팬츠|슬랙스|데님|하의/.test(c)) return 'bottom'
|
||||||
|
if (/신발|스니커즈|구두|부츠|로퍼|샌들|슈즈/.test(c)) return 'shoes'
|
||||||
|
if (/가방|백팩|토트|숄더|크로스/.test(c)) return 'bag'
|
||||||
|
if (/모자|액세서리|주얼리|시계|양말|벨트|안경|스카프|머플러|캡/.test(c)) return 'acc'
|
||||||
|
return 'other'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getJson(url) {
|
||||||
|
const res = await fetch(url, { headers: HEADERS })
|
||||||
|
if (!res.ok) throw new Error(`${res.status} ${url}`)
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 태그·키워드로 인기 스냅 목록 (한 번에 100개, 상품 번호·성별·태그·좋아요 포함) */
|
||||||
|
async function listSnaps(params, pages) {
|
||||||
|
const out = []
|
||||||
|
for (let page = 1; page <= pages; page++) {
|
||||||
|
const q = new URLSearchParams({ sort: 'POPULAR', size: '100', page: String(page), ...params })
|
||||||
|
const body = await getJson(`${LIST_URL}?${q}`)
|
||||||
|
const list = body.data?.list ?? []
|
||||||
|
for (const d of list) {
|
||||||
|
out.push({
|
||||||
|
id: d.id,
|
||||||
|
url: `https://www.musinsa.com/snap/${d.id}`,
|
||||||
|
gender: d.model?.gender ?? '',
|
||||||
|
age: d.model?.age ?? null,
|
||||||
|
likes: d.aggregations?.likeCount ?? 0,
|
||||||
|
tags: (d.tags ?? []).map((t) => t.name),
|
||||||
|
text: (d.detail?.content ?? '').slice(0, 200),
|
||||||
|
image: d.medias?.find((m) => m.type === 'IMAGE')?.path ?? d.thumbnailUrl ?? '',
|
||||||
|
createdAt: d.createdAt ?? '',
|
||||||
|
goodsNos: (d.goods ?? []).map((g) => g.goodsNo).filter(Boolean),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (list.length < 100) break
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
async function goodsDetail(no) {
|
||||||
|
const d = (await getJson(GOODS_URL(no))).data
|
||||||
|
const thumb = d.thumbnailImageUrl ?? ''
|
||||||
|
const g = {
|
||||||
|
no,
|
||||||
|
name: d.goodsNm ?? '',
|
||||||
|
brand: typeof d.brand === 'object' ? (d.brand?.name ?? '') : (d.brand ?? ''),
|
||||||
|
category1: d.category?.categoryDepth1Title ?? '',
|
||||||
|
category2: d.category?.categoryDepth2Title ?? '',
|
||||||
|
thumb: thumb ? (thumb.startsWith('http') ? thumb : IMAGE_HOST + thumb) : '',
|
||||||
|
}
|
||||||
|
return { ...g, slot: slotOf(g) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function withGoods(snap) {
|
||||||
|
const goods = []
|
||||||
|
for (const no of snap.goodsNos.slice(0, 8)) {
|
||||||
|
try {
|
||||||
|
goods.push(await goodsDetail(no))
|
||||||
|
} catch {
|
||||||
|
// 품절·삭제된 상품은 빼고 간다
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ...snap, goods }
|
||||||
|
}
|
||||||
|
|
||||||
|
function fits(snap, band) {
|
||||||
|
const rule = BAND[band] ?? BAND.mild
|
||||||
|
if (snap.createdAt && Date.now() - new Date(snap.createdAt).getTime() > MAX_AGE_DAYS * 86400_000) return false
|
||||||
|
const blob = snap.goods.map((g) => `${g.name} ${g.category2}`).join(' | ')
|
||||||
|
if (rule.rejectGoods.some((re) => re.test(blob))) return false
|
||||||
|
if (rule.rejectTags.some((re) => snap.tags.some((t) => re.test(t)))) return false
|
||||||
|
const slots = new Set(snap.goods.map((g) => g.slot))
|
||||||
|
const hasTop = slots.has('top') || slots.has('onepiece')
|
||||||
|
const hasBottom = slots.has('bottom') || slots.has('onepiece')
|
||||||
|
return hasTop && hasBottom && slots.has('shoes') && !!snap.image
|
||||||
|
}
|
||||||
|
|
||||||
|
function score(snap, persona) {
|
||||||
|
let s = Math.log10(snap.likes + 10)
|
||||||
|
const tagBlob = snap.tags.join(' ')
|
||||||
|
const goods = snap.goods ?? []
|
||||||
|
if (PERSONAS[persona].mature) {
|
||||||
|
if (MATURE_TAG.test(tagBlob)) s += 1.5
|
||||||
|
if (YOUNG_ONLY.test(tagBlob)) s -= 2
|
||||||
|
if (goods.some((g) => /슬랙스|로퍼|니트|블라우스|코트|자켓|재킷|셔츠/.test(g.name + g.category2))) s += 0.5
|
||||||
|
if (goods.some((g) => /카고|후드|조거|스웨트/.test(g.name + g.category2))) s -= 1
|
||||||
|
} else if (MATURE_TAG.test(tagBlob) && !/꾸안꾸|데일리/.test(tagBlob)) s -= 0.3
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
async function download(url, path) {
|
||||||
|
const res = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' } })
|
||||||
|
if (!res.ok) throw new Error(`${res.status} ${url}`)
|
||||||
|
writeFileSync(path, Buffer.from(await res.arrayBuffer()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 사람별로 스냅 하나씩: { f20: {...snap, files: { image, thumbs[] }}, ... }. style 을 주면 네 사람 모두 그 스타일 태그가 붙은 스냅에서 고른다 */
|
||||||
|
export async function pickSnaps({ band, style, outDir, pages = 2, log = console.log }) {
|
||||||
|
mkdirSync(outDir, { recursive: true })
|
||||||
|
const rule = BAND[band] ?? BAND.mild
|
||||||
|
const styleTags = STYLE_TAGS[style] ?? []
|
||||||
|
const pool = new Map()
|
||||||
|
const add = (list) => list.forEach((s) => s.goodsNos.length >= 3 && !pool.has(s.id) && pool.set(s.id, s))
|
||||||
|
for (const tag of styleTags) add(await listSnaps({ tags: tag }, pages))
|
||||||
|
for (const tag of rule.tags) add(await listSnaps({ tags: tag }, pages))
|
||||||
|
for (const gender of ['WOMEN', 'MEN']) for (const kw of MATURE_KEYWORDS[gender]) add(await listSnaps({ keyword: kw }, 1))
|
||||||
|
const hasStyle = (s) => styleTags.length === 0 || s.tags.some((t) => styleTags.some((st) => t.includes(st)))
|
||||||
|
log(`무신사 스냅 후보 ${pool.size}개 (구간 ${band}${styleTags.length ? ` · 스타일 #${styleTags.join(' #')} ${[...pool.values()].filter(hasStyle).length}개` : ''}). 상품 정보를 받아 거르는 중…`)
|
||||||
|
|
||||||
|
const picks = {}
|
||||||
|
const history = loadHistory()
|
||||||
|
const used = recentIds(history)
|
||||||
|
// 40대~ 를 먼저 골라야 단정한 코디가 남는다. 좋아요 순으로 상품 정보를 받아 보며 맞는 첫 코디를 고른다
|
||||||
|
for (const persona of ['f40', 'm40', 'f20', 'm20']) {
|
||||||
|
const { gender } = PERSONAS[persona]
|
||||||
|
// 스타일 태그가 붙은 스냅을 먼저, 모자라면 나머지 (스타일 태그 없는 스냅은 뒤로)
|
||||||
|
const candidates = [...pool.values()]
|
||||||
|
.filter((s) => s.gender === gender && !used.has(s.id))
|
||||||
|
.sort((a, b) => Number(hasStyle(b)) - Number(hasStyle(a)) || score(b, persona) - score(a, persona))
|
||||||
|
.slice(0, 25)
|
||||||
|
let best = null
|
||||||
|
for (const c of candidates) {
|
||||||
|
const full = c.goods ? c : await withGoods(c)
|
||||||
|
pool.set(full.id, full)
|
||||||
|
if (fits(full, band)) {
|
||||||
|
best = full
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!best) throw new Error(`${persona} 에 맞는 스냅이 없어요 (성별 ${gender}, 구간 ${band})`)
|
||||||
|
used.add(best.id)
|
||||||
|
const dir = join(outDir, persona)
|
||||||
|
mkdirSync(dir, { recursive: true })
|
||||||
|
const image = join(dir, 'snap.jpg')
|
||||||
|
await download(best.image, image)
|
||||||
|
const thumbs = []
|
||||||
|
for (const [i, g] of best.goods.entries()) {
|
||||||
|
if (!g.thumb || g.slot === 'other') continue
|
||||||
|
const p = join(dir, `goods-${i + 1}.jpg`)
|
||||||
|
try {
|
||||||
|
await download(g.thumb, p)
|
||||||
|
thumbs.push({ path: p, goods: g })
|
||||||
|
} catch {
|
||||||
|
// 썸네일 없으면 상품명만 쓴다
|
||||||
|
}
|
||||||
|
}
|
||||||
|
picks[persona] = { ...best, styled: hasStyle(best), files: { image, thumbs } }
|
||||||
|
log(` ${persona}: ${best.url} ♥${best.likes}${styleTags.length && !hasStyle(best) ? ' (스타일 태그 없음, 대체)' : ''} #${best.tags.slice(0, 3).join(' #')} | ${best.goods.map((g) => g.name).join(' / ').slice(0, 90)}`)
|
||||||
|
}
|
||||||
|
writeFileSync(join(outDir, 'picks.json'), JSON.stringify(picks, null, 1))
|
||||||
|
const today = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||||
|
history[today] = [...new Set([...(history[today] ?? []), ...Object.values(picks).map((p) => p.id)])]
|
||||||
|
mkdirSync(resolve('out'), { recursive: true })
|
||||||
|
writeFileSync(HISTORY_FILE, JSON.stringify(history, null, 1))
|
||||||
|
return picks
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1]?.endsWith('snap.mjs')) {
|
||||||
|
const args = process.argv.slice(2)
|
||||||
|
const flag = (n) => (args.includes(n) ? args[args.indexOf(n) + 1] : null)
|
||||||
|
const band = flag('--band') ?? 'mild'
|
||||||
|
const outDir = flag('--out') ?? `out/${new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)}/snaps`
|
||||||
|
await pickSnaps({ band, style: flag('--style') ?? undefined, outDir, pages: Number(flag('--pages') ?? 2) })
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 204 KiB |
|
After Width: | Height: | Size: 201 KiB |
|
After Width: | Height: | Size: 214 KiB |
|
After Width: | Height: | Size: 228 KiB |
|
After Width: | Height: | Size: 245 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 280 KiB |
|
After Width: | Height: | Size: 203 KiB |
|
After Width: | Height: | Size: 218 KiB |
|
After Width: | Height: | Size: 255 KiB |
|
After Width: | Height: | Size: 221 KiB |
|
After Width: | Height: | Size: 227 KiB |
|
After Width: | Height: | Size: 214 KiB |
|
After Width: | Height: | Size: 273 KiB |
|
After Width: | Height: | Size: 220 KiB |
|
After Width: | Height: | Size: 174 KiB |
|
After Width: | Height: | Size: 348 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 244 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 194 KiB |
|
After Width: | Height: | Size: 219 KiB |
|
After Width: | Height: | Size: 232 KiB |
|
After Width: | Height: | Size: 236 KiB |
|
After Width: | Height: | Size: 237 KiB |
|
After Width: | Height: | Size: 204 KiB |
|
After Width: | Height: | Size: 260 KiB |
|
After Width: | Height: | Size: 219 KiB |
@@ -133,7 +133,7 @@
|
|||||||
top: 350px;
|
top: 350px;
|
||||||
left: 80px;
|
left: 80px;
|
||||||
width: 920px;
|
width: 920px;
|
||||||
height: 800px;
|
height: 760px;
|
||||||
border-radius: 44px;
|
border-radius: 44px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: var(--stage);
|
background: var(--stage);
|
||||||
@@ -141,7 +141,7 @@
|
|||||||
.ootd-stage > img {
|
.ootd-stage > img {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
object-fit: cover;
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
.ootd-labels {
|
.ootd-labels {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
@@ -159,7 +159,7 @@
|
|||||||
/* 그림 아래 옷 목록: 그림 속 위치에 기대지 않고 따로 적는다 */
|
/* 그림 아래 옷 목록: 그림 속 위치에 기대지 않고 따로 적는다 */
|
||||||
.ootd-items {
|
.ootd-items {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 1168px;
|
top: 1126px;
|
||||||
left: 80px;
|
left: 80px;
|
||||||
right: 80px;
|
right: 80px;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
@@ -168,13 +168,14 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 10px;
|
align-content: flex-start;
|
||||||
|
gap: 8px;
|
||||||
}
|
}
|
||||||
.ootd-items li {
|
.ootd-items li {
|
||||||
padding: 8px 18px;
|
padding: 7px 16px;
|
||||||
border-radius: 99px;
|
border-radius: 99px;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
font-size: 28px;
|
font-size: 26px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
box-shadow: 0 6px 16px #28304a1f;
|
box-shadow: 0 6px 16px #28304a1f;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import spec from '../../image-prompts/ootd.json'
|
|||||||
/** 낮 최고기온 구간 × 스타일 × 사람별 옷. 옷 목록·카드 글자는 image-prompts/ootd.json 한 곳에서 정한다.
|
/** 낮 최고기온 구간 × 스타일 × 사람별 옷. 옷 목록·카드 글자는 image-prompts/ootd.json 한 곳에서 정한다.
|
||||||
* 그림은 src/assets/ootd/<구간>-<사람>-<스타일>.webp 가 있으면 자동으로 붙는다 (npm run gen-image -- ootd <구간|스타일>).
|
* 그림은 src/assets/ootd/<구간>-<사람>-<스타일>.webp 가 있으면 자동으로 붙는다 (npm run gen-image -- ootd <구간|스타일>).
|
||||||
* 일교차가 크면(OUTER_GAP_C 이상) 겉옷을 5번째 옷으로 그린 <구간>-<사람>-<스타일>-outer.webp 를 쓰고 이름표에도 겉옷을 더한다 */
|
* 일교차가 크면(OUTER_GAP_C 이상) 겉옷을 5번째 옷으로 그린 <구간>-<사람>-<스타일>-outer.webp 를 쓰고 이름표에도 겉옷을 더한다 */
|
||||||
export type Outfit = { persona: string; label: string; labels: string[]; outer: string; imageId: string; image?: string }
|
export type Outfit = { persona: string; label: string; style?: string; labels: string[]; outer: string; imageId: string; image?: string }
|
||||||
export type OotdBand = { id: string; from: number }
|
export type OotdBand = { id: string; from: number }
|
||||||
|
|
||||||
const IMAGES = import.meta.glob<string>('../assets/ootd/*.webp', { eager: true, import: 'default' })
|
const IMAGES = import.meta.glob<string>('../assets/ootd/*.webp', { eager: true, import: 'default' })
|
||||||
@@ -27,6 +27,17 @@ export function ootdBand(maxC: number) {
|
|||||||
return OOTD_BANDS.find((b) => maxC >= b.from) ?? OOTD_BANDS[OOTD_BANDS.length - 1]
|
return OOTD_BANDS.find((b) => maxC >= b.from) ?? OOTD_BANDS[OOTD_BANDS.length - 1]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 그날 무신사 스냅에서 뽑은 코디 (scripts/daily-ootd.mjs 가 copy.outfits 에 JSON 문자열로 넣는다). 없으면 undefined */
|
||||||
|
export function dailyOutfits(copy: Record<string, string>): Outfit[] | undefined {
|
||||||
|
if (!copy.outfits) return undefined
|
||||||
|
try {
|
||||||
|
const list = JSON.parse(copy.outfits) as { persona: string; label: string; style?: string; labels: string[]; image: string }[]
|
||||||
|
return list.map((o) => ({ persona: o.persona, label: o.label, style: o.style, labels: o.labels, outer: '', imageId: o.image, image: o.image }))
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 그 구간·스타일의 사람별 옷. bandId 를 주면 기온 대신 그 구간 (예시 카드용). withOuter 면 겉옷 포함 그림·이름표 */
|
/** 그 구간·스타일의 사람별 옷. bandId 를 주면 기온 대신 그 구간 (예시 카드용). withOuter 면 겉옷 포함 그림·이름표 */
|
||||||
export function ootdOutfits(maxC: number, style?: string, bandId?: string, withOuter = false): Outfit[] {
|
export function ootdOutfits(maxC: number, style?: string, bandId?: string, withOuter = false): Outfit[] {
|
||||||
const band = spec.bands.find((b) => b.id === (bandId || ootdBand(maxC).id))!
|
const band = spec.bands.find((b) => b.id === (bandId || ootdBand(maxC).id))!
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import stillNight from '../assets/intro/still-night.webp'
|
|||||||
import type { CardData } from './data'
|
import type { CardData } from './data'
|
||||||
import { Frame, Lines } from './Frame'
|
import { Frame, Lines } from './Frame'
|
||||||
import { tidy } from './text'
|
import { tidy } from './text'
|
||||||
import { DEFAULT_STYLE, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd'
|
import { DEFAULT_STYLE, dailyOutfits, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd'
|
||||||
import { gakArt, gakByCode } from './gaks'
|
import { gakArt, gakByCode } from './gaks'
|
||||||
|
|
||||||
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
|
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
|
||||||
@@ -65,6 +65,7 @@ const ootd: Template = {
|
|||||||
hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상',
|
hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상',
|
||||||
}),
|
}),
|
||||||
warnings: (d, c) => {
|
warnings: (d, c) => {
|
||||||
|
if (dailyOutfits(c)) return []
|
||||||
const missing = ootdOutfits(d.maxC, c.style, undefined, needsOuter(d.maxC, d.morningC)).filter((o) => !o.image)
|
const missing = ootdOutfits(d.maxC, c.style, undefined, needsOuter(d.maxC, d.morningC)).filter((o) => !o.image)
|
||||||
const id = `${ootdBand(d.maxC).id}`
|
const id = `${ootdBand(d.maxC).id}`
|
||||||
return missing.length
|
return missing.length
|
||||||
@@ -72,11 +73,11 @@ const ootd: Template = {
|
|||||||
: []
|
: []
|
||||||
},
|
},
|
||||||
slides: (d, c) =>
|
slides: (d, c) =>
|
||||||
ootdOutfits(d.maxC, c.style, c.band, needsOuter(d.maxC, d.morningC)).map((o, i, all) => (
|
(dailyOutfits(c) ?? ootdOutfits(d.maxC, c.style, c.band, needsOuter(d.maxC, d.morningC))).map((o, i, all) => (
|
||||||
<Frame page={i} total={all.length} theme={c.theme} className="ootd" key={o.persona}>
|
<Frame page={i} total={all.length} theme={c.theme} className="ootd" key={o.persona}>
|
||||||
<p className="meta">{d.dateLabel} · 오늘의 코디</p>
|
<p className="meta">{d.dateLabel} · 오늘의 코디</p>
|
||||||
<h1 className="ootd-title">
|
<h1 className="ootd-title">
|
||||||
<Lines text={`*${o.label}* ${styleLabel(c.style)}${c.title ? ` ${c.title}` : ''}`} />
|
<Lines text={`*${o.label}* ${o.style ?? styleLabel(c.style)}${c.title ? ` ${c.title}` : ''}`} />
|
||||||
</h1>
|
</h1>
|
||||||
<div className="ootd-stage">
|
<div className="ootd-stage">
|
||||||
{o.image ? (
|
{o.image ? (
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { spawn } from 'node:child_process'
|
import { spawn } from 'node:child_process'
|
||||||
|
import { createReadStream, existsSync } from 'node:fs'
|
||||||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||||
|
import { basename, resolve } from 'node:path'
|
||||||
import tailwindcss from '@tailwindcss/vite'
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
import { defineConfig, type Plugin } from 'vite'
|
import { defineConfig, type Plugin } from 'vite'
|
||||||
@@ -171,9 +173,26 @@ function postApi(): Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** GET /daily/<날짜>-<사람>.webp → public/daily (scripts/daily-ootd.mjs 가 만든 그날 코디 그림). publicDir 는 프론트 아이콘용이라 따로 서빙 */
|
||||||
|
function dailyImages(): Plugin {
|
||||||
|
return {
|
||||||
|
name: 'daily-images',
|
||||||
|
configureServer(server) {
|
||||||
|
server.middlewares.use('/daily', (req, res, next) => {
|
||||||
|
const name = basename((req.url ?? '').split('?')[0])
|
||||||
|
const file = resolve(import.meta.dirname, 'public/daily', name)
|
||||||
|
if (!name.endsWith('.webp') || !existsSync(file)) return next()
|
||||||
|
res.setHeader('Content-Type', 'image/webp')
|
||||||
|
res.setHeader('Cache-Control', 'no-cache')
|
||||||
|
createReadStream(file).pipe(res)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 각 아이콘·캐릭터는 서비스와 같은 파일을 쓴다 (/icons/*.png)
|
// 각 아이콘·캐릭터는 서비스와 같은 파일을 쓴다 (/icons/*.png)
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi()],
|
plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi(), dailyImages()],
|
||||||
publicDir: '../frontend/public',
|
publicDir: '../frontend/public',
|
||||||
server: { port: 5175, strictPort: true },
|
server: { port: 5175, strictPort: true },
|
||||||
})
|
})
|
||||||
@@ -360,7 +360,6 @@ class User(Base):
|
|||||||
color: Mapped[str] = mapped_column(String(20), default="orange")
|
color: Mapped[str] = mapped_column(String(20), default="orange")
|
||||||
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
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)
|
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
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())
|
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
@@ -401,29 +400,10 @@ class Comment(Base):
|
|||||||
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||||
body: Mapped[str] = mapped_column(String(60))
|
body: Mapped[str] = mapped_column(String(60))
|
||||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
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())
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
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):
|
class CommentLike(Base):
|
||||||
__tablename__ = "comment_like"
|
__tablename__ = "comment_like"
|
||||||
|
|
||||||
@@ -492,3 +472,9 @@ class TalkReport(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
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())
|
||||||
@@ -25,7 +25,6 @@ class ErrorType(Enum):
|
|||||||
AUTH_FAILED = 4002
|
AUTH_FAILED = 4002
|
||||||
AUTH_DUPLICATE_ID = 4003
|
AUTH_DUPLICATE_ID = 4003
|
||||||
AUTH_TOKEN_INVALID = 4004
|
AUTH_TOKEN_INVALID = 4004
|
||||||
TERMS_REQUIRED = 4005
|
|
||||||
|
|
||||||
|
|
||||||
class Sky(CodeEnum):
|
class Sky(CodeEnum):
|
||||||
@@ -192,10 +191,3 @@ class CardStatus(CodeEnum):
|
|||||||
class AuthProvider(CodeEnum):
|
class AuthProvider(CodeEnum):
|
||||||
LOCAL = 1
|
LOCAL = 1
|
||||||
GOOGLE = 2
|
GOOGLE = 2
|
||||||
|
|
||||||
|
|
||||||
class ReportReason(CodeEnum):
|
|
||||||
ABUSE = 1
|
|
||||||
AD = 2
|
|
||||||
PRIVACY = 3
|
|
||||||
OTHER = 4
|
|
||||||
@@ -2,15 +2,13 @@ import uuid
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy import delete, func, or_, select, update
|
from sqlalchemy import delete, func, select, update
|
||||||
from sqlalchemy.dialects.postgresql import insert
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, CommentReport, Post, PostLike, PostLikeAnon, PostSave, User, UserBlock
|
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, Post, PostLike, PostLikeAnon, PostSave, User
|
||||||
from common.liker import Liker
|
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:
|
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."""
|
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
|
||||||
@@ -54,16 +52,9 @@ class ReactionCRUD:
|
|||||||
stmt = stmt.where(Post.post_id < cursor)
|
stmt = stmt.where(Post.post_id < cursor)
|
||||||
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
|
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
|
||||||
|
|
||||||
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]]]:
|
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 이다. 숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
|
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다."""
|
||||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(
|
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.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:
|
if cursor is not None:
|
||||||
stmt = stmt.where(Comment.comment_id > cursor)
|
stmt = stmt.where(Comment.comment_id > cursor)
|
||||||
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
|
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
|
||||||
@@ -90,61 +81,18 @@ 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))
|
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(
|
res = await s.execute(
|
||||||
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
|
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
|
||||||
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
|
.values(deleted=True).returning(Comment.post_id)
|
||||||
)
|
)
|
||||||
row = res.first()
|
post_id = res.scalar()
|
||||||
if row is None:
|
if post_id is None:
|
||||||
return False
|
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
|
return True
|
||||||
|
|
||||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
|
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), Comment.is_hidden.is_(False)))
|
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
|
||||||
if exists is None:
|
if exists is None:
|
||||||
return None
|
return None
|
||||||
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
|
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)))
|
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))
|
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())
|
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
import uuid
|
import uuid
|
||||||
from collections import Counter
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy import delete, select, update
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.model.models import Comment, CommentLike, CommentReport, Post, PostLike, PostSave, User, UserBlock
|
from common.database.model.models import User
|
||||||
|
|
||||||
|
|
||||||
class UserCRUD:
|
class UserCRUD:
|
||||||
@@ -38,29 +37,3 @@ class UserCRUD:
|
|||||||
user.updated_at = datetime.now(timezone.utc)
|
user.updated_at = datetime.now(timezone.utc)
|
||||||
await s.flush()
|
await s.flush()
|
||||||
return user
|
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))
|
|
||||||
@@ -218,7 +218,6 @@ CREATE TABLE IF NOT EXISTS public.users (
|
|||||||
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
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 = 안 고름
|
mood VARCHAR(20) NULL, -- 오늘 기분: clear·partly·cloudy·rain·thunder·snow·fog·rainbow. NULL = 안 고름
|
||||||
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
||||||
terms_agreed_at TIMESTAMPTZ NULL, -- 이용약관 동의 시각. NULL 이면 댓글을 못 쓴다
|
|
||||||
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
@@ -266,28 +265,16 @@ 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;
|
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;
|
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
|
||||||
|
|
||||||
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 report_count INTEGER NOT NULL DEFAULT 0;
|
||||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS is_hidden BOOLEAN NOT NULL DEFAULT FALSE; -- 신고 3건이면 숨김. 숨긴 댓글은 댓글 수에서 빠진다
|
-- 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,
|
||||||
CREATE TABLE IF NOT EXISTS public.comment_report (
|
-- user_id UUID NOT NULL,
|
||||||
comment_id BIGINT NOT NULL,
|
-- reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||||
user_id UUID NOT NULL,
|
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
-- PRIMARY KEY (comment_id, user_id)
|
||||||
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 (
|
CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||||
comment_id BIGINT NOT NULL,
|
comment_id BIGINT NOT NULL,
|
||||||
@@ -355,6 +342,14 @@ CREATE TABLE IF NOT EXISTS public.talk_report (
|
|||||||
PRIMARY KEY (talk_id, user_id)
|
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)
|
||||||
|
);
|
||||||
|
|
||||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||||
|
|
||||||
-- 구 목록.
|
-- 구 목록.
|
||||||
|
|||||||
@@ -5,14 +5,14 @@ from common.database.model.models import User
|
|||||||
from common.enums import AuthProvider, ErrorType
|
from common.enums import AuthProvider, ErrorType
|
||||||
from common.models.errors import error_info
|
from common.models.errors import error_info
|
||||||
from config.settings import settings
|
from config.settings import settings
|
||||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_Withdraw
|
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me
|
||||||
from services.auth_service import AuthService
|
from services.auth_service import AuthService
|
||||||
|
|
||||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
def _me(u: User) -> Me:
|
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), terms_agreed=u.terms_agreed_at is not None)
|
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider))
|
||||||
|
|
||||||
|
|
||||||
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
|
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
|
||||||
@@ -68,17 +68,3 @@ async def update_me(req: Req_UpdateMe, user: User = Depends(current_user), servi
|
|||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return Res_Me(result=error_info(err))
|
return Res_Me(result=error_info(err))
|
||||||
return Res_Me(me=_me(updated))
|
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))
|
|
||||||
@@ -39,7 +39,6 @@ class Me(WebPacketProtocol):
|
|||||||
color: str
|
color: str
|
||||||
mood: Optional[str] = None
|
mood: Optional[str] = None
|
||||||
provider: AuthProvider
|
provider: AuthProvider
|
||||||
terms_agreed: bool = False
|
|
||||||
|
|
||||||
|
|
||||||
class Res_Auth(Res_WebPacketProtocol):
|
class Res_Auth(Res_WebPacketProtocol):
|
||||||
@@ -52,10 +51,6 @@ class Res_Logout(Res_WebPacketProtocol):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Res_Withdraw(Res_WebPacketProtocol):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class Res_Me(Res_WebPacketProtocol):
|
class Res_Me(Res_WebPacketProtocol):
|
||||||
me: Optional[Me] = None
|
me: Optional[Me] = None
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import uuid
|
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
|
||||||
from common.enums import PostType, ReportReason
|
from common.enums import PostType
|
||||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||||
|
|
||||||
|
|
||||||
@@ -59,18 +58,3 @@ class Res_Comment(Res_WebPacketProtocol):
|
|||||||
class Res_CommentLike(Res_WebPacketProtocol):
|
class Res_CommentLike(Res_WebPacketProtocol):
|
||||||
liked: Optional[bool] = None
|
liked: Optional[bool] = None
|
||||||
like_count: Optional[int] = 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] = []
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import uuid
|
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Path, Query
|
from fastapi import APIRouter, Depends, Path, Query
|
||||||
@@ -11,8 +10,7 @@ from common.models.errors import error_info
|
|||||||
from common.models.gmodel import Res_WebPacketProtocol
|
from common.models.gmodel import Res_WebPacketProtocol
|
||||||
from common.utils.kma_time import KST
|
from common.utils.kma_time import KST
|
||||||
from router.v1.reaction.protocol import (
|
from router.v1.reaction.protocol import (
|
||||||
BlockedUser, CommentData, Req_Comment, Req_Report, Res_BlockedList, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave,
|
CommentData, Req_Comment, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave, Res_SavedList, SavedPost,
|
||||||
Res_SavedList, SavedPost,
|
|
||||||
)
|
)
|
||||||
from services.reaction_service import PAGE, CommentView, ReactionService
|
from services.reaction_service import PAGE, CommentView, ReactionService
|
||||||
|
|
||||||
@@ -71,7 +69,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)
|
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개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)")
|
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)")
|
||||||
async def add_comment(
|
async def add_comment(
|
||||||
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
|
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
|
||||||
) -> Res_Comment:
|
) -> Res_Comment:
|
||||||
@@ -97,26 +95,3 @@ 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="댓글 좋아요 취소")
|
@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:
|
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)
|
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)))
|
|
||||||
@@ -14,7 +14,7 @@ async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path
|
|||||||
err, html = await service.page(f"today/{sido}/{place}")
|
err, html = await service.page(f"today/{sido}/{place}")
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return HTMLResponse("not found", status_code=404)
|
return HTMLResponse("not found", status_code=404)
|
||||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
|
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
|
||||||
@@ -22,7 +22,7 @@ async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = P
|
|||||||
err, html = await service.page(f"today/{sido}/{place}/{gu}")
|
err, html = await service.page(f"today/{sido}/{place}/{gu}")
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return HTMLResponse("not found", status_code=404)
|
return HTMLResponse("not found", status_code=404)
|
||||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
|
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
|
||||||
@@ -30,7 +30,7 @@ async def get_tomorrow_page(sido: str = Path(..., pattern=_SLUG), place: str = P
|
|||||||
err, html = await service.page(f"tomorrow/{sido}/{place}")
|
err, html = await service.page(f"tomorrow/{sido}/{place}")
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return HTMLResponse("not found", status_code=404)
|
return HTMLResponse("not found", status_code=404)
|
||||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
|
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
|
||||||
@@ -38,4 +38,4 @@ async def get_tomorrow_gu_page(sido: str = Path(..., pattern=_SLUG), place: str
|
|||||||
err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}")
|
err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}")
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return HTMLResponse("not found", status_code=404)
|
return HTMLResponse("not found", status_code=404)
|
||||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
"""운영자용 댓글·사용자 조치.
|
|
||||||
|
|
||||||
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:])))
|
|
||||||
@@ -91,16 +91,6 @@ 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})])
|
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]]:
|
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 = {}
|
values: dict = {}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import uuid
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
@@ -7,7 +6,7 @@ from fastapi import Depends
|
|||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import Comment, Post, User
|
from common.database.model.models import Comment, Post, User
|
||||||
from common.enums import ErrorType, ReportReason
|
from common.enums import ErrorType
|
||||||
from common.liker import Liker
|
from common.liker import Liker
|
||||||
from common.utils.kma_time import kst_midnight, now_kst
|
from common.utils.kma_time import kst_midnight, now_kst
|
||||||
from crud.feed_crud import FeedCRUD
|
from crud.feed_crud import FeedCRUD
|
||||||
@@ -93,7 +92,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)
|
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]]:
|
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, user.user_id if user else None, cursor, PAGE))
|
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, []
|
return err, []
|
||||||
liked: set[int] = set()
|
liked: set[int] = set()
|
||||||
@@ -110,8 +109,6 @@ class ReactionService:
|
|||||||
body = body.strip()
|
body = body.strip()
|
||||||
if not body or len(body) > COMMENT_MAX:
|
if not body or len(body) > COMMENT_MAX:
|
||||||
return ErrorType.INVALID_INPUT, None
|
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)
|
err = await self._post_exists(post_id)
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, None
|
return err, None
|
||||||
@@ -148,37 +145,3 @@ class ReactionService:
|
|||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, None
|
return err, None
|
||||||
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
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 []
|
|
||||||
@@ -43,7 +43,7 @@ def anyio_backend():
|
|||||||
|
|
||||||
_VOLATILE = (
|
_VOLATILE = (
|
||||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
"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", "comment_report", "user_block", "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", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -14,9 +14,7 @@ def client():
|
|||||||
|
|
||||||
async def _login(c, login_id: str) -> dict:
|
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()
|
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||||
h = {"Authorization": f"Bearer {body['access_token']}"}
|
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||||
await c.post("/v1/auth/terms", headers=h) # 로그인한 사람은 약관에 동의해야 댓글을 쓴다
|
|
||||||
return h
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
@@ -149,26 +147,3 @@ async def test_hero_tomorrow_and_tomorrow_slots(offline):
|
|||||||
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
||||||
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
||||||
assert res["day"] == hero["tomorrow"]["day"]
|
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"]]
|
|
||||||
@@ -10,12 +10,8 @@ def client():
|
|||||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||||
|
|
||||||
|
|
||||||
async def _signup(c, login_id="mina_01", nickname="망원동주민", agree=True):
|
async def _signup(c, login_id="mina_01", nickname="망원동주민"):
|
||||||
"""가입하고, 댓글을 쓸 수 있게 이용약관에도 동의한다 (agree=False 면 안 함)."""
|
return (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||||
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
|
@pytest.mark.anyio
|
||||||
@@ -126,118 +122,3 @@ 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"
|
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()
|
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
|
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) == ["남아요"]
|
|
||||||
@@ -84,7 +84,6 @@ async def test_like_in_one_sido_not_seen_in_another(offline):
|
|||||||
async with client() as c:
|
async with client() as c:
|
||||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||||
h = {"Authorization": f"Bearer {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()
|
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)
|
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
|
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ services:
|
|||||||
# 운영형: docker compose up --build → http://localhost:8080
|
# 운영형: docker compose up --build → http://localhost:8080
|
||||||
frontend:
|
frontend:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: ./frontend
|
||||||
dockerfile: frontend/Dockerfile
|
|
||||||
target: prod
|
target: prod
|
||||||
args:
|
args:
|
||||||
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
||||||
@@ -20,16 +19,13 @@ services:
|
|||||||
frontend-dev:
|
frontend-dev:
|
||||||
profiles: ["dev"]
|
profiles: ["dev"]
|
||||||
build:
|
build:
|
||||||
context: .
|
context: ./frontend
|
||||||
dockerfile: frontend/Dockerfile
|
|
||||||
target: dev
|
target: dev
|
||||||
ports:
|
ports:
|
||||||
- "5173:5173"
|
- "5173:5173"
|
||||||
volumes:
|
volumes:
|
||||||
- ./frontend:/app/frontend
|
- ./frontend:/app
|
||||||
- ./shared:/app/shared
|
|
||||||
- /app/node_modules
|
- /app/node_modules
|
||||||
- /app/frontend/node_modules
|
|
||||||
environment:
|
environment:
|
||||||
- CHOKIDAR_USEPOLLING=true
|
- CHOKIDAR_USEPOLLING=true
|
||||||
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
|
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.git
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
@@ -2,19 +2,13 @@
|
|||||||
|
|
||||||
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
|
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
|
||||||
FROM node:24-alpine AS deps
|
FROM node:24-alpine AS deps
|
||||||
# 빌드 대상은 저장소 루트(npm workspaces). 웹에 필요한 frontend·shared 만 설치한다
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
COPY frontend/package.json frontend/
|
RUN npm ci
|
||||||
COPY shared/package.json shared/
|
|
||||||
COPY mobile/package.json mobile/
|
|
||||||
RUN npm ci -w frontend -w shared
|
|
||||||
|
|
||||||
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
|
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
|
||||||
FROM deps AS dev
|
FROM deps AS dev
|
||||||
COPY shared shared
|
COPY . .
|
||||||
COPY frontend frontend
|
|
||||||
WORKDIR /app/frontend
|
|
||||||
EXPOSE 5173
|
EXPOSE 5173
|
||||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
||||||
|
|
||||||
@@ -24,14 +18,12 @@ ARG VITE_API_BASE_URL=""
|
|||||||
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
||||||
ARG VITE_SITE_URL=""
|
ARG VITE_SITE_URL=""
|
||||||
ENV VITE_SITE_URL=$VITE_SITE_URL
|
ENV VITE_SITE_URL=$VITE_SITE_URL
|
||||||
COPY shared shared
|
COPY . .
|
||||||
COPY frontend frontend
|
|
||||||
WORKDIR /app/frontend
|
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# ---- prod: nginx로 정적 파일 제공 ----
|
# ---- prod: nginx로 정적 파일 제공 ----
|
||||||
FROM nginx:1.29-alpine AS prod
|
FROM nginx:1.29-alpine AS prod
|
||||||
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
COPY --from=build /app/frontend/dist /usr/share/nginx/html
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
EXPOSE 80
|
EXPOSE 80
|
||||||
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
|
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
|
||||||
@@ -2,7 +2,7 @@ import { defineConfig } from '@hey-api/openapi-ts'
|
|||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
|
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
|
||||||
output: '../shared/api/client',
|
output: 'src/api/client',
|
||||||
parser: {
|
parser: {
|
||||||
patch: {
|
patch: {
|
||||||
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
|
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
|
||||||
|
|||||||
@@ -11,7 +11,6 @@
|
|||||||
"api": "openapi-ts"
|
"api": "openapi-ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nalssigak/shared": "*",
|
|
||||||
"@tailwindcss/vite": "^4.3.3",
|
"@tailwindcss/vite": "^4.3.3",
|
||||||
"@tanstack/react-query": "^5.104.0",
|
"@tanstack/react-query": "^5.104.0",
|
||||||
"embla-carousel-react": "^8.6.0",
|
"embla-carousel-react": "^8.6.0",
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="ko">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>이용약관 - 날씨각</title>
|
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
||||||
<style>
|
|
||||||
body { margin: 0; padding: 32px 20px 64px; font: 15px/1.7 -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif; color: #28304a; background: #f1f8ff; }
|
|
||||||
main { max-width: 720px; margin: 0 auto; }
|
|
||||||
h1 { font-size: 26px; margin: 0 0 4px; }
|
|
||||||
h2 { font-size: 18px; margin: 32px 0 8px; }
|
|
||||||
.muted { color: #5a6380; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<main>
|
|
||||||
<h1>이용약관</h1>
|
|
||||||
<p class="muted">시행일: 2026년 10월 20일</p>
|
|
||||||
|
|
||||||
<p>이 약관은 AIO2O(이하 "회사")가 운영하는 날씨각 웹·앱 서비스(이하 "서비스")를 이용하는 조건을 정합니다. 댓글을 쓰려면 이 약관에 동의해야 합니다.</p>
|
|
||||||
|
|
||||||
<h2>1. 서비스</h2>
|
|
||||||
<p>서비스는 지역별 날씨, 하늘·노을 예보, 생활 지수, 주변 행사 같은 정보를 제공합니다. 날씨 정보는 기상청 등 외부 자료를 바탕으로 한 예보이며 실제 날씨와 다를 수 있습니다.</p>
|
|
||||||
|
|
||||||
<h2>2. 계정</h2>
|
|
||||||
<p>회원은 자신의 계정을 직접 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다. 회원은 언제든지 내 정보에서 탈퇴할 수 있고, 탈퇴하면 계정과 남긴 댓글·좋아요·저장·신고·차단 기록이 모두 지워집니다.</p>
|
|
||||||
|
|
||||||
<h2>3. 댓글에 쓰면 안 되는 내용</h2>
|
|
||||||
<p>아래 내용은 댓글로 쓸 수 없습니다.</p>
|
|
||||||
<ul>
|
|
||||||
<li>욕설, 비하, 혐오, 따돌림, 위협</li>
|
|
||||||
<li>광고, 홍보, 같은 내용 반복 게시</li>
|
|
||||||
<li>전화번호·주소 등 자신이나 다른 사람의 개인정보</li>
|
|
||||||
<li>음란하거나 폭력적인 내용, 불법 행위를 부추기는 내용</li>
|
|
||||||
<li>다른 사람의 권리(저작권·초상권·명예 등)를 침해하는 내용</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<h2>4. 신고·차단과 조치</h2>
|
|
||||||
<p>회원은 댓글마다 신고하거나 그 댓글을 쓴 사람을 차단할 수 있습니다. 신고한 댓글과 차단한 사람의 댓글은 본인에게 더는 보이지 않습니다. 신고가 여러 건 쌓인 댓글은 자동으로 숨겨지고, 회사가 확인해 3항을 어긴 댓글은 숨기거나 지우며, 반복해서 어긴 회원은 서비스 이용을 제한할 수 있습니다. 조치에 이의가 있으면 아래 연락처로 알려 주세요.</p>
|
|
||||||
|
|
||||||
<h2>5. 게시물의 권리와 책임</h2>
|
|
||||||
<p>댓글의 권리와 책임은 작성한 회원에게 있습니다. 회사는 서비스 화면에 댓글을 보여 주는 범위에서만 이를 사용합니다.</p>
|
|
||||||
|
|
||||||
<h2>6. 서비스 변경·중단</h2>
|
|
||||||
<p>회사는 운영상 필요하면 서비스 내용을 바꾸거나 중단할 수 있으며, 중요한 변경은 미리 서비스 안에 알립니다.</p>
|
|
||||||
|
|
||||||
<h2>7. 책임의 한계</h2>
|
|
||||||
<p>회사는 예보와 실제 날씨의 차이, 회원 사이의 다툼, 회원이 쓴 댓글로 생긴 손해에 대해 회사의 고의나 중대한 과실이 없으면 책임지지 않습니다.</p>
|
|
||||||
|
|
||||||
<h2>8. 개인정보</h2>
|
|
||||||
<p>개인정보 처리는 <a href="/privacy.html">개인정보처리방침</a>을 따릅니다.</p>
|
|
||||||
|
|
||||||
<h2>9. 문의</h2>
|
|
||||||
<p>운영자: AIO2O<br />이메일: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></p>
|
|
||||||
|
|
||||||
<h2>10. 약관 변경</h2>
|
|
||||||
<p>이 약관이 바뀌면 시행 7일 전부터 이 페이지에 알립니다.</p>
|
|
||||||
</main>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,18 +1,10 @@
|
|||||||
// 로그인 토큰 저장소: 플랫폼 저장소(웹 localStorage, 앱 SecureStore) + 메모리, 바뀌면 구독자에게 알린다
|
// 로그인 토큰 저장소: localStorage + 메모리, 바뀌면 구독자에게 알린다
|
||||||
const ACCESS_KEY = 'nalssigak.accessToken'
|
const ACCESS_KEY = 'nalssigak.accessToken'
|
||||||
const REFRESH_KEY = 'nalssigak.refreshToken'
|
const REFRESH_KEY = 'nalssigak.refreshToken'
|
||||||
|
|
||||||
export type TokenStorage = {
|
|
||||||
getItem(key: string): string | null
|
|
||||||
setItem(key: string, value: string): void
|
|
||||||
removeItem(key: string): void
|
|
||||||
}
|
|
||||||
|
|
||||||
let storage: TokenStorage | null = null
|
|
||||||
|
|
||||||
function readStored(key: string): string | null {
|
function readStored(key: string): string | null {
|
||||||
try {
|
try {
|
||||||
return storage?.getItem(key) ?? null
|
return localStorage.getItem(key)
|
||||||
} catch {
|
} catch {
|
||||||
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
|
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
|
||||||
return null
|
return null
|
||||||
@@ -21,21 +13,15 @@ function readStored(key: string): string | null {
|
|||||||
|
|
||||||
function writeStored(key: string, value: string | null) {
|
function writeStored(key: string, value: string | null) {
|
||||||
try {
|
try {
|
||||||
if (value) storage?.setItem(key, value)
|
if (value) localStorage.setItem(key, value)
|
||||||
else storage?.removeItem(key)
|
else localStorage.removeItem(key)
|
||||||
} catch {
|
} catch {
|
||||||
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
|
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let accessToken: string | null = null
|
let accessToken = readStored(ACCESS_KEY)
|
||||||
|
|
||||||
/** 앱이 뜰 때 한 번: 저장된 토큰을 읽어 로그인 상태로 시작한다 */
|
|
||||||
export function setTokenStorage(next: TokenStorage) {
|
|
||||||
storage = next
|
|
||||||
accessToken = readStored(ACCESS_KEY)
|
|
||||||
}
|
|
||||||
const listeners = new Set<(reason: 'change' | 'required') => void>()
|
const listeners = new Set<(reason: 'change' | 'required') => void>()
|
||||||
|
|
||||||
/** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */
|
/** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||||
|
|
||||||
import { client } from '../client.gen';
|
import { client } from '../client.gen';
|
||||||
import { addComment, addMyGak, addTalk, agreeTerms, authConfig, blockAuthor, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listBlocked, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, refresh, rejectCard, reportComment, reportTalk, savePost, scoreMyGak, signup, talkGroups, unblock, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage, withdraw } from '../sdk.gen';
|
import { 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, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
|
||||||
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, CreateReelData, CreateReelError, CreateReelResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetReelCoverData, GetReelCoverError, GetReelVideoData, GetReelVideoError, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListBlockedData, ListBlockedError, ListBlockedResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListReelsData, ListReelsError, ListReelsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, PublishInstagram2Data, PublishInstagram2Error, PublishInstagram2Response, PublishInstagramData, PublishInstagramError, PublishInstagramResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen';
|
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AuthConfigData, AuthConfigResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
|
||||||
|
|
||||||
export type QueryKey<TOptions extends Options> = [
|
export type QueryKey<TOptions extends Options> = [
|
||||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||||
@@ -448,23 +448,6 @@ export const logoutMutation = (options?: Partial<Options<LogoutData>>): UseMutat
|
|||||||
return mutationOptions;
|
return mutationOptions;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 탈퇴 (계정과 남긴 댓글·좋아요를 모두 지운다)
|
|
||||||
*/
|
|
||||||
export const withdrawMutation = (options?: Partial<Options<WithdrawData>>): UseMutationOptions<WithdrawResponse, WithdrawError, Options<WithdrawData>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<WithdrawResponse, WithdrawError, Options<WithdrawData>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await withdraw({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const meQueryKey = (options?: Options<MeData>) => createQueryKey('me', options);
|
export const meQueryKey = (options?: Options<MeData>) => createQueryKey('me', options);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -500,23 +483,6 @@ export const updateMeMutation = (options?: Partial<Options<UpdateMeData>>): UseM
|
|||||||
return mutationOptions;
|
return mutationOptions;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 이용약관 동의 (댓글 쓰기 전에 한 번)
|
|
||||||
*/
|
|
||||||
export const agreeTermsMutation = (options?: Partial<Options<AgreeTermsData>>): UseMutationOptions<AgreeTermsResponse, AgreeTermsError, Options<AgreeTermsData>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<AgreeTermsResponse, AgreeTermsError, Options<AgreeTermsData>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await agreeTerms({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 좋아요 취소
|
* 좋아요 취소
|
||||||
*/
|
*/
|
||||||
@@ -711,7 +677,7 @@ export const listCommentsInfiniteOptions = (options: Options<ListCommentsData>)
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)
|
* 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)
|
||||||
*/
|
*/
|
||||||
export const addCommentMutation = (options?: Partial<Options<AddCommentData>>): UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> => {
|
export const addCommentMutation = (options?: Partial<Options<AddCommentData>>): UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> => {
|
||||||
const mutationOptions: UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> = {
|
const mutationOptions: UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> = {
|
||||||
@@ -778,75 +744,6 @@ export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>)
|
|||||||
return mutationOptions;
|
return mutationOptions;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)
|
|
||||||
*/
|
|
||||||
export const reportCommentMutation = (options?: Partial<Options<ReportCommentData>>): UseMutationOptions<ReportCommentResponse, ReportCommentError, Options<ReportCommentData>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<ReportCommentResponse, ReportCommentError, Options<ReportCommentData>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await reportComment({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임)
|
|
||||||
*/
|
|
||||||
export const blockAuthorMutation = (options?: Partial<Options<BlockAuthorData>>): UseMutationOptions<BlockAuthorResponse, BlockAuthorError, Options<BlockAuthorData>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<BlockAuthorResponse, BlockAuthorError, Options<BlockAuthorData>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await blockAuthor({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const listBlockedQueryKey = (options?: Options<ListBlockedData>) => createQueryKey('listBlocked', options);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 내가 차단한 사람
|
|
||||||
*/
|
|
||||||
export const listBlockedOptions = (options?: Options<ListBlockedData>) => queryOptions<ListBlockedResponse, ListBlockedError, ListBlockedResponse, ReturnType<typeof listBlockedQueryKey>>({
|
|
||||||
queryFn: async ({ queryKey, signal }) => {
|
|
||||||
const { data } = await listBlocked({
|
|
||||||
...options,
|
|
||||||
...queryKey[0],
|
|
||||||
signal,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
queryKey: listBlockedQueryKey(options)
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 차단 풀기
|
|
||||||
*/
|
|
||||||
export const unblockMutation = (options?: Partial<Options<UnblockData>>): UseMutationOptions<UnblockResponse, UnblockError, Options<UnblockData>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<UnblockResponse, UnblockError, Options<UnblockData>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await unblock({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const listMyGakQueryKey = (options?: Options<ListMyGakData>) => createQueryKey('listMyGak', options);
|
export const listMyGakQueryKey = (options?: Options<ListMyGakData>) => createQueryKey('listMyGak', options);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1362,23 +1259,6 @@ export const rejectCardMutation = (options?: Partial<Options<RejectCardData>>):
|
|||||||
return mutationOptions;
|
return mutationOptions;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만
|
|
||||||
*/
|
|
||||||
export const publishInstagramMutation = (options?: Partial<Options<PublishInstagramData>>): UseMutationOptions<PublishInstagramResponse, PublishInstagramError, Options<PublishInstagramData>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<PublishInstagramResponse, PublishInstagramError, Options<PublishInstagramData>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await publishInstagram({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getCardImageQueryKey = (options: Options<GetCardImageData>) => createQueryKey('getCardImage', options);
|
export const getCardImageQueryKey = (options: Options<GetCardImageData>) => createQueryKey('getCardImage', options);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1397,94 +1277,6 @@ export const getCardImageOptions = (options: Options<GetCardImageData>) => query
|
|||||||
queryKey: getCardImageQueryKey(options)
|
queryKey: getCardImageQueryKey(options)
|
||||||
});
|
});
|
||||||
|
|
||||||
export const listReelsQueryKey = (options?: Options<ListReelsData>) => createQueryKey('listReels', options);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 목록 (관리자)
|
|
||||||
*/
|
|
||||||
export const listReelsOptions = (options?: Options<ListReelsData>) => queryOptions<ListReelsResponse, ListReelsError, ListReelsResponse, ReturnType<typeof listReelsQueryKey>>({
|
|
||||||
queryFn: async ({ queryKey, signal }) => {
|
|
||||||
const { data } = await listReels({
|
|
||||||
...options,
|
|
||||||
...queryKey[0],
|
|
||||||
signal,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
queryKey: listReelsQueryKey(options)
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 mp4 저장 (관리자). 공개 주소가 생기고, 인스타엔 따로 올린다
|
|
||||||
*/
|
|
||||||
export const createReelMutation = (options?: Partial<Options<CreateReelData>>): UseMutationOptions<CreateReelResponse, CreateReelError, Options<CreateReelData>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<CreateReelResponse, CreateReelError, Options<CreateReelData>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await createReel({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스를 인스타그램에 올리기 (관리자). 같은 릴스는 한 번만
|
|
||||||
*/
|
|
||||||
export const publishInstagram2Mutation = (options?: Partial<Options<PublishInstagram2Data>>): UseMutationOptions<PublishInstagram2Response, PublishInstagram2Error, Options<PublishInstagram2Data>> => {
|
|
||||||
const mutationOptions: UseMutationOptions<PublishInstagram2Response, PublishInstagram2Error, Options<PublishInstagram2Data>> = {
|
|
||||||
mutationFn: async (fnOptions) => {
|
|
||||||
const { data } = await publishInstagram2({
|
|
||||||
...options,
|
|
||||||
...fnOptions,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return mutationOptions;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getReelVideoQueryKey = (options: Options<GetReelVideoData>) => createQueryKey('getReelVideo', options);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 영상 (인스타가 받아 가는 공개 주소, Range 지원)
|
|
||||||
*/
|
|
||||||
export const getReelVideoOptions = (options: Options<GetReelVideoData>) => queryOptions<unknown, GetReelVideoError, unknown, ReturnType<typeof getReelVideoQueryKey>>({
|
|
||||||
queryFn: async ({ queryKey, signal }) => {
|
|
||||||
const { data } = await getReelVideo({
|
|
||||||
...options,
|
|
||||||
...queryKey[0],
|
|
||||||
signal,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
queryKey: getReelVideoQueryKey(options)
|
|
||||||
});
|
|
||||||
|
|
||||||
export const getReelCoverQueryKey = (options: Options<GetReelCoverData>) => createQueryKey('getReelCover', options);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 표지
|
|
||||||
*/
|
|
||||||
export const getReelCoverOptions = (options: Options<GetReelCoverData>) => queryOptions<unknown, GetReelCoverError, unknown, ReturnType<typeof getReelCoverQueryKey>>({
|
|
||||||
queryFn: async ({ queryKey, signal }) => {
|
|
||||||
const { data } = await getReelCover({
|
|
||||||
...options,
|
|
||||||
...queryKey[0],
|
|
||||||
signal,
|
|
||||||
throwOnError: true
|
|
||||||
});
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
queryKey: getReelCoverQueryKey(options)
|
|
||||||
});
|
|
||||||
|
|
||||||
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
|
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// 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, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, 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
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
|
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
|
||||||
import { client } from './client.gen';
|
import { client } from './client.gen';
|
||||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetReelCoverData, GetReelCoverErrors, GetReelCoverResponses, GetReelVideoData, GetReelVideoErrors, GetReelVideoResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListBlockedData, ListBlockedErrors, ListBlockedResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListReelsData, ListReelsErrors, ListReelsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.gen';
|
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
|
||||||
|
|
||||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||||
/**
|
/**
|
||||||
@@ -161,11 +161,6 @@ export const refresh = <ThrowOnError extends boolean = true>(options: Options<Re
|
|||||||
*/
|
*/
|
||||||
export const logout = <ThrowOnError extends boolean = true>(options?: Options<LogoutData, ThrowOnError>): RequestResult<LogoutResponses, LogoutErrors, ThrowOnError> => (options?.client ?? client).post<LogoutResponses, LogoutErrors, ThrowOnError>({ url: '/v1/auth/logout', ...options });
|
export const logout = <ThrowOnError extends boolean = true>(options?: Options<LogoutData, ThrowOnError>): RequestResult<LogoutResponses, LogoutErrors, ThrowOnError> => (options?.client ?? client).post<LogoutResponses, LogoutErrors, ThrowOnError>({ url: '/v1/auth/logout', ...options });
|
||||||
|
|
||||||
/**
|
|
||||||
* 탈퇴 (계정과 남긴 댓글·좋아요를 모두 지운다)
|
|
||||||
*/
|
|
||||||
export const withdraw = <ThrowOnError extends boolean = true>(options?: Options<WithdrawData, ThrowOnError>): RequestResult<WithdrawResponses, WithdrawErrors, ThrowOnError> => (options?.client ?? client).delete<WithdrawResponses, WithdrawErrors, ThrowOnError>({ url: '/v1/auth/me', ...options });
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 내 정보
|
* 내 정보
|
||||||
*/
|
*/
|
||||||
@@ -183,11 +178,6 @@ export const updateMe = <ThrowOnError extends boolean = true>(options: Options<U
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* 이용약관 동의 (댓글 쓰기 전에 한 번)
|
|
||||||
*/
|
|
||||||
export const agreeTerms = <ThrowOnError extends boolean = true>(options?: Options<AgreeTermsData, ThrowOnError>): RequestResult<AgreeTermsResponses, AgreeTermsErrors, ThrowOnError> => (options?.client ?? client).post<AgreeTermsResponses, AgreeTermsErrors, ThrowOnError>({ url: '/v1/auth/terms', ...options });
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 좋아요 취소
|
* 좋아요 취소
|
||||||
*/
|
*/
|
||||||
@@ -219,7 +209,7 @@ export const listSaved = <ThrowOnError extends boolean = true>(options?: Options
|
|||||||
export const listComments = <ThrowOnError extends boolean = true>(options: Options<ListCommentsData, ThrowOnError>): RequestResult<ListCommentsResponses, ListCommentsErrors, ThrowOnError> => (options.client ?? client).get<ListCommentsResponses, ListCommentsErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/comment/list', ...options });
|
export const listComments = <ThrowOnError extends boolean = true>(options: Options<ListCommentsData, ThrowOnError>): RequestResult<ListCommentsResponses, ListCommentsErrors, ThrowOnError> => (options.client ?? client).get<ListCommentsResponses, ListCommentsErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/comment/list', ...options });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)
|
* 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)
|
||||||
*/
|
*/
|
||||||
export const addComment = <ThrowOnError extends boolean = true>(options: Options<AddCommentData, ThrowOnError>): RequestResult<AddCommentResponses, AddCommentErrors, ThrowOnError> => (options.client ?? client).post<AddCommentResponses, AddCommentErrors, ThrowOnError>({
|
export const addComment = <ThrowOnError extends boolean = true>(options: Options<AddCommentData, ThrowOnError>): RequestResult<AddCommentResponses, AddCommentErrors, ThrowOnError> => (options.client ?? client).post<AddCommentResponses, AddCommentErrors, ThrowOnError>({
|
||||||
url: '/v1/reaction/post/{post_id}/comment',
|
url: '/v1/reaction/post/{post_id}/comment',
|
||||||
@@ -245,33 +235,6 @@ export const unlikeComment = <ThrowOnError extends boolean = true>(options: Opti
|
|||||||
*/
|
*/
|
||||||
export const likeComment = <ThrowOnError extends boolean = true>(options: Options<LikeCommentData, ThrowOnError>): RequestResult<LikeCommentResponses, LikeCommentErrors, ThrowOnError> => (options.client ?? client).post<LikeCommentResponses, LikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
|
export const likeComment = <ThrowOnError extends boolean = true>(options: Options<LikeCommentData, ThrowOnError>): RequestResult<LikeCommentResponses, LikeCommentErrors, ThrowOnError> => (options.client ?? client).post<LikeCommentResponses, LikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
|
||||||
|
|
||||||
/**
|
|
||||||
* 남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)
|
|
||||||
*/
|
|
||||||
export const reportComment = <ThrowOnError extends boolean = true>(options: Options<ReportCommentData, ThrowOnError>): RequestResult<ReportCommentResponses, ReportCommentErrors, ThrowOnError> => (options.client ?? client).post<ReportCommentResponses, ReportCommentErrors, ThrowOnError>({
|
|
||||||
url: '/v1/reaction/comment/{comment_id}/report',
|
|
||||||
...options,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...options.headers
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임)
|
|
||||||
*/
|
|
||||||
export const blockAuthor = <ThrowOnError extends boolean = true>(options: Options<BlockAuthorData, ThrowOnError>): RequestResult<BlockAuthorResponses, BlockAuthorErrors, ThrowOnError> => (options.client ?? client).post<BlockAuthorResponses, BlockAuthorErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/block', ...options });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 내가 차단한 사람
|
|
||||||
*/
|
|
||||||
export const listBlocked = <ThrowOnError extends boolean = true>(options?: Options<ListBlockedData, ThrowOnError>): RequestResult<ListBlockedResponses, ListBlockedErrors, ThrowOnError> => (options?.client ?? client).get<ListBlockedResponses, ListBlockedErrors, ThrowOnError>({ url: '/v1/reaction/block/list', ...options });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 차단 풀기
|
|
||||||
*/
|
|
||||||
export const unblock = <ThrowOnError extends boolean = true>(options: Options<UnblockData, ThrowOnError>): RequestResult<UnblockResponses, UnblockErrors, ThrowOnError> => (options.client ?? client).delete<UnblockResponses, UnblockErrors, ThrowOnError>({ url: '/v1/reaction/block/{user_id}', ...options });
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 내 각 목록 (로그인하지 않았으면 빈 목록)
|
* 내 각 목록 (로그인하지 않았으면 빈 목록)
|
||||||
*/
|
*/
|
||||||
@@ -445,48 +408,11 @@ export const publishCard = <ThrowOnError extends boolean = true>(options: Option
|
|||||||
*/
|
*/
|
||||||
export const rejectCard = <ThrowOnError extends boolean = true>(options: Options<RejectCardData, ThrowOnError>): RequestResult<RejectCardResponses, RejectCardErrors, ThrowOnError> => (options.client ?? client).post<RejectCardResponses, RejectCardErrors, ThrowOnError>({ url: '/v1/card/{card_id}/reject', ...options });
|
export const rejectCard = <ThrowOnError extends boolean = true>(options: Options<RejectCardData, ThrowOnError>): RequestResult<RejectCardResponses, RejectCardErrors, ThrowOnError> => (options.client ?? client).post<RejectCardResponses, RejectCardErrors, ThrowOnError>({ url: '/v1/card/{card_id}/reject', ...options });
|
||||||
|
|
||||||
/**
|
|
||||||
* 카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만
|
|
||||||
*/
|
|
||||||
export const publishInstagram = <ThrowOnError extends boolean = true>(options: Options<PublishInstagramData, ThrowOnError>): RequestResult<PublishInstagramResponses, PublishInstagramErrors, ThrowOnError> => (options.client ?? client).post<PublishInstagramResponses, PublishInstagramErrors, ThrowOnError>({ url: '/v1/card/{card_id}/instagram', ...options });
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 카드뉴스 이미지
|
* 카드뉴스 이미지
|
||||||
*/
|
*/
|
||||||
export const getCardImage = <ThrowOnError extends boolean = true>(options: Options<GetCardImageData, ThrowOnError>): RequestResult<GetCardImageResponses, GetCardImageErrors, ThrowOnError> => (options.client ?? client).get<GetCardImageResponses, GetCardImageErrors, ThrowOnError>({ url: '/v1/card/{card_id}/{seq}.jpg', ...options });
|
export const getCardImage = <ThrowOnError extends boolean = true>(options: Options<GetCardImageData, ThrowOnError>): RequestResult<GetCardImageResponses, GetCardImageErrors, ThrowOnError> => (options.client ?? client).get<GetCardImageResponses, GetCardImageErrors, ThrowOnError>({ url: '/v1/card/{card_id}/{seq}.jpg', ...options });
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 목록 (관리자)
|
|
||||||
*/
|
|
||||||
export const listReels = <ThrowOnError extends boolean = true>(options?: Options<ListReelsData, ThrowOnError>): RequestResult<ListReelsResponses, ListReelsErrors, ThrowOnError> => (options?.client ?? client).get<ListReelsResponses, ListReelsErrors, ThrowOnError>({ url: '/v1/reel', ...options });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 mp4 저장 (관리자). 공개 주소가 생기고, 인스타엔 따로 올린다
|
|
||||||
*/
|
|
||||||
export const createReel = <ThrowOnError extends boolean = true>(options: Options<CreateReelData, ThrowOnError>): RequestResult<CreateReelResponses, CreateReelErrors, ThrowOnError> => (options.client ?? client).post<CreateReelResponses, CreateReelErrors, ThrowOnError>({
|
|
||||||
url: '/v1/reel',
|
|
||||||
...options,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...options.headers
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스를 인스타그램에 올리기 (관리자). 같은 릴스는 한 번만
|
|
||||||
*/
|
|
||||||
export const publishInstagram2 = <ThrowOnError extends boolean = true>(options: Options<PublishInstagram2Data, ThrowOnError>): RequestResult<PublishInstagram2Responses, PublishInstagram2Errors, ThrowOnError> => (options.client ?? client).post<PublishInstagram2Responses, PublishInstagram2Errors, ThrowOnError>({ url: '/v1/reel/{reel_id}/instagram', ...options });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 영상 (인스타가 받아 가는 공개 주소, Range 지원)
|
|
||||||
*/
|
|
||||||
export const getReelVideo = <ThrowOnError extends boolean = true>(options: Options<GetReelVideoData, ThrowOnError>): RequestResult<GetReelVideoResponses, GetReelVideoErrors, ThrowOnError> => (options.client ?? client).get<GetReelVideoResponses, GetReelVideoErrors, ThrowOnError>({ url: '/v1/reel/{reel_id}.mp4', ...options });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 릴스 표지
|
|
||||||
*/
|
|
||||||
export const getReelCover = <ThrowOnError extends boolean = true>(options: Options<GetReelCoverData, ThrowOnError>): RequestResult<GetReelCoverResponses, GetReelCoverErrors, ThrowOnError> => (options.client ?? client).get<GetReelCoverResponses, GetReelCoverErrors, ThrowOnError>({ url: '/v1/reel/{reel_id}/cover.jpg', ...options });
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 헬스체크
|
* 헬스체크
|
||||||
*/
|
*/
|
||||||
@@ -238,28 +238,6 @@ export type BestTime = {
|
|||||||
end?: string | null;
|
end?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* BlockedUser
|
|
||||||
*/
|
|
||||||
export type BlockedUser = {
|
|
||||||
/**
|
|
||||||
* User Id
|
|
||||||
*/
|
|
||||||
user_id: string;
|
|
||||||
/**
|
|
||||||
* Nickname
|
|
||||||
*/
|
|
||||||
nickname: string;
|
|
||||||
/**
|
|
||||||
* Character
|
|
||||||
*/
|
|
||||||
character: string;
|
|
||||||
/**
|
|
||||||
* Color
|
|
||||||
*/
|
|
||||||
color: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Body_upload_talk_image_v1_talk_image_post
|
* Body_upload_talk_image_v1_talk_image_post
|
||||||
*/
|
*/
|
||||||
@@ -307,10 +285,6 @@ export type CardItem = {
|
|||||||
* Image Urls
|
* Image Urls
|
||||||
*/
|
*/
|
||||||
image_urls?: Array<string>;
|
image_urls?: Array<string>;
|
||||||
/**
|
|
||||||
* Ig Media Id
|
|
||||||
*/
|
|
||||||
ig_media_id?: string | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1005,10 +979,6 @@ export type Me = {
|
|||||||
*/
|
*/
|
||||||
mood?: string | null;
|
mood?: string | null;
|
||||||
provider: AuthProvider;
|
provider: AuthProvider;
|
||||||
/**
|
|
||||||
* Terms Agreed
|
|
||||||
*/
|
|
||||||
terms_agreed?: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1515,36 +1485,6 @@ export type RankData = {
|
|||||||
situation_label?: string | null;
|
situation_label?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* ReelItem
|
|
||||||
*/
|
|
||||||
export type ReelItem = {
|
|
||||||
/**
|
|
||||||
* Reel Id
|
|
||||||
*/
|
|
||||||
reel_id: number;
|
|
||||||
/**
|
|
||||||
* Title
|
|
||||||
*/
|
|
||||||
title: string;
|
|
||||||
/**
|
|
||||||
* Created At
|
|
||||||
*/
|
|
||||||
created_at: string;
|
|
||||||
/**
|
|
||||||
* Video Url
|
|
||||||
*/
|
|
||||||
video_url: string;
|
|
||||||
/**
|
|
||||||
* Cover Url
|
|
||||||
*/
|
|
||||||
cover_url?: string | null;
|
|
||||||
/**
|
|
||||||
* Ig Media Id
|
|
||||||
*/
|
|
||||||
ig_media_id?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* RegionData
|
* RegionData
|
||||||
*/
|
*/
|
||||||
@@ -1571,33 +1511,6 @@ export type RegionData = {
|
|||||||
lon: number;
|
lon: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* ReportReason
|
|
||||||
*/
|
|
||||||
export const ReportReason = {
|
|
||||||
/**
|
|
||||||
* ABUSE
|
|
||||||
*/
|
|
||||||
ABUSE: 1,
|
|
||||||
/**
|
|
||||||
* AD
|
|
||||||
*/
|
|
||||||
AD: 2,
|
|
||||||
/**
|
|
||||||
* PRIVACY
|
|
||||||
*/
|
|
||||||
PRIVACY: 3,
|
|
||||||
/**
|
|
||||||
* OTHER
|
|
||||||
*/
|
|
||||||
OTHER: 4
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ReportReason
|
|
||||||
*/
|
|
||||||
export type ReportReason = typeof ReportReason[keyof typeof ReportReason];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Req_CardCreate
|
* Req_CardCreate
|
||||||
*/
|
*/
|
||||||
@@ -1620,12 +1533,6 @@ export type ReqCardCreate = {
|
|||||||
* Caption
|
* Caption
|
||||||
*/
|
*/
|
||||||
caption?: string;
|
caption?: string;
|
||||||
/**
|
|
||||||
* Hashtags
|
|
||||||
*
|
|
||||||
* 인스타 캡션 뒤에만 붙는 해시태그. 날씨각 피드에는 안 나간다
|
|
||||||
*/
|
|
||||||
hashtags?: string;
|
|
||||||
/**
|
/**
|
||||||
* Texts
|
* Texts
|
||||||
*
|
*
|
||||||
@@ -1717,40 +1624,6 @@ export type ReqMyGakScore = {
|
|||||||
rules: Array<MyGakRule>;
|
rules: Array<MyGakRule>;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Req_ReelCreate
|
|
||||||
*/
|
|
||||||
export type ReqReelCreate = {
|
|
||||||
/**
|
|
||||||
* Title
|
|
||||||
*
|
|
||||||
* 인스타 캡션 첫 줄
|
|
||||||
*/
|
|
||||||
title: string;
|
|
||||||
/**
|
|
||||||
* Caption
|
|
||||||
*/
|
|
||||||
caption?: string;
|
|
||||||
/**
|
|
||||||
* Hashtags
|
|
||||||
*
|
|
||||||
* 인스타 캡션 뒤에 붙는 해시태그
|
|
||||||
*/
|
|
||||||
hashtags?: string;
|
|
||||||
/**
|
|
||||||
* Video
|
|
||||||
*
|
|
||||||
* mp4(H.264, 9:16), base64, 30MB 이하
|
|
||||||
*/
|
|
||||||
video: string;
|
|
||||||
/**
|
|
||||||
* Cover
|
|
||||||
*
|
|
||||||
* 표지 JPEG, base64 (없으면 인스타가 첫 장면을 쓴다)
|
|
||||||
*/
|
|
||||||
cover?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Req_Refresh
|
* Req_Refresh
|
||||||
*/
|
*/
|
||||||
@@ -1761,13 +1634,6 @@ export type ReqRefresh = {
|
|||||||
refresh_token: string;
|
refresh_token: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Req_Report
|
|
||||||
*/
|
|
||||||
export type ReqReport = {
|
|
||||||
reason: ReportReason;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Req_Signup
|
* Req_Signup
|
||||||
*/
|
*/
|
||||||
@@ -1909,21 +1775,6 @@ export type ResAuthConfig = {
|
|||||||
google_client_id?: string | null;
|
google_client_id?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Res_BlockedList
|
|
||||||
*/
|
|
||||||
export type ResBlockedList = {
|
|
||||||
result?: ErrorInfo;
|
|
||||||
/**
|
|
||||||
* Msg
|
|
||||||
*/
|
|
||||||
msg?: string | null;
|
|
||||||
/**
|
|
||||||
* Users
|
|
||||||
*/
|
|
||||||
users?: Array<BlockedUser>;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Res_Card
|
* Res_Card
|
||||||
*/
|
*/
|
||||||
@@ -1946,10 +1797,6 @@ export type ResCard = {
|
|||||||
* Image Urls
|
* Image Urls
|
||||||
*/
|
*/
|
||||||
image_urls?: Array<string>;
|
image_urls?: Array<string>;
|
||||||
/**
|
|
||||||
* Ig Media Id
|
|
||||||
*/
|
|
||||||
ig_media_id?: string | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -2319,48 +2166,6 @@ export type ResPostSave = {
|
|||||||
saved?: boolean | null;
|
saved?: boolean | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Res_Reel
|
|
||||||
*/
|
|
||||||
export type ResReel = {
|
|
||||||
result?: ErrorInfo;
|
|
||||||
/**
|
|
||||||
* Msg
|
|
||||||
*/
|
|
||||||
msg?: string | null;
|
|
||||||
/**
|
|
||||||
* Reel Id
|
|
||||||
*/
|
|
||||||
reel_id?: number | null;
|
|
||||||
/**
|
|
||||||
* Video Url
|
|
||||||
*/
|
|
||||||
video_url?: string | null;
|
|
||||||
/**
|
|
||||||
* Cover Url
|
|
||||||
*/
|
|
||||||
cover_url?: string | null;
|
|
||||||
/**
|
|
||||||
* Ig Media Id
|
|
||||||
*/
|
|
||||||
ig_media_id?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Res_ReelList
|
|
||||||
*/
|
|
||||||
export type ResReelList = {
|
|
||||||
result?: ErrorInfo;
|
|
||||||
/**
|
|
||||||
* Msg
|
|
||||||
*/
|
|
||||||
msg?: string | null;
|
|
||||||
/**
|
|
||||||
* Items
|
|
||||||
*/
|
|
||||||
items?: Array<ReelItem>;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Res_Region
|
* Res_Region
|
||||||
*/
|
*/
|
||||||
@@ -2762,17 +2567,6 @@ export type ResWeekRanking = {
|
|||||||
days?: Array<WeekRankDay>;
|
days?: Array<WeekRankDay>;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Res_Withdraw
|
|
||||||
*/
|
|
||||||
export type ResWithdraw = {
|
|
||||||
result?: ErrorInfo;
|
|
||||||
/**
|
|
||||||
* Msg
|
|
||||||
*/
|
|
||||||
msg?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Row
|
* Row
|
||||||
*/
|
*/
|
||||||
@@ -4608,37 +4402,6 @@ export type LogoutResponses = {
|
|||||||
|
|
||||||
export type LogoutResponse = LogoutResponses[keyof LogoutResponses];
|
export type LogoutResponse = LogoutResponses[keyof LogoutResponses];
|
||||||
|
|
||||||
export type WithdrawData = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* Authorization
|
|
||||||
*/
|
|
||||||
authorization?: string | null;
|
|
||||||
};
|
|
||||||
path?: never;
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/auth/me';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WithdrawErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WithdrawError = WithdrawErrors[keyof WithdrawErrors];
|
|
||||||
|
|
||||||
export type WithdrawResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResWithdraw;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type WithdrawResponse = WithdrawResponses[keyof WithdrawResponses];
|
|
||||||
|
|
||||||
export type MeData = {
|
export type MeData = {
|
||||||
body?: never;
|
body?: never;
|
||||||
headers?: {
|
headers?: {
|
||||||
@@ -4701,37 +4464,6 @@ export type UpdateMeResponses = {
|
|||||||
|
|
||||||
export type UpdateMeResponse = UpdateMeResponses[keyof UpdateMeResponses];
|
export type UpdateMeResponse = UpdateMeResponses[keyof UpdateMeResponses];
|
||||||
|
|
||||||
export type AgreeTermsData = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* Authorization
|
|
||||||
*/
|
|
||||||
authorization?: string | null;
|
|
||||||
};
|
|
||||||
path?: never;
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/auth/terms';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type AgreeTermsErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type AgreeTermsError = AgreeTermsErrors[keyof AgreeTermsErrors];
|
|
||||||
|
|
||||||
export type AgreeTermsResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResMe;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type AgreeTermsResponse = AgreeTermsResponses[keyof AgreeTermsResponses];
|
|
||||||
|
|
||||||
export type UnlikePostData = {
|
export type UnlikePostData = {
|
||||||
body?: never;
|
body?: never;
|
||||||
headers?: {
|
headers?: {
|
||||||
@@ -5097,145 +4829,6 @@ export type LikeCommentResponses = {
|
|||||||
|
|
||||||
export type LikeCommentResponse = LikeCommentResponses[keyof LikeCommentResponses];
|
export type LikeCommentResponse = LikeCommentResponses[keyof LikeCommentResponses];
|
||||||
|
|
||||||
export type ReportCommentData = {
|
|
||||||
body: ReqReport;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* Authorization
|
|
||||||
*/
|
|
||||||
authorization?: string | null;
|
|
||||||
};
|
|
||||||
path: {
|
|
||||||
/**
|
|
||||||
* Comment Id
|
|
||||||
*/
|
|
||||||
comment_id: number;
|
|
||||||
};
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reaction/comment/{comment_id}/report';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ReportCommentErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ReportCommentError = ReportCommentErrors[keyof ReportCommentErrors];
|
|
||||||
|
|
||||||
export type ReportCommentResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResWebPacketProtocol;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ReportCommentResponse = ReportCommentResponses[keyof ReportCommentResponses];
|
|
||||||
|
|
||||||
export type BlockAuthorData = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* Authorization
|
|
||||||
*/
|
|
||||||
authorization?: string | null;
|
|
||||||
};
|
|
||||||
path: {
|
|
||||||
/**
|
|
||||||
* Comment Id
|
|
||||||
*/
|
|
||||||
comment_id: number;
|
|
||||||
};
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reaction/comment/{comment_id}/block';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BlockAuthorErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BlockAuthorError = BlockAuthorErrors[keyof BlockAuthorErrors];
|
|
||||||
|
|
||||||
export type BlockAuthorResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResWebPacketProtocol;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BlockAuthorResponse = BlockAuthorResponses[keyof BlockAuthorResponses];
|
|
||||||
|
|
||||||
export type ListBlockedData = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* Authorization
|
|
||||||
*/
|
|
||||||
authorization?: string | null;
|
|
||||||
};
|
|
||||||
path?: never;
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reaction/block/list';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListBlockedErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListBlockedError = ListBlockedErrors[keyof ListBlockedErrors];
|
|
||||||
|
|
||||||
export type ListBlockedResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResBlockedList;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListBlockedResponse = ListBlockedResponses[keyof ListBlockedResponses];
|
|
||||||
|
|
||||||
export type UnblockData = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* Authorization
|
|
||||||
*/
|
|
||||||
authorization?: string | null;
|
|
||||||
};
|
|
||||||
path: {
|
|
||||||
/**
|
|
||||||
* User Id
|
|
||||||
*/
|
|
||||||
user_id: string;
|
|
||||||
};
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reaction/block/{user_id}';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UnblockErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UnblockError = UnblockErrors[keyof UnblockErrors];
|
|
||||||
|
|
||||||
export type UnblockResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResWebPacketProtocol;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type UnblockResponse = UnblockResponses[keyof UnblockResponses];
|
|
||||||
|
|
||||||
export type ListMyGakData = {
|
export type ListMyGakData = {
|
||||||
body?: never;
|
body?: never;
|
||||||
headers?: {
|
headers?: {
|
||||||
@@ -6126,42 +5719,6 @@ export type RejectCardResponses = {
|
|||||||
|
|
||||||
export type RejectCardResponse = RejectCardResponses[keyof RejectCardResponses];
|
export type RejectCardResponse = RejectCardResponses[keyof RejectCardResponses];
|
||||||
|
|
||||||
export type PublishInstagramData = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* X-Admin-Key
|
|
||||||
*/
|
|
||||||
'x-admin-key'?: string | null;
|
|
||||||
};
|
|
||||||
path: {
|
|
||||||
/**
|
|
||||||
* Card Id
|
|
||||||
*/
|
|
||||||
card_id: number;
|
|
||||||
};
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/card/{card_id}/instagram';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PublishInstagramErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PublishInstagramError = PublishInstagramErrors[keyof PublishInstagramErrors];
|
|
||||||
|
|
||||||
export type PublishInstagramResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResCard;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PublishInstagramResponse = PublishInstagramResponses[keyof PublishInstagramResponses];
|
|
||||||
|
|
||||||
export type GetCardImageData = {
|
export type GetCardImageData = {
|
||||||
body?: never;
|
body?: never;
|
||||||
path: {
|
path: {
|
||||||
@@ -6198,177 +5755,6 @@ export type GetCardImageResponses = {
|
|||||||
200: unknown;
|
200: unknown;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ListReelsData = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* X-Admin-Key
|
|
||||||
*/
|
|
||||||
'x-admin-key'?: string | null;
|
|
||||||
};
|
|
||||||
path?: never;
|
|
||||||
query?: {
|
|
||||||
/**
|
|
||||||
* Limit
|
|
||||||
*/
|
|
||||||
limit?: number;
|
|
||||||
};
|
|
||||||
url: '/v1/reel';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListReelsErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListReelsError = ListReelsErrors[keyof ListReelsErrors];
|
|
||||||
|
|
||||||
export type ListReelsResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResReelList;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListReelsResponse = ListReelsResponses[keyof ListReelsResponses];
|
|
||||||
|
|
||||||
export type CreateReelData = {
|
|
||||||
body: ReqReelCreate;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* X-Admin-Key
|
|
||||||
*/
|
|
||||||
'x-admin-key'?: string | null;
|
|
||||||
};
|
|
||||||
path?: never;
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reel';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type CreateReelErrors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type CreateReelError = CreateReelErrors[keyof CreateReelErrors];
|
|
||||||
|
|
||||||
export type CreateReelResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResReel;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type CreateReelResponse = CreateReelResponses[keyof CreateReelResponses];
|
|
||||||
|
|
||||||
export type PublishInstagram2Data = {
|
|
||||||
body?: never;
|
|
||||||
headers?: {
|
|
||||||
/**
|
|
||||||
* X-Admin-Key
|
|
||||||
*/
|
|
||||||
'x-admin-key'?: string | null;
|
|
||||||
};
|
|
||||||
path: {
|
|
||||||
/**
|
|
||||||
* Reel Id
|
|
||||||
*/
|
|
||||||
reel_id: number;
|
|
||||||
};
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reel/{reel_id}/instagram';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PublishInstagram2Errors = {
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PublishInstagram2Error = PublishInstagram2Errors[keyof PublishInstagram2Errors];
|
|
||||||
|
|
||||||
export type PublishInstagram2Responses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: ResReel;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PublishInstagram2Response = PublishInstagram2Responses[keyof PublishInstagram2Responses];
|
|
||||||
|
|
||||||
export type GetReelVideoData = {
|
|
||||||
body?: never;
|
|
||||||
path: {
|
|
||||||
/**
|
|
||||||
* Reel Id
|
|
||||||
*/
|
|
||||||
reel_id: number;
|
|
||||||
};
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reel/{reel_id}.mp4';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type GetReelVideoErrors = {
|
|
||||||
/**
|
|
||||||
* Not Found
|
|
||||||
*/
|
|
||||||
404: unknown;
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type GetReelVideoError = GetReelVideoErrors[keyof GetReelVideoErrors];
|
|
||||||
|
|
||||||
export type GetReelVideoResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: unknown;
|
|
||||||
/**
|
|
||||||
* Partial Content
|
|
||||||
*/
|
|
||||||
206: unknown;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type GetReelCoverData = {
|
|
||||||
body?: never;
|
|
||||||
path: {
|
|
||||||
/**
|
|
||||||
* Reel Id
|
|
||||||
*/
|
|
||||||
reel_id: number;
|
|
||||||
};
|
|
||||||
query?: never;
|
|
||||||
url: '/v1/reel/{reel_id}/cover.jpg';
|
|
||||||
};
|
|
||||||
|
|
||||||
export type GetReelCoverErrors = {
|
|
||||||
/**
|
|
||||||
* Not Found
|
|
||||||
*/
|
|
||||||
404: unknown;
|
|
||||||
/**
|
|
||||||
* Validation Error
|
|
||||||
*/
|
|
||||||
422: HttpValidationError;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type GetReelCoverError = GetReelCoverErrors[keyof GetReelCoverErrors];
|
|
||||||
|
|
||||||
export type GetReelCoverResponses = {
|
|
||||||
/**
|
|
||||||
* Successful Response
|
|
||||||
*/
|
|
||||||
200: unknown;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type HealthzHealthzGetData = {
|
export type HealthzHealthzGetData = {
|
||||||
body?: never;
|
body?: never;
|
||||||
path?: never;
|
path?: never;
|
||||||
@@ -1,14 +1,72 @@
|
|||||||
import { configureApi } from '@nalssigak/shared/api/setup'
|
import { client } from './client/client.gen'
|
||||||
|
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
|
||||||
|
|
||||||
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
export const 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(/\/+$/, '')
|
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
|
||||||
|
|
||||||
// 사파리 프라이빗 모드 등에서는 localStorage 를 읽는 것만으로 에러가 나서 쓸 때마다 꺼낸다
|
type Refresh = 'ok' | 'rejected' | 'unreachable'
|
||||||
configureApi({
|
|
||||||
baseUrl: API_BASE_URL,
|
// 401이 한꺼번에 와도 갱신은 한 번만
|
||||||
storage: {
|
let refreshing: Promise<Refresh> | null = null
|
||||||
getItem: (key) => localStorage.getItem(key),
|
|
||||||
setItem: (key, value) => localStorage.setItem(key, value),
|
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
|
||||||
removeItem: (key) => localStorage.removeItem(key),
|
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
|
||||||
})
|
})
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||||
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
|
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
|
||||||
import { useIsFetching, useQuery } from '@tanstack/react-query'
|
import { useIsFetching, useQuery } from '@tanstack/react-query'
|
||||||
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
|
import { kindOfHour, kst, seasonOf, type TimeKind } from './lib'
|
||||||
import './b.css'
|
import './b.css'
|
||||||
import { AuthProvider } from './auth'
|
import { AuthProvider } from './auth'
|
||||||
import { RegionProvider } from './region'
|
import { RegionProvider } from './region'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen'
|
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { kst, loadOf, MEDALS, seasonOf } from '@nalssigak/shared/lib'
|
import { kst, loadOf, MEDALS, seasonOf } from './lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
|
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
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 '@nalssigak/shared/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 '../api/client/types.gen'
|
||||||
import { API_BASE_URL } from '../api/setup'
|
import { API_BASE_URL } from '../api/setup'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, clockShort } from '@nalssigak/shared/lib'
|
import { cardBg, clockShort, fall } from './lib'
|
||||||
import { fall } from './lib'
|
import type { SlideBg } from './types'
|
||||||
import type { SlideBg } from '@nalssigak/shared/lib/types'
|
import { deg } from './weatherText'
|
||||||
import { deg } from '@nalssigak/shared/lib/weatherText'
|
|
||||||
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||||
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
|
||||||
import { usePinnedLike, type PinnedKey } from './pinnedLike'
|
import { usePinnedLike, type PinnedKey } from './pinnedLike'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen'
|
import { ArticleCategory } from '../api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
|
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
||||||
import { ARTICLE_CAT, fall } from './lib'
|
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
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 { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||||
import regionPages from '../../seo/region.json'
|
import regionPages from '../../seo/region.json'
|
||||||
import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
import { setTokens, subscribeAuth } from '../api/auth'
|
||||||
import { SITE_URL } from '../api/setup'
|
import { SITE_URL } from '../api/setup'
|
||||||
import {
|
import {
|
||||||
addCommentMutation,
|
addCommentMutation,
|
||||||
agreeTermsMutation,
|
|
||||||
blockAuthorMutation,
|
|
||||||
deleteCommentMutation,
|
deleteCommentMutation,
|
||||||
getArticleOptions,
|
getArticleOptions,
|
||||||
getFeedQueryKey,
|
getFeedQueryKey,
|
||||||
@@ -14,29 +12,23 @@ import {
|
|||||||
getSeasonWeekOptions,
|
getSeasonWeekOptions,
|
||||||
likeCommentMutation,
|
likeCommentMutation,
|
||||||
listCommentsInfiniteOptions,
|
listCommentsInfiniteOptions,
|
||||||
listBlockedOptions,
|
|
||||||
listBlockedQueryKey,
|
|
||||||
listCommentsInfiniteQueryKey,
|
listCommentsInfiniteQueryKey,
|
||||||
listRegionsOptions,
|
listRegionsOptions,
|
||||||
meQueryKey,
|
meQueryKey,
|
||||||
reportCommentMutation,
|
|
||||||
unblockMutation,
|
|
||||||
unlikeCommentMutation,
|
unlikeCommentMutation,
|
||||||
updateMeMutation,
|
updateMeMutation,
|
||||||
withdrawMutation,
|
} from '../api/client/@tanstack/react-query.gen'
|
||||||
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.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 { track } from '../lib/analytics'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { useAuth } from './authContext'
|
import { useAuth } from './authContext'
|
||||||
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
|
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
||||||
import { GoogleButton } from './googleLogin'
|
import { GoogleButton } from './googleLogin'
|
||||||
import { useInstall, useInstallable } from './install'
|
import { useInstall, useInstallable } from './install'
|
||||||
import { InstallSheet } from './installBanner'
|
import { InstallSheet } from './installBanner'
|
||||||
import { ARTICLE_CAT } from './lib'
|
import { WeatherWhySheet } from './weatherWhy'
|
||||||
import { MixSheet } from './myGak'
|
import { MixSheet } from './myGak'
|
||||||
import { ownPage, useRegion } from './regionContext'
|
import { ownPage, useRegion } from './regionContext'
|
||||||
import { WeatherWhySheet } from './weatherWhy'
|
|
||||||
import { useSky } from './skyContext'
|
import { useSky } from './skyContext'
|
||||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||||
@@ -636,88 +628,8 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
|||||||
/* ---------- 댓글 ---------- */
|
/* ---------- 댓글 ---------- */
|
||||||
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
|
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
|
||||||
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
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 { region } = useRegion()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [liked, setLiked] = useState(c.liked)
|
const [liked, setLiked] = useState(c.liked)
|
||||||
@@ -799,7 +711,6 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
|
|||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
|
|
||||||
</small>
|
</small>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
|
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
|
||||||
@@ -819,21 +730,13 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|||||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||||||
})
|
})
|
||||||
const add = useMutation(addCommentMutation())
|
const add = useMutation(addCommentMutation())
|
||||||
const agree = useMutation(agreeTermsMutation())
|
|
||||||
const [addFailed, setAddFailed] = useState(false)
|
const [addFailed, setAddFailed] = useState(false)
|
||||||
const [askTerms, setAskTerms] = useState(false)
|
|
||||||
const [notice, setNotice] = useState('')
|
|
||||||
const [text, setText] = useState(draft ?? '')
|
const [text, setText] = useState(draft ?? '')
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||||||
|
|
||||||
useEffect(() => {
|
const submit = (e: FormEvent) => {
|
||||||
if (!notice) return
|
e.preventDefault()
|
||||||
const t = setTimeout(() => setNotice(''), 3000)
|
|
||||||
return () => clearTimeout(t)
|
|
||||||
}, [notice])
|
|
||||||
|
|
||||||
const send = () => {
|
|
||||||
const body = text.trim()
|
const body = text.trim()
|
||||||
if (!body || add.isPending) return
|
if (!body || add.isPending) return
|
||||||
setAddFailed(false)
|
setAddFailed(false)
|
||||||
@@ -841,7 +744,6 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|||||||
{ path: { post_id: postId }, body: { body, region: region.code } },
|
{ path: { post_id: postId }, body: { body, region: region.code } },
|
||||||
{
|
{
|
||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
|
|
||||||
setAddFailed(!res.result?.success)
|
setAddFailed(!res.result?.success)
|
||||||
if (!res.result?.success) return
|
if (!res.result?.success) return
|
||||||
setText('')
|
setText('')
|
||||||
@@ -853,35 +755,13 @@ 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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<Body>
|
<Body>
|
||||||
{comments.length ? (
|
{comments.length ? (
|
||||||
<>
|
<>
|
||||||
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
||||||
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />)}
|
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} />)}
|
||||||
{list.hasNextPage && (
|
{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">
|
<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 ? '불러오는 중…' : '댓글 더 보기'}
|
{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}
|
||||||
@@ -894,38 +774,24 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|||||||
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
|
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
|
||||||
)}
|
)}
|
||||||
</Body>
|
</Body>
|
||||||
{askTerms ? (
|
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
|
||||||
<div className="mx-3 flex flex-col gap-2 rounded-[16px] bg-[#f3f6fb] p-3" role="dialog" aria-label="이용약관 동의">
|
{EMOJIS.map((e) => (
|
||||||
<p className="m-0 text-[13px] font-bold text-(--ink)">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</p>
|
<button
|
||||||
<div className="flex gap-2">
|
key={e}
|
||||||
<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)">
|
type="button"
|
||||||
이용약관 보기
|
disabled={add.isPending}
|
||||||
</a>
|
className="cursor-pointer disabled:opacity-40"
|
||||||
<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">
|
onClick={() => {
|
||||||
동의하고 쓰기
|
setText((t) => (t + e).slice(0, 60))
|
||||||
</button>
|
inputRef.current?.focus()
|
||||||
</div>
|
}}
|
||||||
</div>
|
>
|
||||||
) : (
|
{e}
|
||||||
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
|
</button>
|
||||||
{EMOJIS.map((e) => (
|
))}
|
||||||
<button
|
</div>
|
||||||
key={e}
|
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
|
||||||
type="button"
|
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
|
||||||
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>
|
</p>
|
||||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
|
<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" />
|
<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" />
|
||||||
@@ -977,93 +843,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃·탈퇴 ---------- */
|
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
|
||||||
/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */
|
|
||||||
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 }) {
|
function MeSheet({ onDone }: { onDone: () => void }) {
|
||||||
const install = useInstall()
|
const install = useInstall()
|
||||||
const installable = useInstallable()
|
const installable = useInstallable()
|
||||||
@@ -1190,8 +970,6 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
|||||||
>
|
>
|
||||||
로그아웃
|
로그아웃
|
||||||
</button>
|
</button>
|
||||||
<Blocked />
|
|
||||||
<Withdraw onDone={onDone} />
|
|
||||||
</Body>
|
</Body>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useState, type ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen'
|
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { clockShort, loadOf } from '@nalssigak/shared/lib'
|
import { clockShort, loadOf } from './lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { MapLink, Sec, Skel, StateBox } from './ui'
|
import { MapLink, Sec, Skel, StateBox } from './ui'
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useSearchParams } from 'react-router'
|
import { useSearchParams } from 'react-router'
|
||||||
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
|
import type { TalkTopic } from '../api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { TalkCard } from './talk'
|
import { TalkCard } from './talk'
|
||||||
import { TOPICS, useTopicTalks } from './talkState'
|
import { TOPICS, useTopicTalks } from './talkState'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
|
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
|
||||||
import { Link, useLocation } from 'react-router'
|
import { Link, useLocation } from 'react-router'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import {
|
import {
|
||||||
PostType,
|
PostType,
|
||||||
RainType,
|
RainType,
|
||||||
@@ -15,10 +15,9 @@ import {
|
|||||||
type TalkData,
|
type TalkData,
|
||||||
type TopIndex,
|
type TopIndex,
|
||||||
type WeatherSlot,
|
type WeatherSlot,
|
||||||
} from '@nalssigak/shared/api/client/types.gen'
|
} from '../api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
|
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
|
||||||
import { fall } from './lib'
|
|
||||||
import { FoliageCard } from './foliageMap'
|
import { FoliageCard } from './foliageMap'
|
||||||
import { InstallBanner } from './installBanner'
|
import { InstallBanner } from './installBanner'
|
||||||
import { MyGakRow } from './myGak'
|
import { MyGakRow } from './myGak'
|
||||||
@@ -33,7 +32,7 @@ import { useSky } from './skyContext'
|
|||||||
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
|
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
|
||||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||||
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
|
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||||
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'
|
import { deg, slotAt } from './weatherText'
|
||||||
|
|
||||||
type Mode = 'now' | TimeKind
|
type Mode = 'now' | TimeKind
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useRef, useState, type ReactNode } from 'react'
|
import { useRef, useState, type ReactNode } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
|
import { cardBg, dateRange, loadOf, shortDay } from './lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
||||||
import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth'
|
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth'
|
||||||
import { meOptions, meQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { meOptions } from '../api/client/@tanstack/react-query.gen'
|
||||||
import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen'
|
import { logout as logoutOnServer } from '../api/client/sdk.gen'
|
||||||
import { AuthContext } from './authContext'
|
import { AuthContext } from './authContext'
|
||||||
|
|
||||||
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
||||||
@@ -18,16 +18,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
const me = useQuery({ ...meOptions(), enabled: !!token })
|
const me = useQuery({ ...meOptions(), enabled: !!token })
|
||||||
|
|
||||||
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
||||||
// 로그아웃·탈퇴 땐 내 정보 캐시를 먼저 버린다. 남겨 두면 다시 받다가 401 이 나서 로그인 창이 뜬다
|
useEffect(() => subscribeAuth((reason) => reason === 'change' && queryClient.invalidateQueries()), [queryClient])
|
||||||
useEffect(
|
|
||||||
() =>
|
|
||||||
subscribeAuth((reason) => {
|
|
||||||
if (reason !== 'change') return
|
|
||||||
if (!getAccessToken()) queryClient.removeQueries({ queryKey: meQueryKey() })
|
|
||||||
void queryClient.invalidateQueries()
|
|
||||||
}),
|
|
||||||
[queryClient],
|
|
||||||
)
|
|
||||||
|
|
||||||
const mePending = !!token && me.isPending
|
const mePending = !!token && me.isPending
|
||||||
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending])
|
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending])
|
||||||
|
|||||||