Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0689bdf46e | ||
|
|
271e625767 | ||
|
|
c1d62653a9 | ||
|
|
0db4b130f0 | ||
|
|
81dc101239 | ||
|
|
ba70fbcd49 | ||
|
|
e0a723a3e4 | ||
|
|
d716cf070b | ||
|
|
fa99ea4f08 | ||
|
|
9adee6762e | ||
|
|
b4d09574da | ||
|
|
ddcb4ee771 | ||
|
|
8ea8c9b368 | ||
|
|
b718955927 | ||
|
|
f9988855d3 | ||
|
|
a3271a827b | ||
|
|
872d68e738 | ||
|
|
90773081c2 | ||
|
|
e22564bc20 | ||
|
|
fb2e6c4fac | ||
|
|
512ae6b591 | ||
|
|
01263f4149 | ||
|
|
387929683c | ||
|
|
a875dfabe6 | ||
|
|
096d1effb0 | ||
|
|
928e9053cf | ||
|
|
e1b5efc01b | ||
|
|
a6251db762 | ||
|
|
814e64931d |
No files matched your search
@@ -1,16 +1,16 @@
|
||||
---
|
||||
description: 오늘 날씨 타로·코디 카드를 만들어 검수하고 킹서버에 승인 대기로 저장한다 (올리지는 않는다)
|
||||
argument-hint: <타로 주제> <코디 스타일: casual|semi|formal|street|minimal>
|
||||
description: 오늘 날씨 타로·코디 카드를 둘 다 만들어 검수하고 날씨각 피드와 인스타에 올린다 (/daily-tarot + /daily-ootd)
|
||||
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`, 값은 출력하지 않는다).
|
||||
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`.
|
||||
출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
|
||||
4. 코디: `{"style":"<스타일>","theme":"sky"}` 를 base64url 로 만들어 `npm run card -- ootd --copy <값> --post-wait`. 빠진 그림은 자동 생성된다(장당 1~5분).
|
||||
5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 옷 목록 줄의 옷이 그림에 전부 있고 추가 옷이 없는지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다.
|
||||
6. 새 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/ootd admin/src/assets/tarot-bg` 후 `feat: <날짜> 카드 그림(…)` 로 커밋한다 (Claude 서명 없이).
|
||||
7. 보고(한국어, 짧게): 킹서버 카드 번호 2개(승인 대기), 만든 JPEG 경로, 새 그림 수, 검수에서 고친 것, 남은 이슈. 올리는 건 사용자가 관리자 '만든 카드' 탭이나 "올려" 로 한다.
|
||||
4. 코디(그날 코디): `npm run card -- ootd --daily --style <스타일> --color sky --post-wait`. 무신사 인기 스냅 중 그 스타일 태그(꾸안꾸·오피스룩·캐주얼·스트릿·정장)가 붙은 것에서 사람 4명(20-30대·40대~ 여·남) 코디를 고르고, Claude 가 옷 목록을 뽑고, Codex 가 참고 사진대로 플랫레이 그림을 그린다(사람당 2~4분). 고른 스냅 주소와 옷 목록이 출력된다. "스냅이 없어요"·"저장하지 못했어요" 가 나오면 멈추고 보고한다.
|
||||
5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 그림 아래 옷 목록의 옷이 그림에 전부 있고 추가 옷이 없는지, 스냅 사진(`out/<날짜>/snaps/<사람>/snap.jpg`)과 옷·색이 같은지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다.
|
||||
6. 새 타로 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/tarot-bg` 후 `feat: <날짜> 각 카드 그림(…)` 로 커밋한다 (Claude 서명 없이). 코디 그림(`admin/public/daily`)은 커밋하지 않는다.
|
||||
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
|
||||
@@ -13,6 +13,11 @@ INSTAGRAM_USER_ID=
|
||||
# 인스타가 카드 이미지를 받아 갈 공개 주소
|
||||
PUBLIC_BASE_URL=https://weather.o2o.kr
|
||||
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
|
||||
# 오늘 화면 쇼츠 줄 (YouTube Data API v3 키, console.cloud.google.com/apis/credentials 에서 발급·YouTube Data API v3 만 허용).
|
||||
# 비우면 채널 쇼츠를 자동으로 못 받고 YOUTUBE_SHORTS(영상 ID, 쉼표로 구분, 최신순)만 보여 준다. 둘 다 비우면 기본값(영상 3개)
|
||||
YOUTUBE_API_KEY=
|
||||
YOUTUBE_CHANNEL_ID=UCWdesmwvHFsnjMUWNcDaA9w
|
||||
YOUTUBE_SHORTS=
|
||||
|
||||
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
|
||||
DB_HOST=localhost
|
||||
|
||||
@@ -4,9 +4,6 @@
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# npm workspaces 의존성 (frontend·mobile·shared 가 루트 하나를 같이 쓴다)
|
||||
node_modules/
|
||||
|
||||
# Python 바이트코드/캐시
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# 날씨각
|
||||
|
||||
날씨를 보면 오늘 할 일을 알려 주는 서비스. https://weather.o2o.kr
|
||||
|
||||
| 폴더 | 내용 | 문서 |
|
||||
|---|---|---|
|
||||
| `backend/` | FastAPI 백엔드 (날씨·각 점수·피드·카드 API) | `backend/docs/README.md` |
|
||||
| `frontend/` | React 서비스 화면 | `frontend/README.md` |
|
||||
| `admin/` | 관리자: 인스타 카드(날씨 타로·오늘의 코디) 제작 | `admin/AGENTS.md` |
|
||||
| `docs/` | 기획·설계·운영 문서 | 아래 |
|
||||
|
||||
## 인스타 카드 올리기
|
||||
|
||||
Claude Code에서 한 줄:
|
||||
|
||||
```
|
||||
/daily-tarot 건강 운동 ← 날씨 타로 5장
|
||||
/daily-ootd minimal ← 오늘의 코디 4장
|
||||
```
|
||||
|
||||
만들고 검수하고 날씨각 피드·인스타까지 올린 뒤 링크를 보고한다. 자세한 건 [docs/인스타_카드_사용법.md](docs/인스타_카드_사용법.md).
|
||||
|
||||
## 주요 문서
|
||||
|
||||
- [서비스 동작 안내](docs/서비스_동작_안내.md) — 날씨를 언제 받고 점수를 어떻게 매기나
|
||||
- [각 계산 기준](docs/각_계산기준.md) · [점수 계산식](docs/점수_계산식.md)
|
||||
- [피드 동작 방식](docs/피드_동작방식.md) · [콘텐츠 설계서](docs/콘텐츠_설계서.md)
|
||||
- [인스타 카드 사용법](docs/인스타_카드_사용법.md)
|
||||
- [TODO](TODO.md) — 결정 필요·미해결 항목
|
||||
- 회의록: `docs/meetings/`
|
||||
|
||||
## 배포
|
||||
|
||||
킹서버에서 `./deploy.sh` (init.sql 재실행, docker compose). 운영 `.env`는 서버에 따로 있다.
|
||||
@@ -59,6 +59,10 @@
|
||||
| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` |
|
||||
| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | |
|
||||
| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | |
|
||||
| [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` |
|
||||
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
|
||||
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
|
||||
| [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` |
|
||||
| [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | |
|
||||
| [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | |
|
||||
| [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | |
|
||||
@@ -268,52 +272,13 @@
|
||||
| [ ] | 인스타 릴스(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 검수 실패 | — |
|
||||
| [ ] | 소개 카드 최종본(`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` |
|
||||
| [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` |
|
||||
| [x] | 10/25 건강·운동 타로(킹서버 카드 7→포스트 3960, 인스타 https://www.instagram.com/p/De5iLg4AS_M/)·꾸안꾸 코디는 처음 올린 카드 8→포스트 3961(인스타 De58VfXINy0)이 40대~ 옷이 20-30대와 같아 숨기고, 40대~ 옷을 새로 써서 카드 9→포스트 3962(인스타 De5-8gboL-c)로 재게시했으나 40대 여자 그림에 롱가디건이 끼고 전체가 여름 옷으로 보여 다시 숨김. 일교차 8도 이상이면 겉옷을 5번째 옷으로 넣게 고쳐 카드 10→포스트 3963(인스타 De6B2gwIMXF)으로 올렸으나 그림 배치와 이름표 자리가 어긋나 숨김. 프롬프트에 옷 자리를 적고 다시 그려 카드 11→포스트 3964, 인스타 https://www.instagram.com/p/De6JRIkoKbT/ 로 최종 게시. 07:52 예약(세션 크론)이 세션 종료로 안 돌아 09:46 수동 실행. 코디는 사용자 결정으로 사람 구분을 20-30대·40대~ 4장으로 바꿈(f30·m30 그림 파일 8장은 남아 있으나 미사용). 새 그림 8장(러닝각·자전거각·warm 꾸안꾸 6) | 사용자 요청 (10/24) | `admin/image-prompts/ootd.json`, `admin/scripts/card.mjs` |
|
||||
|
||||
## 앱(React Native) 마이그레이션
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [x] | 1단계: 웹·앱 공통 코드 `shared/`(`@nalssigak/shared`) 분리, 루트 npm workspaces, 웹 Docker 빌드 대상을 루트로 | 앱과 API 클라이언트·로직 공유 | `package.json`, `shared/`, `frontend/Dockerfile`, `compose.yaml`, `.dockerignore` |
|
||||
| [x] | 2단계: 앱에 react-query·Uniwind 설정 + Metro가 `react`를 `mobile/node_modules`(19.2.3) 것만 쓰게 설정 — 루트에는 웹용 react 19.3.0이 있고 RN 렌더러는 19.2.3에서만 돌아감 | 앱 시작 준비 | `mobile/metro.config.js`, `mobile/src/app/_layout.tsx`, `mobile/src/lib/query-client.ts` |
|
||||
| [x] | 앱 토큰 저장소 `expo-secure-store`로 `configureApi` 연결, API 주소는 `EXPO_PUBLIC_API_BASE_URL` | 웹은 localStorage | `mobile/src/lib/api.ts`, `mobile/.env.example` |
|
||||
| [x] | 안드로이드 에뮬레이터(Expo Go)에서 확인: 오늘 화면 실데이터, 위치 권한 창, 탭 이동, 각 근거 시트 | | `mobile/` |
|
||||
| [x] | 안드로이드 개발 빌드에서 가입·로그인(아바타 표시)·좋아요·이미지 공유·위치로 지역 찾기 확인 | | `mobile/` |
|
||||
| [ ] | 안드로이드 댓글 쓰기·내 정보 바꾸기·로그아웃 확인 | 아직 안 눌러 봄 | `mobile/src/components/sheets/` |
|
||||
| [x] | 출시 빌드 설정: `eas.json`(production 은 운영 API·사이트 주소, 빌드 번호 자동 증가), iOS 수출 규정 암호화 없음, 안드로이드 권한은 대략 위치만(정밀 위치·저장소·다른 앱 위에 그리기 뺌) | | `mobile/eas.json`, `mobile/app.json` |
|
||||
| [ ] | 출시 빌드 전 준비(사용자): Apple Developer·Google Play Console·Expo 계정, 스토어 스크린샷·설명·데이터 안전 양식 | 서명·제출에 필요 | |
|
||||
| [x] | 회원 탈퇴(스토어 심사 필수): `DELETE /v1/auth/me` — 계정·댓글·좋아요·저장 모두 삭제, 게시물·댓글 수 맞춤. 웹·앱 내 정보 시트 '탈퇴하기'(한 번 더 확인) | Apple 5.1.1(v), Google Play 계정 삭제 정책 | `backend/crud/user_crud.py`, `backend/services/auth_service.py`, `frontend/src/b/Sheets.tsx`, `mobile/src/components/sheets/me.tsx` |
|
||||
| [ ] | 운영 배포 때 탈퇴 API 같이 나감 — 배포 전 웹 내 정보 시트 '탈퇴하기' 화면 확인 (앱은 안드로이드에서 확인, 웹은 빌드·린트만) | | `frontend/src/b/Sheets.tsx` |
|
||||
| [ ] | 백엔드 테스트 3개가 날짜 때문에 실패 (10/19): `test_feed`(제철 각 수 42≠40), `test_watch`, `test_weather_today`(10월 하순 18시가 일몰 뒤라 'sunset' 아이콘 아님) — 탈퇴 작업과 무관 | 기대값을 날짜에 안 묶이게 고쳐야 함 | `backend/tests/` |
|
||||
| [ ] | Xcode 설치 후 iOS 시뮬레이터에서 전체 확인 | | `mobile/` |
|
||||
| [x] | 안드로이드 개발 빌드(`expo run:android`) 설치 확인: 홈 화면 해 아이콘·'날씨각' 이름, 실데이터 화면 | | `mobile/` |
|
||||
| [x] | 앱 ID: 안드로이드 패키지 `kr.o2o.nalssigak` — Play Console 기존 '날씨각'(Wear OS 트랙에 워치 앱 있음)에 휴대전화 앱으로 추가하려면 패키지명이 같아야 함. iOS 번들 ID는 미정 | 스토어에 올리면 못 바꿈 | `mobile/app.json` |
|
||||
| [x] | Play 제출: 휴대전화 versionCode 1000부터 (10/23 `app.json` versionCode 1000, 로컬 빌드)(워치가 1 사용) — `eas login` 후 `eas build:version:set -p android` | 같은 앱 안에서 versionCode 겹치면 안 됨 | `mobile/eas.json` |
|
||||
| [x] | Play 제출: 워치 앱과 같은 업로드 키 (10/23 로컬 빌드로 서명 확인, SHA-1 D3:51…44:79. 비밀번호는 ~/.gradle/gradle.properties `NALSSIGAK_UPLOAD_*`)(.jks)를 `eas credentials -p android`로 등록 (사용자: 키 파일·비밀번호 준비, 분실 시 Play Console에서 업로드 키 재설정) | EAS는 안 넣으면 새 키를 만듦 | |
|
||||
| [ ] | 출시 aab 서명 설정이 생성 폴더 `mobile/android/app/build.gradle`에만 있음 — `expo prebuild --clean` 하면 지워지니 다시 넣거나 config plugin으로 옮기기 | `android/`는 gitignore·재생성 | `mobile/android/app/build.gradle` |
|
||||
| [ ] | 앱 구글 로그인 기기 확인: 네이티브 다시 빌드 → 구글 계정 로그인된 에뮬레이터(Play 서비스 이미지)에서 구글로 계속하기 | 새 네이티브 모듈이라 지금 설치된 개발 빌드엔 없음. Android 클라이언트(개발·Play SHA-1)는 콘솔에 등록됨 | `mobile/src/components/sheets/google.tsx` |
|
||||
| [ ] | 운영 서버 `.env`에 `GOOGLE_CLIENT_ID`(웹 클라이언트 ID) 넣고 구글 로그인 백엔드 배포 | 비어 있으면 `/v1/auth/config`가 ID를 안 줘서 앱·웹 구글 버튼이 숨음 | `backend/config/settings.py` |
|
||||
| [ ] | Play 제출(사용자): 휴대전화 스크린샷 2장+, 개인정보처리방침 URL, 계정 삭제 URL(웹 '탈퇴하기' 운영 배포 후), 데이터 보안 양식(대략 위치·계정 정보·댓글), 콘텐츠 등급, 앱 액세스용 심사 테스트 계정. 개인 계정(2023.11 이후)이면 비공개 테스트 12명·14일 | | |
|
||||
| [x] | Play UGC 정책(댓글): 처음 댓글 쓸 때 이용약관 동의(`POST /v1/auth/terms`), 남의 댓글 ⋯ → 신고(이유 4가지, 신고한 사람에겐 바로 숨김, 3건이면 모두에게 숨김) / 이 사람 차단, 내 정보 '차단한 사람'·풀기, 운영 조치 `scripts/moderate.py`(숨김·되살림·정지), 탈퇴 때 신고·차단도 삭제 | Play 'User Generated Content' 정책 | `backend/`, `frontend/src/b/Sheets.tsx`, `frontend/public/terms.html`, `mobile/src/components/sheets/` |
|
||||
| [ ] | 운영 DB 반영: `init.sql`의 `users.terms_agreed_at`, `comment.report_count`·`is_hidden`, `comment_report`, `user_block` (ALTER·CREATE IF NOT EXISTS) — 코드 배포 전에 먼저 | 새 코드가 이 칼럼을 읽음 | `backend/postgres-init/init.sql` |
|
||||
| [ ] | **[검토 필요]** 이용약관 초안 문구 검토 | 법무 문구라 확인 필요 | `frontend/public/terms.html` |
|
||||
| [ ] | 개인정보처리방침에 휴대전화 앱·댓글·신고·차단 기록 추가 (지금은 웹·워치 앱만 적혀 있음) | Play 데이터 보안 양식과 맞아야 함 | `frontend/public/privacy.html` |
|
||||
| [x] | 앱 신고·차단·약관 화면 안드로이드 확인: ⋯ 메뉴, 차단 확인·안내·목록에서 빠짐, 약관 동의 후 바로 게시, 내 정보 '차단한 사람' 풀기 (신고 흐름은 백엔드 테스트로만). 새 패키지 `kr.o2o.nalssigak` 개발 빌드로 다시 설치함 | | `mobile/` |
|
||||
| [ ] | 오늘 날씨 칸(3시·6시 등)이 '?' — 백엔드가 며칠 꺼져 있다 켜지면 최신 발표(예: 8시, 9시부터 예보)만 받아 새벽 칸 행이 없음. 0시 재수신(`_midnight_missing`)은 0시에 묵은 값이 있으면 안 돎. 운영은 늘 켜져 있어 드묾 — 고칠 땐 오늘 칸 중 비거나 묵은 칸이 있으면 다시 받기 | 10/19 로컬(9811)에서 확인, 앱·웹 버그 아님 | `backend/services/weather_service.py` (`today`, `ensure_vilage`, `_midnight_missing`) |
|
||||
| [x] | 앱 아이콘 3D 해 그림(600px 원본)으로: iOS 1024, 안드로이드 적응형(앞·뒤·단색), 스플래시. Expo Go 에선 안 보이고 개발 빌드부터 보임. 스토어용으로는 1024px 이상 원본이 있으면 더 선명 | | `mobile/assets/images/` |
|
||||
| [x] | 3단계-1: 탭 5개 구조·위 막대·하늘 배경·밤 테마(Uniwind dark), Today 히어로·각 순위·행사/TOP5/계절 띠 | | `mobile/src/app/`, `mobile/src/components/` |
|
||||
| [x] | Today 게시물 카드(슬라이드 7종·넘기기·좋아요·댓글·텍스트 공유), 3·6·9번째 글 뒤 띠 | | `mobile/src/components/post/`, `mobile/src/app/index.tsx` |
|
||||
| [x] | 시트 7종(각 근거·읽을거리·댓글·이번 주 특집·로그인/가입·내 정보·지역 고르기)을 RN `Modal`로, 위 막대 로그인/아바타 | 새 패키지 없이 | `mobile/src/components/sheets/`, `mobile/src/components/top-bar.tsx` |
|
||||
| [x] | 고른 지역 저장 (SecureStore) | | `mobile/src/lib/region.tsx` |
|
||||
| [x] | 위치로 지역 찾기(`expo-location`): 처음 켠 사람은 가장 가까운 구로, 지역 시트 '지금 위치로 찾기' | 웹과 같게 | `mobile/src/lib/region.tsx`, `mobile/src/components/sheets/region.tsx` |
|
||||
| [x] | 움직임: 해·구름 떨어지기/둥둥, 비·눈, 스켈레톤 깜빡임, 첫 로딩 덮개, 하늘색 서서히 바뀜, 밤 별 반짝임 ('동작 줄이기' 켜면 멈춤) | | `mobile/src/components/today/hero.tsx`, `first-load.tsx`, `sky-bg.tsx` |
|
||||
| [x] | 나머지 탭(각·노을·주말·행사·계절·상식) 옮기기 | | `mobile/src/app/`, `mobile/src/components/{gak,sky,week,season}/` |
|
||||
| [x] | 이미지로 공유(`react-native-view-shot` + `expo-sharing`): 게시물은 보고 있는 슬라이드, 주말은 고른 날 추천 카드 | 웹 스토리 이미지(머리말·주소 붙인 9:16)와는 다름 | `mobile/src/lib/share-image.ts` |
|
||||
| [x] | 웹과 다른 작은 것들 맞춤: 좋아요 튀는 하트·토스트, 밤 별똥별, 단풍잎 떨어짐, 시 구절 고운바탕, 실패·빈 안내 높이 유지(hold), 시트 배경은 제자리 페이드 | | `mobile/src/` |
|
||||
| [ ] | 공유 이미지를 웹처럼 9:16 스토리(머리말·사이트 주소)로 — 지금은 화면 그대로 찍음. 좋아요 효과는 카드 안에만 뜸(RN에 portal 없음) | 남은 차이 | `mobile/src/lib/share-image.ts`, `mobile/src/components/post/` |
|
||||
| [x] | `mobile/` 템플릿 예제 화면·`.vscode`·`LICENSE`·README 지움, `AGENTS.md`·`.claude`는 둠 | 사용자 결정 | `mobile/` |
|
||||
| [ ] | `frontend-dev` 개발 컨테이너 실제로 띄워 확인 (이미지 빌드만 확인, 5173이 사용 중이라 실행은 못 함) | 볼륨 경로 바뀜 | `compose.yaml` |
|
||||
| [ ] | 운영 서버가 git pull 뒤 루트 `package-lock.json`으로 빌드되는지 배포 때 확인 | 빌드 대상이 `./frontend` → `.` | `deploy.sh`, `compose.yaml` |
|
||||
@@ -25,3 +25,6 @@ dist-ssr
|
||||
|
||||
# npm run card 결과
|
||||
out
|
||||
|
||||
# 그날 코디 그림 (scripts/daily-ootd.mjs 가 만들고 카드가 /daily/... 로 읽는다)
|
||||
public/daily
|
||||
@@ -33,6 +33,10 @@ VITE_API_BASE_URL=http://localhost:9810 npm run dev # http://localhost:5175
|
||||
- **카드**: 날씨각 각 카드(`../backend/seed/index_definition.json`, 53장). 오늘 점수가 높은 각 중 질문과 엮이는 3장을 고르고, 각 카드로 질문을 리딩한다. 카드 그림은 그 각의 아이콘.
|
||||
- 대주제·소주제·아이콘을 늘리려면 `topics.json`만 고친다. 새 꾸밈 모양은 CSS와 `image-prompts/tarot.json`에 같이 더한다.
|
||||
|
||||
## 매일 올리기 (슬래시 명령)
|
||||
|
||||
사용자용 안내는 `docs/인스타_카드_사용법.md`. Claude Code에서 `/daily-tarot <주제>`, `/daily-ootd <스타일>`, `/daily-cards <주제> <스타일>` 을 치면 만들기 → 장마다 검수 → 킹서버 피드·인스타 게시 → 링크 보고까지 한 번에 한다. 명령 정의는 `.claude/commands/`.
|
||||
|
||||
## 대화로 만들 때 (Claude·Codex)
|
||||
|
||||
사용자가 "오늘 주식 날씨 타로 만들어 줘"처럼 말하면 아래 명령을 실행한다. 관리자 화면(`npm run dev`)이 켜져 있어야 한다.
|
||||
@@ -55,6 +59,25 @@ VITE_API_BASE_URL=http://localhost:9810 npm run card -- tarot --topic 주식 [--
|
||||
- 관리자 서버가 비밀값을 `/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`
|
||||
|
||||
## 그날 코디 (무신사 인기 스냅 → 옷 추출 → 참고 사진대로 그림)
|
||||
|
||||
코디 카드는 고정 데이터(`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 이미지 생성)
|
||||
|
||||
**그림은 그날 만드는 카드에 필요한 것만 그때 만든다.** 조합(기온 구간 × 스타일 × 사람, 타로 78장)을 미리 일괄로 만들지 않는다. Codex 사용량이 한정돼 있다.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post).
|
||||
// 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION)
|
||||
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'
|
||||
|
||||
const SLIDES = { tarot: 5, ootd: 4, intro: 8 }
|
||||
@@ -34,11 +34,14 @@ let copy = flag('--copy')
|
||||
const topic = flag('--topic')
|
||||
const feedback = flag('--feedback')
|
||||
const color = flag('--color')
|
||||
const styleArg = flag('--style')
|
||||
const outArg = flag('--out')
|
||||
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 postWait = take('--post-wait')
|
||||
// --daily: 코디를 고정 데이터 대신 그날 무신사 인기 스냅에서 뽑아 그린다 (scripts/daily-ootd.mjs)
|
||||
const daily = take('--daily')
|
||||
const [template] = args
|
||||
|
||||
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}`)
|
||||
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')
|
||||
// 타로: 오늘 고른 각을 적어 두면 다음 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}`)
|
||||
}
|
||||
|
||||
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, 한 장씩)
|
||||
if (!noImages) {
|
||||
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 })
|
||||
|
||||
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 에 넣는다.
|
||||
// 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force]
|
||||
// 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
|
||||
import { drawWithCodex } from './codex-image.mjs'
|
||||
|
||||
function fail(message) {
|
||||
console.error(message)
|
||||
@@ -77,33 +74,14 @@ for (const band of bands) {
|
||||
console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`)
|
||||
continue
|
||||
}
|
||||
const prompt = band.prompt
|
||||
const work = mkdtempSync(join(tmpdir(), `gen-${kind}-${band.id}-`))
|
||||
const task = [
|
||||
'내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
|
||||
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
|
||||
`통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.`,
|
||||
'',
|
||||
prompt,
|
||||
].join('\n')
|
||||
console.log(`${band.id}: Codex로 그리는 중…`)
|
||||
let result
|
||||
try {
|
||||
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다)
|
||||
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'] })
|
||||
result = drawWithCodex({ id: band.id, prompt: band.prompt, outPath: outPath(band.id) })
|
||||
} catch (e) {
|
||||
rmSync(work, { recursive: true, force: true })
|
||||
fail(`${band.id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
|
||||
fail(e.message)
|
||||
}
|
||||
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
|
||||
// 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤)
|
||||
if (!png) {
|
||||
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 (result !== 'ok') failed.push(band.id)
|
||||
}
|
||||
|
||||
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)에 넘겨 칸별 문구를 받는다.
|
||||
// 관리자 서버(/api/plan)와 npm run card --topic 이 같이 쓴다. API 키 없이 이 맥에 로그인된 Claude Code를 쓴다.
|
||||
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 { 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 }))
|
||||
// 최근에 쓴 각은 빼서 매일 같은 카드가 나오지 않게 한다 (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 RULES = [
|
||||
@@ -56,15 +69,25 @@ const TAROT_TONE = [
|
||||
'키워드(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 [
|
||||
'',
|
||||
'## 각 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)',
|
||||
questionOf(topic) ? `표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}` : '표지 질문(question)은 주제에 맞는 "오늘 ~할까요?" 꼴 질문 하나를 쓴다.',
|
||||
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 각(오늘 실제로 하기 좋은 각) 가운데 질문과 엮을 수 있는 것을 고른다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
|
||||
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 편(상위 15개 안)인 각 가운데 질문과 엮을 수 있는 것을 고른다. 매일 같은 야외 운동 각(산책·자전거·등산·드라이브)만 반복하지 말고 먹거리·계절·집·동네 각도 섞어 날마다 다른 카드가 나오게 한다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
|
||||
excluded.length ? `최근 7일에 쓴 각이라 오늘은 고를 수 없음(목록에서 뺐다): ${excluded.join(', ')}` : '',
|
||||
...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(', ')}`,
|
||||
feedback ? `## 피드백 (반드시 반영): ${feedback}` : '',
|
||||
'',
|
||||
...(isTarot(ctx) ? tarotSection(topic) : []),
|
||||
...(isTarot(ctx) ? tarotSection(topic, fixed) : []),
|
||||
fixed.question ? `## 질문은 관리자가 정했다(그대로 쓴다): ${fixed.question}` : '',
|
||||
fixed.cards?.length ? `## 카드는 관리자가 골랐다(card1·card2·card3 순서 그대로): ${fixed.cards.join(', ')}` : '',
|
||||
'모든 칸을 채운 JSON으로만 답한다. topic에는 쓴 주제를 짧게 적는다.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function schema(ctx) {
|
||||
function schema(ctx, fixed = {}) {
|
||||
const properties = { topic: { 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 }
|
||||
}
|
||||
|
||||
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
|
||||
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) => {
|
||||
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 로그인 상태를 확인하세요.`))
|
||||
|
||||
@@ -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;
|
||||
left: 80px;
|
||||
width: 920px;
|
||||
height: 800px;
|
||||
height: 760px;
|
||||
border-radius: 44px;
|
||||
overflow: hidden;
|
||||
background: var(--stage);
|
||||
@@ -141,7 +141,7 @@
|
||||
.ootd-stage > img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
object-fit: contain;
|
||||
}
|
||||
.ootd-labels {
|
||||
position: absolute;
|
||||
@@ -159,7 +159,7 @@
|
||||
/* 그림 아래 옷 목록: 그림 속 위치에 기대지 않고 따로 적는다 */
|
||||
.ootd-items {
|
||||
position: absolute;
|
||||
top: 1168px;
|
||||
top: 1126px;
|
||||
left: 80px;
|
||||
right: 80px;
|
||||
margin: 0;
|
||||
@@ -168,13 +168,14 @@
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
align-content: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
.ootd-items li {
|
||||
padding: 8px 18px;
|
||||
padding: 7px 16px;
|
||||
border-radius: 99px;
|
||||
background: #fff;
|
||||
font-size: 28px;
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 6px 16px #28304a1f;
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -3,7 +3,7 @@ import spec from '../../image-prompts/ootd.json'
|
||||
/** 낮 최고기온 구간 × 스타일 × 사람별 옷. 옷 목록·카드 글자는 image-prompts/ootd.json 한 곳에서 정한다.
|
||||
* 그림은 src/assets/ootd/<구간>-<사람>-<스타일>.webp 가 있으면 자동으로 붙는다 (npm run gen-image -- ootd <구간|스타일>).
|
||||
* 일교차가 크면(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 }
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
/** 그날 무신사 스냅에서 뽑은 코디 (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 면 겉옷 포함 그림·이름표 */
|
||||
export function ootdOutfits(maxC: number, style?: string, bandId?: string, withOuter = false): Outfit[] {
|
||||
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 { Frame, Lines } from './Frame'
|
||||
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'
|
||||
|
||||
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
|
||||
@@ -65,6 +65,7 @@ const ootd: Template = {
|
||||
hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상',
|
||||
}),
|
||||
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 id = `${ootdBand(d.maxC).id}`
|
||||
return missing.length
|
||||
@@ -72,11 +73,11 @@ const ootd: Template = {
|
||||
: []
|
||||
},
|
||||
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}>
|
||||
<p className="meta">{d.dateLabel} · 오늘의 코디</p>
|
||||
<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>
|
||||
<div className="ootd-stage">
|
||||
{o.image ? (
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { createReadStream, existsSync } from 'node:fs'
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import { basename, resolve } from 'node:path'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
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)
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi()],
|
||||
plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi(), dailyImages()],
|
||||
publicDir: '../frontend/public',
|
||||
server: { port: 5175, strictPort: true },
|
||||
})
|
||||
@@ -360,7 +360,6 @@ class User(Base):
|
||||
color: Mapped[str] = mapped_column(String(20), default="orange")
|
||||
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -401,29 +400,10 @@ class Comment(Base):
|
||||
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
body: Mapped[str] = mapped_column(String(60))
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class CommentReport(Base):
|
||||
__tablename__ = "comment_report"
|
||||
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
reason: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class UserBlock(Base):
|
||||
__tablename__ = "user_block"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class CommentLike(Base):
|
||||
__tablename__ = "comment_like"
|
||||
|
||||
@@ -492,3 +472,9 @@ class TalkReport(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class UserBlock(Base):
|
||||
__tablename__ = "user_block"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -25,7 +25,6 @@ class ErrorType(Enum):
|
||||
AUTH_FAILED = 4002
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
AUTH_TOKEN_INVALID = 4004
|
||||
TERMS_REQUIRED = 4005
|
||||
|
||||
|
||||
class Sky(CodeEnum):
|
||||
@@ -192,10 +191,3 @@ class CardStatus(CodeEnum):
|
||||
class AuthProvider(CodeEnum):
|
||||
LOCAL = 1
|
||||
GOOGLE = 2
|
||||
|
||||
|
||||
class ReportReason(CodeEnum):
|
||||
ABUSE = 1
|
||||
AD = 2
|
||||
PRIVACY = 3
|
||||
OTHER = 4
|
||||
@@ -51,6 +51,11 @@ class Settings(BaseSettings):
|
||||
azure_blob_base_url: str = ""
|
||||
azure_blob_sas_token: str = ""
|
||||
|
||||
# 오늘 화면 쇼츠 줄. API 키가 있으면 채널의 쇼츠를 받고, 없으면 youtube_shorts(영상 ID, 쉼표로 구분, 최신순)를 보여 준다
|
||||
youtube_api_key: str = ""
|
||||
youtube_channel_id: str = "UCWdesmwvHFsnjMUWNcDaA9w"
|
||||
youtube_shorts: str = "kpp6WFEi4Nk,Wdv-e_DdQFY,WmbOEhi91IM"
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
|
||||
@@ -2,15 +2,13 @@ import uuid
|
||||
from datetime import datetime
|
||||
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.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
|
||||
|
||||
HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다
|
||||
|
||||
|
||||
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
|
||||
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
|
||||
@@ -54,16 +52,9 @@ class ReactionCRUD:
|
||||
stmt = stmt.where(Post.post_id < cursor)
|
||||
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
|
||||
|
||||
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
|
||||
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다. 숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
|
||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(
|
||||
Comment.post_id == post_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)
|
||||
)
|
||||
if viewer is not None:
|
||||
stmt = stmt.where(
|
||||
Comment.comment_id.not_in(select(CommentReport.comment_id).where(CommentReport.user_id == viewer)),
|
||||
or_(Comment.user_id.is_(None), Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer))),
|
||||
)
|
||||
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
|
||||
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다."""
|
||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(Comment.comment_id > cursor)
|
||||
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
|
||||
@@ -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))
|
||||
res = await s.execute(
|
||||
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()
|
||||
if row is None:
|
||||
post_id = res.scalar()
|
||||
if post_id is None:
|
||||
return False
|
||||
# 숨긴 댓글은 이미 댓글 수에서 빠져 있다
|
||||
if not row.is_hidden:
|
||||
await s.execute(update(Post).where(Post.post_id == row.post_id).values(comment_count=Post.comment_count - 1))
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
||||
return True
|
||||
|
||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
|
||||
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), 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:
|
||||
return None
|
||||
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
|
||||
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
|
||||
|
||||
async def comment_author(self, s: AsyncSession, comment_id: int):
|
||||
"""지금 보이는 댓글이면 (comment_id, user_id) 행, 없으면 None. 로그인 없이 쓴 댓글은 user_id 가 None."""
|
||||
return (await s.execute(select(Comment.comment_id, Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))).first()
|
||||
|
||||
async def report_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, reason: int) -> None:
|
||||
"""같은 사람이 두 번 신고해도 한 번만 센다. HIDE_AT 건이 되면 숨기고 댓글 수에서 뺀다."""
|
||||
res = await s.execute(insert(CommentReport).values(comment_id=comment_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(CommentReport.comment_id))
|
||||
if res.first() is None:
|
||||
return
|
||||
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(report_count=Comment.report_count + 1))
|
||||
res = await s.execute(
|
||||
update(Comment).where(Comment.comment_id == comment_id, Comment.report_count >= HIDE_AT, Comment.is_hidden.is_(False), Comment.deleted.is_(False))
|
||||
.values(is_hidden=True).returning(Comment.post_id)
|
||||
)
|
||||
post_id = res.scalar()
|
||||
if post_id is not None:
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
||||
|
||||
async def set_hidden(self, s: AsyncSession, comment_id: int, hidden: bool) -> bool:
|
||||
"""운영자가 댓글을 숨기거나 되살린다. 실제로 바뀌었을 때만 댓글 수를 고친다."""
|
||||
res = await s.execute(
|
||||
update(Comment).where(Comment.comment_id == comment_id, Comment.is_hidden.is_(not hidden), Comment.deleted.is_(False))
|
||||
.values(is_hidden=hidden).returning(Comment.post_id)
|
||||
)
|
||||
post_id = res.scalar()
|
||||
if post_id is None:
|
||||
return False
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + (-1 if hidden else 1)))
|
||||
return True
|
||||
|
||||
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
|
||||
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
|
||||
|
||||
async def unblock(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> bool:
|
||||
res = await s.execute(delete(UserBlock).where(UserBlock.user_id == user_id, UserBlock.blocked_id == blocked_id).returning(UserBlock.blocked_id))
|
||||
return res.first() is not None
|
||||
|
||||
async def blocked(self, s: AsyncSession, user_id: uuid.UUID) -> list[User]:
|
||||
stmt = select(User).join(UserBlock, UserBlock.blocked_id == User.user_id).where(UserBlock.user_id == user_id).order_by(UserBlock.created_at.desc())
|
||||
return list((await s.scalars(stmt)).all())
|
||||
@@ -1,12 +1,11 @@
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy import select
|
||||
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:
|
||||
@@ -38,29 +37,3 @@ class UserCRUD:
|
||||
user.updated_at = datetime.now(timezone.utc)
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def agree_terms(self, s: AsyncSession, user_id: uuid.UUID) -> None:
|
||||
await s.execute(update(User).where(User.user_id == user_id, User.terms_agreed_at.is_(None)).values(terms_agreed_at=datetime.now(timezone.utc)))
|
||||
|
||||
async def withdraw(self, s: AsyncSession, user_id: uuid.UUID) -> None:
|
||||
"""계정과 그 사람이 남긴 좋아요·저장·댓글·신고·차단을 모두 지우고, 게시물·댓글에 쌓인 수를 그만큼 줄인다."""
|
||||
liked_posts = (await s.scalars(delete(PostLike).where(PostLike.user_id == user_id).returning(PostLike.post_id))).all()
|
||||
if liked_posts:
|
||||
await s.execute(update(Post).where(Post.post_id.in_(liked_posts)).values(like_count=Post.like_count - 1))
|
||||
liked_comments = (await s.scalars(delete(CommentLike).where(CommentLike.user_id == user_id).returning(CommentLike.comment_id))).all()
|
||||
if liked_comments:
|
||||
await s.execute(update(Comment).where(Comment.comment_id.in_(liked_comments)).values(like_count=Comment.like_count - 1))
|
||||
await s.execute(delete(PostSave).where(PostSave.user_id == user_id))
|
||||
reported = (await s.scalars(delete(CommentReport).where(CommentReport.user_id == user_id).returning(CommentReport.comment_id))).all()
|
||||
if reported:
|
||||
await s.execute(update(Comment).where(Comment.comment_id.in_(reported)).values(report_count=Comment.report_count - 1))
|
||||
await s.execute(delete(UserBlock).where((UserBlock.user_id == user_id) | (UserBlock.blocked_id == user_id)))
|
||||
mine = (await s.execute(delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.deleted, Comment.is_hidden))).all()
|
||||
if mine:
|
||||
ids = [c for c, _, _, _ in mine]
|
||||
await s.execute(delete(CommentLike).where(CommentLike.comment_id.in_(ids)))
|
||||
await s.execute(delete(CommentReport).where(CommentReport.comment_id.in_(ids)))
|
||||
# 이미 지웠거나 숨긴 댓글은 댓글 수에서 빠져 있다
|
||||
for post_id, n in Counter(p for _, p, deleted, hidden in mine if not deleted and not hidden).items():
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - n))
|
||||
await s.execute(delete(User).where(User.user_id == user_id))
|
||||
@@ -218,7 +218,6 @@ CREATE TABLE IF NOT EXISTS public.users (
|
||||
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
||||
mood VARCHAR(20) NULL, -- 오늘 기분: clear·partly·cloudy·rain·thunder·snow·fog·rainbow. NULL = 안 고름
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
||||
terms_agreed_at TIMESTAMPTZ NULL, -- 이용약관 동의 시각. NULL 이면 댓글을 못 쓴다
|
||||
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -266,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;
|
||||
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 IF NOT EXISTS is_hidden BOOLEAN NOT NULL DEFAULT FALSE; -- 신고 3건이면 숨김. 숨긴 댓글은 댓글 수에서 빠진다
|
||||
|
||||
-- 댓글 신고. 신고한 사람에게는 그 댓글이 바로 안 보인다
|
||||
CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
comment_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (comment_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_report_user ON public.comment_report (user_id);
|
||||
|
||||
-- 사용자 차단. 차단한 사람의 댓글·동네 이야기 글이 내게 안 보인다
|
||||
CREATE TABLE IF NOT EXISTS public.user_block (
|
||||
user_id UUID NOT NULL, -- 차단한 사람
|
||||
blocked_id UUID NOT NULL, -- 차단당한 사람
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, blocked_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_block_blocked ON public.user_block (blocked_id);
|
||||
-- 댓글 신고 (보류)
|
||||
-- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
|
||||
-- ALTER TABLE public.comment ADD COLUMN is_hidden BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
-- CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
-- comment_id BIGINT NOT NULL,
|
||||
-- user_id UUID NOT NULL,
|
||||
-- reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
-- PRIMARY KEY (comment_id, user_id)
|
||||
-- );
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||
comment_id BIGINT NOT NULL,
|
||||
@@ -355,6 +342,14 @@ CREATE TABLE IF NOT EXISTS public.talk_report (
|
||||
PRIMARY KEY (talk_id, user_id)
|
||||
);
|
||||
|
||||
-- 이 사람 글 안 보기
|
||||
CREATE TABLE IF NOT EXISTS public.user_block (
|
||||
user_id UUID NOT NULL,
|
||||
blocked_id UUID NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, blocked_id)
|
||||
);
|
||||
|
||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||
|
||||
-- 구 목록.
|
||||
|
||||
@@ -18,6 +18,7 @@ from router.v1.reaction.reaction import router as reaction_router
|
||||
from router.v1.region.region import router as region_router
|
||||
from router.v1.season.season import router as season_router
|
||||
from router.v1.seo.seo import router as seo_router
|
||||
from router.v1.shorts.shorts import router as shorts_router
|
||||
from router.v1.sky.sky import router as sky_router
|
||||
from router.v1.talk.talk import router as talk_router
|
||||
from router.v1.watch.watch import router as watch_router
|
||||
@@ -53,6 +54,7 @@ app.include_router(image_router)
|
||||
app.include_router(seo_router)
|
||||
app.include_router(card_router)
|
||||
app.include_router(reel_router)
|
||||
app.include_router(shorts_router)
|
||||
|
||||
|
||||
class Res_Health(Res_WebPacketProtocol):
|
||||
|
||||
@@ -5,14 +5,14 @@ from common.database.model.models import User
|
||||
from common.enums import AuthProvider, ErrorType
|
||||
from common.models.errors import error_info
|
||||
from config.settings import settings
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_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
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _me(u: User) -> Me:
|
||||
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider), 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:
|
||||
@@ -68,17 +68,3 @@ async def update_me(req: Req_UpdateMe, user: User = Depends(current_user), servi
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Me(result=error_info(err))
|
||||
return Res_Me(me=_me(updated))
|
||||
|
||||
|
||||
@router.post("/terms", response_model=Res_Me, response_model_exclude_none=True, summary="이용약관 동의 (댓글 쓰기 전에 한 번)")
|
||||
async def agree_terms(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Me:
|
||||
err, updated = await service.agree_terms(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Me(result=error_info(err))
|
||||
return Res_Me(me=_me(updated))
|
||||
|
||||
|
||||
@router.delete("/me", response_model=Res_Withdraw, response_model_exclude_none=True, summary="탈퇴 (계정과 남긴 댓글·좋아요를 모두 지운다)")
|
||||
async def withdraw(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Withdraw:
|
||||
err = await service.withdraw(user)
|
||||
return Res_Withdraw() if err is ErrorType.SUCCESS else Res_Withdraw(result=error_info(err))
|
||||
@@ -39,7 +39,6 @@ class Me(WebPacketProtocol):
|
||||
color: str
|
||||
mood: Optional[str] = None
|
||||
provider: AuthProvider
|
||||
terms_agreed: bool = False
|
||||
|
||||
|
||||
class Res_Auth(Res_WebPacketProtocol):
|
||||
@@ -52,10 +51,6 @@ class Res_Logout(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_Withdraw(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_Me(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -59,18 +58,3 @@ class Res_Comment(Res_WebPacketProtocol):
|
||||
class Res_CommentLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
|
||||
|
||||
class Req_Report(Req_WebPacketProtocol):
|
||||
reason: ReportReason
|
||||
|
||||
|
||||
class BlockedUser(WebPacketProtocol):
|
||||
user_id: uuid.UUID
|
||||
nickname: str
|
||||
character: str
|
||||
color: str
|
||||
|
||||
|
||||
class Res_BlockedList(Res_WebPacketProtocol):
|
||||
users: list[BlockedUser] = []
|
||||
@@ -1,4 +1,3 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
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.utils.kma_time import KST
|
||||
from router.v1.reaction.protocol import (
|
||||
BlockedUser, CommentData, Req_Comment, Req_Report, Res_BlockedList, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave,
|
||||
Res_SavedList, SavedPost,
|
||||
CommentData, Req_Comment, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave, Res_SavedList, SavedPost,
|
||||
)
|
||||
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)
|
||||
|
||||
|
||||
@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(
|
||||
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
|
||||
) -> 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="댓글 좋아요 취소")
|
||||
async def unlike_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, who, False, service)
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)")
|
||||
async def report_comment(comment_id: int = Path(...), req: Req_Report = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.report_comment(comment_id, user, req.reason)))
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임)")
|
||||
async def block_author(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.block_author(comment_id, user)))
|
||||
|
||||
|
||||
@router.get("/block/list", response_model=Res_BlockedList, response_model_exclude_none=True, summary="내가 차단한 사람")
|
||||
async def list_blocked(user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_BlockedList:
|
||||
err, users = await service.blocked(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_BlockedList(result=error_info(err))
|
||||
return Res_BlockedList(users=[BlockedUser(user_id=u.user_id, nickname=u.nickname, character=u.character, color=u.color) for u in users])
|
||||
|
||||
|
||||
@router.delete("/block/{user_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="차단 풀기")
|
||||
async def unblock(user_id: uuid.UUID = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.unblock(user, user_id)))
|
||||
@@ -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}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
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)")
|
||||
@@ -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}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
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/... 를 넘김)")
|
||||
@@ -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}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
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="구로 나뉜 시의 구 내일 날씨 페이지")
|
||||
@@ -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}")
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return HTMLResponse("not found", status_code=404)
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
|
||||
@@ -0,0 +1,10 @@
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class ShortItem(WebPacketProtocol):
|
||||
id: str # 유튜브 영상 ID
|
||||
title: str
|
||||
|
||||
|
||||
class Res_ShortList(Res_WebPacketProtocol):
|
||||
items: list[ShortItem] = []
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.enums import ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.shorts.protocol import Res_ShortList, ShortItem
|
||||
from services.shorts_service import ShortsService
|
||||
|
||||
router = APIRouter(prefix="/v1/shorts", tags=["shorts"])
|
||||
|
||||
|
||||
@router.get("", response_model=Res_ShortList, response_model_exclude_none=True, summary="오늘 화면 쇼츠 줄: 날씨각 유튜브 채널의 쇼츠, 최신순")
|
||||
async def list_shorts(service: ShortsService = Depends()) -> Res_ShortList:
|
||||
err, items = await service.items()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_ShortList(result=error_info(err))
|
||||
return Res_ShortList(items=[ShortItem(**i) for i in items])
|
||||
@@ -21,6 +21,7 @@ from services.external.culture_api import SIDO_NAME
|
||||
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
|
||||
from services.feed_service import build_feed_day, clear_feed_cache
|
||||
from services.shorts_service import ShortsService
|
||||
from services.week_service import collect_events, drop_known
|
||||
from services.weekend_rank import WeekendRank
|
||||
|
||||
@@ -188,3 +189,10 @@ async def refresh_events(only_if_missing: bool = False) -> ErrorType:
|
||||
LOG.error(f"[scheduler] refresh_events done mark: {e}")
|
||||
LOG.info(f"[scheduler] refresh_events: {detail}")
|
||||
return ErrorType.SUCCESS if ok else ErrorType.EXTERNAL_API_ERROR
|
||||
|
||||
|
||||
async def refresh_shorts() -> ErrorType:
|
||||
"""오늘 화면 쇼츠 줄 목록을 유튜브에서 새로 받아 둔다."""
|
||||
err, items = await ShortsService().refresh()
|
||||
LOG.info(f"[scheduler] refresh_shorts: {len(items)}개 {err.name}")
|
||||
return err
|
||||
@@ -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})])
|
||||
|
||||
async def agree_terms(self, user: User) -> tuple[ErrorType, Optional[User]]:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.agree_terms(s, user.user_id)])
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, user.user_id))
|
||||
|
||||
async def withdraw(self, user: User) -> ErrorType:
|
||||
"""탈퇴: 계정과 남긴 댓글·좋아요를 한 번에 지운다. 계정이 없어지니 가진 토큰도 바로 못 쓴다."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.withdraw(s, user.user_id)])
|
||||
|
||||
async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]:
|
||||
"""닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다."""
|
||||
values: dict = {}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
# YouTube Data API v3 (API 키). 채널 업로드 목록 → 영상 정보로 쇼츠만 고른다
|
||||
API_URL = "https://www.googleapis.com/youtube/v3"
|
||||
# 키 없이 영상 제목만 받을 때
|
||||
OEMBED_URL = "https://www.youtube.com/oembed"
|
||||
SHORT_MAX_SEC = 180 # 쇼츠는 3분 이하
|
||||
|
||||
_DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$")
|
||||
|
||||
|
||||
def seconds(iso: str) -> Optional[int]:
|
||||
"""ISO 8601 길이("PT1M5S") → 초. 형식이 다르면 None."""
|
||||
m = _DURATION.match(iso or "")
|
||||
if not m:
|
||||
return None
|
||||
h, mi, s = (int(g or 0) for g in m.groups())
|
||||
return h * 3600 + mi * 60 + s
|
||||
|
||||
|
||||
async def channel_shorts(client: httpx.AsyncClient, key: str, channel_id: str, limit: int) -> list[dict]:
|
||||
"""채널의 공개·퍼가기 허용 쇼츠 [{id, title, published}], 최신순."""
|
||||
res = await client.get(f"{API_URL}/channels", params={"part": "contentDetails", "id": channel_id, "key": key})
|
||||
res.raise_for_status()
|
||||
channels = res.json().get("items") or []
|
||||
if not channels:
|
||||
return []
|
||||
uploads = channels[0]["contentDetails"]["relatedPlaylists"]["uploads"]
|
||||
res = await client.get(f"{API_URL}/playlistItems", params={"part": "contentDetails", "playlistId": uploads, "maxResults": 50, "key": key})
|
||||
res.raise_for_status()
|
||||
ids = [i["contentDetails"]["videoId"] for i in res.json().get("items") or []]
|
||||
if not ids:
|
||||
return []
|
||||
res = await client.get(f"{API_URL}/videos", params={"part": "snippet,contentDetails,status", "id": ",".join(ids), "key": key})
|
||||
res.raise_for_status()
|
||||
found = []
|
||||
for v in res.json().get("items") or []:
|
||||
status, sec = v.get("status", {}), seconds(v["contentDetails"].get("duration", ""))
|
||||
if status.get("privacyStatus") != "public" or not status.get("embeddable") or sec is None or sec > SHORT_MAX_SEC:
|
||||
continue
|
||||
found.append({"id": v["id"], "title": v["snippet"]["title"], "published": v["snippet"]["publishedAt"]})
|
||||
found.sort(key=lambda x: x["published"], reverse=True)
|
||||
return found[:limit]
|
||||
|
||||
|
||||
async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str]:
|
||||
"""영상 제목. 없거나 퍼가기가 막힌 영상이면 None."""
|
||||
res = await client.get(OEMBED_URL, params={"url": f"https://www.youtube.com/shorts/{video_id}", "format": "json"})
|
||||
if res.status_code in (401, 403, 404):
|
||||
return None
|
||||
res.raise_for_status()
|
||||
return res.json().get("title")
|
||||
@@ -1,4 +1,3 @@
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
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.model.models import Comment, Post, User
|
||||
from common.enums import ErrorType, ReportReason
|
||||
from common.enums import ErrorType
|
||||
from common.liker import Liker
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
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)
|
||||
|
||||
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:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
@@ -110,8 +109,6 @@ class ReactionService:
|
||||
body = body.strip()
|
||||
if not body or len(body) > COMMENT_MAX:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if user is not None and user.terms_agreed_at is None:
|
||||
return ErrorType.TERMS_REQUIRED, None
|
||||
err = await self._post_exists(post_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
@@ -148,37 +145,3 @@ class ReactionService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
||||
|
||||
async def _others_comment(self, comment_id: int, user: User) -> tuple[ErrorType, Optional[uuid.UUID]]:
|
||||
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT, 로그인 없이 쓴 댓글이면 작성자는 None."""
|
||||
err, author = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comment_author(s, comment_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if author is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
return (ErrorType.INVALID_INPUT, None) if author.user_id == user.user_id else (ErrorType.SUCCESS, author.user_id)
|
||||
|
||||
async def report_comment(self, comment_id: int, user: User, reason: ReportReason) -> ErrorType:
|
||||
err, _ = await self._others_comment(comment_id, user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.report_comment(s, comment_id, user.user_id, reason.value)])
|
||||
|
||||
async def block_author(self, comment_id: int, user: User) -> ErrorType:
|
||||
err, author = await self._others_comment(comment_id, user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
# 로그인 없이 쓴 댓글은 차단할 사람이 없어 신고만 받는다
|
||||
if author is None:
|
||||
return ErrorType.INVALID_INPUT
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.block(s, user.user_id, author)])
|
||||
|
||||
async def unblock(self, user: User, blocked_id: uuid.UUID) -> ErrorType:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.unblock(s, user.user_id, blocked_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def blocked(self, user: User) -> tuple[ErrorType, list[User]]:
|
||||
err, users = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.blocked(s, user.user_id))
|
||||
return err, users or []
|
||||
@@ -0,0 +1,51 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
from services.external import youtube
|
||||
|
||||
CACHE_KEY = "shorts:list"
|
||||
# 워커가 하루 3번(07·12·18시 10분) 새로 받는다. 한 번 실패해도 다음 회차까지 이전 목록을 쓰게 넉넉히 둔다
|
||||
CACHE_SEC = 2 * 86400
|
||||
MAX_ITEMS = 10
|
||||
|
||||
|
||||
class ShortsService:
|
||||
async def items(self) -> tuple[ErrorType, list[dict]]:
|
||||
"""오늘 화면 쇼츠 줄 [{id, title}]. 워커가 받아 둔 목록을 읽고, 없을 때만(처음 켰을 때) 바로 받는다."""
|
||||
try:
|
||||
cached = await REDIS.conn.get(CACHE_KEY)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[shorts] cache get: {e}")
|
||||
cached = None
|
||||
if cached:
|
||||
return ErrorType.SUCCESS, json.loads(cached)
|
||||
return await self.refresh()
|
||||
|
||||
async def refresh(self) -> tuple[ErrorType, list[dict]]:
|
||||
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
items = await self._fetch(client)
|
||||
except (httpx.HTTPError, KeyError, ValueError) as e:
|
||||
LOG.error(f"[shorts] fetch: {e}")
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
try:
|
||||
await REDIS.conn.set(CACHE_KEY, json.dumps(items, ensure_ascii=False), ex=CACHE_SEC)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[shorts] cache set: {e}")
|
||||
return ErrorType.SUCCESS, items
|
||||
|
||||
async def _fetch(self, client: httpx.AsyncClient) -> list[dict]:
|
||||
if settings.youtube_api_key:
|
||||
found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS)
|
||||
return [{"id": v["id"], "title": v["title"]} for v in found]
|
||||
ids = [i.strip() for i in settings.youtube_shorts.split(",") if i.strip()][:MAX_ITEMS]
|
||||
titles = await asyncio.gather(*(youtube.video_title(client, i) for i in ids))
|
||||
return [{"id": i, "title": t} for i, t in zip(ids, titles) if t]
|
||||
@@ -43,7 +43,7 @@ def anyio_backend():
|
||||
|
||||
_VOLATILE = (
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "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:
|
||||
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']}"}
|
||||
await c.post("/v1/auth/terms", headers=h) # 로그인한 사람은 약관에 동의해야 댓글을 쓴다
|
||||
return h
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
@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"}
|
||||
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
||||
assert res["day"] == hero["tomorrow"]["day"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_can_be_reported_not_blocked(offline):
|
||||
"""로그인 없이 쓴 댓글도 신고는 되고(신고한 사람에겐 숨김), 차단할 사람이 없어 차단은 안 된다. 다른 사람을 차단해도 익명 댓글은 그대로 보인다."""
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/comment"
|
||||
listing = f"{url}/list"
|
||||
anon_id = (await c.post(url, headers=IP_A, json={"body": "익명 댓글"})).json()["comment"]["comment_id"]
|
||||
writer = await _login(c, "anon_mod_01")
|
||||
writer_id = (await c.post(url, headers=writer, json={"body": "회원 댓글"})).json()["comment"]["comment_id"]
|
||||
viewer = await _login(c, "anon_mod_02")
|
||||
|
||||
blocked = (await c.post(f"/v1/reaction/comment/{writer_id}/block", headers=viewer)).json()
|
||||
assert blocked["result"]["success"] is True
|
||||
ids = [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||
assert anon_id in ids and writer_id not in ids
|
||||
|
||||
assert (await c.post(f"/v1/reaction/comment/{anon_id}/block", headers=viewer)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(f"/v1/reaction/comment/{anon_id}/report", headers=viewer, json={"reason": 1})).json()["result"]["success"] is True
|
||||
assert anon_id not in [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||
assert anon_id in [x["comment_id"] for x in (await c.get(listing, headers=IP_B)).json()["comments"]]
|
||||
@@ -10,12 +10,8 @@ def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _signup(c, login_id="mina_01", nickname="망원동주민", agree=True):
|
||||
"""가입하고, 댓글을 쓸 수 있게 이용약관에도 동의한다 (agree=False 면 안 함)."""
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||
if agree and body.get("access_token"):
|
||||
await c.post("/v1/auth/terms", headers={"Authorization": f"Bearer {body['access_token']}"})
|
||||
return body
|
||||
async def _signup(c, login_id="mina_01", nickname="망원동주민"):
|
||||
return (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||
|
||||
|
||||
@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"
|
||||
again = (await c.post("/v1/auth/login", json={"login_id": "mina_out", "password": "password1"})).json()
|
||||
assert (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {again['access_token']}"})).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_withdraw_deletes_account_and_reactions(offline):
|
||||
async with client() as c:
|
||||
body = await _signup(c, login_id="mina_bye")
|
||||
h = {"Authorization": f"Bearer {body['access_token']}"}
|
||||
other = {"Authorization": f"Bearer {(await _signup(c, 'other_bye', '남는사람'))['access_token']}"}
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)
|
||||
await c.post(f"/v1/reaction/post/{post_id}/save", headers=h)
|
||||
mine = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "곧 떠나요"})).json()["comment"]
|
||||
kept = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=other, json={"body": "남아요"})).json()["comment"]
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/like", headers=h)
|
||||
await c.post(f"/v1/reaction/comment/{mine['comment_id']}/like", headers=other)
|
||||
|
||||
assert (await c.delete("/v1/auth/me")).status_code == 401
|
||||
assert (await c.delete("/v1/auth/me", headers=h)).json()["result"]["success"] is True
|
||||
|
||||
assert (await c.get("/v1/auth/me", headers=h)).status_code == 401
|
||||
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
|
||||
assert (await c.post("/v1/auth/login", json={"login_id": "mina_bye", "password": "password1"})).json()["result"]["desc"] == "AUTH_FAILED"
|
||||
comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"]
|
||||
assert [x["body"] for x in comments] == ["남아요"] and comments[0]["like_count"] == 0
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["like_count"] == 0 and p["comment_count"] == 1
|
||||
# 같은 아이디로 다시 가입할 수 있다
|
||||
assert (await _signup(c, login_id="mina_bye"))["result"]["success"] is True
|
||||
|
||||
|
||||
def _h(body):
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
async def _comment(c, post_id, h, text):
|
||||
return (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": text})).json()
|
||||
|
||||
|
||||
async def _bodies(c, post_id, h=None):
|
||||
return [x["body"] for x in (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=h or {})).json()["comments"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_comment_needs_terms_agreement(offline):
|
||||
async with client() as c:
|
||||
h = _h(await _signup(c, agree=False))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
assert (await c.get("/v1/auth/me", headers=h)).json()["me"]["terms_agreed"] is False
|
||||
assert (await _comment(c, post_id, h, "안녕"))["result"]["desc"] == "TERMS_REQUIRED"
|
||||
assert (await c.post("/v1/auth/terms", headers=h)).json()["me"]["terms_agreed"] is True
|
||||
assert (await _comment(c, post_id, h, "안녕"))["comment"]["body"] == "안녕"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_report_hides_for_reporter_then_for_all_at_three(offline):
|
||||
async with client() as c:
|
||||
writer = _h(await _signup(c, "writer_1", "쓴사람"))
|
||||
r = [_h(await _signup(c, f"reporter_{i}", f"신고자{i}")) for i in range(3)]
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
bad = (await _comment(c, post_id, writer, "광고입니다"))["comment"]
|
||||
url = f"/v1/reaction/comment/{bad['comment_id']}/report"
|
||||
|
||||
assert (await c.post(url, headers=writer, json={"reason": 2})).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 9})).status_code == 422
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True # 두 번 신고해도 한 번
|
||||
assert await _bodies(c, post_id, r[0]) == [] and await _bodies(c, post_id, r[1]) == ["광고입니다"]
|
||||
|
||||
await c.post(url, headers=r[1], json={"reason": 1})
|
||||
assert await _bodies(c, post_id) == ["광고입니다"]
|
||||
await c.post(url, headers=r[2], json={"reason": 1})
|
||||
assert await _bodies(c, post_id) == [] and await _bodies(c, post_id, writer) == []
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["comment_count"] == 0
|
||||
# 숨긴 댓글을 지워도 댓글 수가 한 번 더 줄지 않는다
|
||||
assert (await c.delete(f"/v1/reaction/comment/{bad['comment_id']}", headers=writer)).json()["result"]["success"] is True
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["comment_count"] == 0
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_block_hides_author_comments_and_can_be_undone(offline):
|
||||
async with client() as c:
|
||||
me = _h(await _signup(c))
|
||||
other = _h(await _signup(c, "rude_1", "무례한"))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
rude = (await _comment(c, post_id, other, "흥"))["comment"]
|
||||
mine = (await _comment(c, post_id, me, "좋아요"))["comment"]
|
||||
|
||||
assert (await c.post(f"/v1/reaction/comment/{mine['comment_id']}/block", headers=me)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block")).status_code == 401
|
||||
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block", headers=me)).json()["result"]["success"] is True
|
||||
assert await _bodies(c, post_id, me) == ["좋아요"] and await _bodies(c, post_id) == ["흥", "좋아요"]
|
||||
|
||||
blocked = (await c.get("/v1/reaction/block/list", headers=me)).json()["users"]
|
||||
assert [u["nickname"] for u in blocked] == ["무례한"]
|
||||
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["success"] is True
|
||||
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert await _bodies(c, post_id, me) == ["흥", "좋아요"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_withdraw_removes_reports_and_blocks(offline):
|
||||
async with client() as c:
|
||||
leaver = _h(await _signup(c, "leaver_1", "떠날사람"))
|
||||
stay = _h(await _signup(c, "stay_1", "남는사람"))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
kept = (await _comment(c, post_id, stay, "남아요"))["comment"]
|
||||
gone = (await _comment(c, post_id, leaver, "떠나요"))["comment"]
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/report", headers=leaver, json={"reason": 4})
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/block", headers=leaver)
|
||||
await c.post(f"/v1/reaction/comment/{gone['comment_id']}/block", headers=stay)
|
||||
assert (await c.delete("/v1/auth/me", headers=leaver)).json()["result"]["success"] is True
|
||||
assert (await c.get("/v1/reaction/block/list", headers=stay)).json()["users"] == []
|
||||
assert await _bodies(c, post_id, stay) == ["남아요"]
|
||||
@@ -84,7 +84,6 @@ async def test_like_in_one_sido_not_seen_in_another(offline):
|
||||
async with client() as c:
|
||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
await c.post("/v1/auth/terms", headers=h)
|
||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.enums import ErrorType
|
||||
from services import shorts_service
|
||||
from services.external.youtube import channel_shorts, seconds, video_title
|
||||
from services.shorts_service import CACHE_KEY, ShortsService
|
||||
|
||||
|
||||
def test_seconds_parses_iso_duration():
|
||||
assert seconds("PT45S") == 45
|
||||
assert seconds("PT1M5S") == 65
|
||||
assert seconds("PT1H") == 3600
|
||||
assert seconds("P1D") is None
|
||||
|
||||
|
||||
def _api(videos: list[dict]) -> httpx.MockTransport:
|
||||
def handle(req: httpx.Request) -> httpx.Response:
|
||||
if req.url.path.endswith("/channels"):
|
||||
return httpx.Response(200, json={"items": [{"contentDetails": {"relatedPlaylists": {"uploads": "UUtest"}}}]})
|
||||
if req.url.path.endswith("/playlistItems"):
|
||||
assert req.url.params["playlistId"] == "UUtest"
|
||||
return httpx.Response(200, json={"items": [{"contentDetails": {"videoId": v["id"]}} for v in videos]})
|
||||
return httpx.Response(200, json={"items": videos})
|
||||
return httpx.MockTransport(handle)
|
||||
|
||||
|
||||
def _video(vid: str, duration: str, published: str, embeddable: bool = True, privacy: str = "public") -> dict:
|
||||
return {"id": vid, "snippet": {"title": f"제목 {vid}", "publishedAt": published}, "contentDetails": {"duration": duration},
|
||||
"status": {"embeddable": embeddable, "privacyStatus": privacy}}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_channel_shorts_keeps_public_embeddable_short_videos_newest_first():
|
||||
videos = [
|
||||
_video("old", "PT30S", "2026-10-20T00:00:00Z"),
|
||||
_video("new", "PT58S", "2026-10-26T00:00:00Z"),
|
||||
_video("long", "PT10M", "2026-10-25T00:00:00Z"),
|
||||
_video("noembed", "PT20S", "2026-10-24T00:00:00Z", embeddable=False),
|
||||
_video("private", "PT20S", "2026-10-23T00:00:00Z", privacy="unlisted"),
|
||||
]
|
||||
async with httpx.AsyncClient(transport=_api(videos)) as client:
|
||||
found = await channel_shorts(client, "key", "UCtest", 10)
|
||||
assert [v["id"] for v in found] == ["new", "old"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_video_title_none_when_embedding_blocked():
|
||||
def handle(req: httpx.Request) -> httpx.Response:
|
||||
if "blocked" in req.url.params["url"]:
|
||||
return httpx.Response(401)
|
||||
return httpx.Response(200, content=json.dumps({"title": "오늘 자전거각"}))
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:
|
||||
assert await video_title(client, "ok") == "오늘 자전거각"
|
||||
assert await video_title(client, "blocked") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_fetch(self, client):
|
||||
calls.append(1)
|
||||
return [{"id": "abc", "title": "오늘 자전거각"}]
|
||||
|
||||
monkeypatch.setattr(shorts_service.ShortsService, "_fetch", fake_fetch)
|
||||
await REDIS.conn.delete(CACHE_KEY)
|
||||
assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}])
|
||||
assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}])
|
||||
assert len(calls) == 1
|
||||
@@ -5,7 +5,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.logger import LOG
|
||||
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_events, refresh_openmeteo_weather, refresh_weekend_rank
|
||||
from scheduler.jobs import build_today_feed, cleanup_old_rows, refresh_air_stations, refresh_events, refresh_openmeteo_weather, refresh_shorts, refresh_weekend_rank
|
||||
|
||||
|
||||
async def daily() -> None:
|
||||
@@ -24,8 +24,11 @@ async def main() -> None:
|
||||
scheduler.add_job(refresh_events, "cron", day_of_week="mon", hour=4, minute=0, max_instances=1, coalesce=True)
|
||||
scheduler.add_job(refresh_events, kwargs={"only_if_missing": True}, max_instances=1)
|
||||
scheduler.add_job(refresh_openmeteo_weather, "cron", hour="3,9,15,21", minute=10, max_instances=1, coalesce=True)
|
||||
# 오늘 화면 쇼츠 줄: 하루 1~2개 올라오니 하루 3번이면 충분하다. 켤 때도 한 번.
|
||||
scheduler.add_job(refresh_shorts, "cron", hour="7,12,18", minute=10, max_instances=1, coalesce=True)
|
||||
scheduler.add_job(refresh_shorts, max_instances=1)
|
||||
scheduler.start()
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST, openmeteo job at 03·09·15·21:10 KST")
|
||||
LOG.info("[worker] started, daily job at 03:00 KST, weekend rank at 06:40·18:40 KST, events on Mon 04:00 KST, openmeteo job at 03·09·15·21:10 KST, shorts at 07·12·18:10 KST")
|
||||
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
@@ -4,8 +4,7 @@ services:
|
||||
# 운영형: docker compose up --build → http://localhost:8080
|
||||
frontend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: frontend/Dockerfile
|
||||
context: ./frontend
|
||||
target: prod
|
||||
args:
|
||||
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
||||
@@ -20,16 +19,13 @@ services:
|
||||
frontend-dev:
|
||||
profiles: ["dev"]
|
||||
build:
|
||||
context: .
|
||||
dockerfile: frontend/Dockerfile
|
||||
context: ./frontend
|
||||
target: dev
|
||||
ports:
|
||||
- "5173:5173"
|
||||
volumes:
|
||||
- ./frontend:/app/frontend
|
||||
- ./shared:/app/shared
|
||||
- ./frontend:/app
|
||||
- /app/node_modules
|
||||
- /app/frontend/node_modules
|
||||
environment:
|
||||
- CHOKIDAR_USEPOLLING=true
|
||||
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# 인스타 카드 사용법 (날씨 타로 · 오늘의 코디)
|
||||
|
||||
Claude Code에서 명령 한 줄을 치면 카드를 만들고, 장마다 검수하고, 날씨각 피드와 인스타(@nalssigak)에 올린 뒤 링크를 보고한다. 중간에 묻지 않는다.
|
||||
|
||||
## 명령
|
||||
|
||||
저장소 폴더에서 Claude Code를 열고:
|
||||
|
||||
| 명령 | 만드는 것 | 뒤에 적는 것 |
|
||||
|---|---|---|
|
||||
| `/daily-tarot 건강 운동` | 날씨 타로 5장 | 타로 주제 "대주제 소주제". 비우면 Claude가 오늘 날씨에 맞는 주제를 고름 |
|
||||
| `/daily-ootd minimal` | 오늘의 코디 4장 | 스타일 하나. 비우면 minimal |
|
||||
| `/daily-cards 건강 운동 minimal` | 둘 다 | 타로 주제 + 마지막 단어가 코디 스타일 |
|
||||
|
||||
타로 주제 예: `연애 썸`, `연애 데이트`, `경제 주식`, `경제 재테크`, `건강 운동`, `일·공부`, `관계`. 목록(`admin/topics.json`)에 없는 말도 된다.
|
||||
|
||||
코디 스타일: `minimal`(꾸안꾸) · `casual`(캐주얼) · `semi`(세미정장·오피스) · `formal`(정장) · `street`(스트릿). 포스트 하나는 스타일 하나로, 네 사람(20-30대·40대~ 여·남) 모두 같은 스타일.
|
||||
|
||||
## 무엇이 일어나나
|
||||
|
||||
1. 관리자 서버(`http://localhost:5175`)가 켜져 있는지 확인하고, 꺼져 있으면 켠다.
|
||||
2. 오늘 서울(중구) 예보를 받는다.
|
||||
3. **타로**: Claude가 주제·예보로 문구를 기획하고 각 카드 3장을 고른다(최근 7일에 쓴 각은 제외). 그림이 없는 각은 Codex가 그린다(장당 1~5분, 가을 각 36장은 이미 있음). 문구의 수치·하늘 묘사를 예보와 대조해 틀리면 한 번 다시 기획한다.
|
||||
**코디**: 무신사 인기 스냅에서 오늘 기온 구간과 스타일 태그에 맞는 코디를 사람별로 하나씩 고른다(최근 14일에 쓴 스냅 제외). Claude가 사진·태그된 상품으로 옷 목록을 뽑고, Codex가 스냅 사진·상품 썸네일을 참고해 같은 옷·색으로 플랫레이 그림을 그린다(사람당 2~4분).
|
||||
4. 카드를 1080×1350 JPEG로 찍어 `admin/out/<날짜>/`에 둔다.
|
||||
5. **검수**: 장마다 원본 크기로 열어 글자 잘림·그림 누락·사람·글자·수치 오류를 본다. 틀리면 고쳐서 다시 만들고, 못 고치면 올리지 않고 보고한다.
|
||||
6. 킹서버 피드에 게시 → 인스타 캐러셀 게시 → 인스타 링크·카드/포스트 번호를 보고하고 `TODO.md`에 한 줄 적는다.
|
||||
|
||||
걸리는 시간: 타로 3~10분, 코디 10~15분.
|
||||
|
||||
## 조건
|
||||
|
||||
- 맥(윈도우는 아직 안 됨). Node, Chrome, `cwebp`.
|
||||
- 이 맥에 Claude CLI·Codex CLI가 로그인돼 있을 것(플랜 계정, API 키 없음). 그림은 `gpt-6-sol`로 고정.
|
||||
- 킹서버 관리자 키에 접근 가능할 것(`ssh King_admin`). 관리자 서버 켜는 법은 `admin/AGENTS.md` '켜기'.
|
||||
- 인스타 토큰은 킹서버 `.env`에 있고 60일마다 갱신(`TODO.md` 참고).
|
||||
|
||||
## 올린 뒤
|
||||
|
||||
- 인스타 글은 API로 지울 수 없다. 잘못 올라갔으면 앱에서 직접 지운다. 킹서버 쪽은 포스트를 숨길 수 있다.
|
||||
- 다시 올리고 싶으면 명령을 한 번 더 치면 새 카드가 만들어진다(이전 것은 그대로 남음).
|
||||
|
||||
## 터미널에서만 (Claude 없이)
|
||||
|
||||
승인 대기 저장까지만 한다. 올리는 건 관리자 화면 '만든 카드' 탭에서.
|
||||
|
||||
```bash
|
||||
cd admin
|
||||
VITE_API_BASE_URL=https://weather.o2o.kr npm run card -- tarot --topic "건강 운동" --color sky --post-wait
|
||||
VITE_API_BASE_URL=https://weather.o2o.kr npm run card -- ootd --daily --style minimal --color sky --post-wait
|
||||
```
|
||||
|
||||
## 어디에 있나
|
||||
|
||||
- 명령 정의: `.claude/commands/daily-tarot.md`, `daily-ootd.md`, `daily-cards.md` (git에 있어 `git pull`만 하면 팀원도 같은 명령이 보임. Claude Code는 시작할 때 읽으므로 받은 뒤 새로 열기)
|
||||
- 스크립트: `admin/scripts/card.mjs`(카드), `plan.mjs`(타로 기획), `daily-ootd.mjs`·`snap.mjs`·`outfit.mjs`(그날 코디), `codex-image.mjs`·`gen-image.mjs`(그림)
|
||||
- 각 카드 그림: `admin/src/assets/gak-card/` (36/68장). 코디 그림: `admin/public/daily/` (git에 안 넣음)
|
||||
- 만드는 규칙 전체: `admin/AGENTS.md`
|
||||
@@ -0,0 +1,7 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
*.log
|
||||
.DS_Store
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
@@ -2,19 +2,13 @@
|
||||
|
||||
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
|
||||
FROM node:24-alpine AS deps
|
||||
# 빌드 대상은 저장소 루트(npm workspaces). 웹에 필요한 frontend·shared 만 설치한다
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
COPY frontend/package.json frontend/
|
||||
COPY shared/package.json shared/
|
||||
COPY mobile/package.json mobile/
|
||||
RUN npm ci -w frontend -w shared
|
||||
RUN npm ci
|
||||
|
||||
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
|
||||
FROM deps AS dev
|
||||
COPY shared shared
|
||||
COPY frontend frontend
|
||||
WORKDIR /app/frontend
|
||||
COPY . .
|
||||
EXPOSE 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
|
||||
ARG VITE_SITE_URL=""
|
||||
ENV VITE_SITE_URL=$VITE_SITE_URL
|
||||
COPY shared shared
|
||||
COPY frontend frontend
|
||||
WORKDIR /app/frontend
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# ---- prod: nginx로 정적 파일 제공 ----
|
||||
FROM nginx:1.29-alpine AS prod
|
||||
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/frontend/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
|
||||
@@ -2,7 +2,7 @@ import { defineConfig } from '@hey-api/openapi-ts'
|
||||
|
||||
export default defineConfig({
|
||||
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
|
||||
output: '../shared/api/client',
|
||||
output: 'src/api/client',
|
||||
parser: {
|
||||
patch: {
|
||||
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
"api": "openapi-ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nalssigak/shared": "*",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/react-query": "^5.104.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>
|
||||
@@ -3,6 +3,7 @@ import { BLayout } from './b/BLayout'
|
||||
import { FoliagePage } from './b/FoliagePage'
|
||||
import { GakPage } from './b/GakPage'
|
||||
import { SeasonPage } from './b/SeasonPage'
|
||||
import { ShortsPage } from './b/Shorts'
|
||||
import { SkyPage } from './b/SkyPage'
|
||||
import { TalkPage } from './b/TalkPage'
|
||||
import { TodayPage } from './b/TodayPage'
|
||||
@@ -22,6 +23,7 @@ export default function App() {
|
||||
<Route path="season" element={<SeasonPage />} />
|
||||
<Route path="foliage" element={<FoliagePage />} />
|
||||
<Route path="talk" element={<TalkPage />} />
|
||||
<Route path="shorts/:id?" element={<ShortsPage />} />
|
||||
<Route path="*" element={<TodayPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
// 로그인 토큰 저장소: 플랫폼 저장소(웹 localStorage, 앱 SecureStore) + 메모리, 바뀌면 구독자에게 알린다
|
||||
// 로그인 토큰 저장소: localStorage + 메모리, 바뀌면 구독자에게 알린다
|
||||
const ACCESS_KEY = 'nalssigak.accessToken'
|
||||
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 {
|
||||
try {
|
||||
return storage?.getItem(key) ?? null
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
|
||||
return null
|
||||
@@ -21,21 +13,15 @@ function readStored(key: string): string | null {
|
||||
|
||||
function writeStored(key: string, value: string | null) {
|
||||
try {
|
||||
if (value) storage?.setItem(key, value)
|
||||
else storage?.removeItem(key)
|
||||
if (value) localStorage.setItem(key, value)
|
||||
else localStorage.removeItem(key)
|
||||
} catch {
|
||||
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let accessToken: string | null = null
|
||||
|
||||
/** 앱이 뜰 때 한 번: 저장된 토큰을 읽어 로그인 상태로 시작한다 */
|
||||
export function setTokenStorage(next: TokenStorage) {
|
||||
storage = next
|
||||
accessToken = readStored(ACCESS_KEY)
|
||||
}
|
||||
let accessToken = readStored(ACCESS_KEY)
|
||||
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 { 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 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 { addComment, addMyGak, addTalk, authConfig, 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, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, 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, AuthConfigData, AuthConfigResponse, 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, 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, ListShortsData, ListShortsResponse, 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, 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> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
@@ -448,23 +448,6 @@ export const logoutMutation = (options?: Partial<Options<LogoutData>>): UseMutat
|
||||
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);
|
||||
|
||||
/**
|
||||
@@ -500,23 +483,6 @@ export const updateMeMutation = (options?: Partial<Options<UpdateMeData>>): UseM
|
||||
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>> => {
|
||||
const mutationOptions: UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> = {
|
||||
@@ -778,75 +744,6 @@ export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>)
|
||||
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);
|
||||
|
||||
/**
|
||||
@@ -1485,6 +1382,24 @@ export const getReelCoverOptions = (options: Options<GetReelCoverData>) => query
|
||||
queryKey: getReelCoverQueryKey(options)
|
||||
});
|
||||
|
||||
export const listShortsQueryKey = (options?: Options<ListShortsData>) => createQueryKey('listShorts', options);
|
||||
|
||||
/**
|
||||
* 오늘 화면 쇼츠 줄: 날씨각 유튜브 채널의 쇼츠, 최신순
|
||||
*/
|
||||
export const listShortsOptions = (options?: Options<ListShortsData>) => queryOptions<ListShortsResponse, DefaultError, ListShortsResponse, ReturnType<typeof listShortsQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listShorts({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listShortsQueryKey(options)
|
||||
});
|
||||
|
||||
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
|
||||
|
||||
/**
|
||||