Compare commits

...
29 Commits
Author SHA1 Message Date
minaChoi 0689bdf46e fix: 좋아요·댓글·보내기 아이콘 크기가 달라 간격이 어긋나 보이던 것 — 하트는 10% 키우고 보내기는 5% 줄여 보이는 폭을 맞춤 2026-10-26 15:23:26 +09:00
minaChoi 271e625767 fix: 쇼츠 마우스 끌기 기준을 화면 15%에서 30px로 — 조금만 끌어도 넘어가게 2026-10-26 15:21:24 +09:00
minaChoi c1d62653a9 fix: 밤 화면에서 쇼츠 카드 그림·영상이 남색 판에 가려지던 문제 — 카드 아래 그라데이션에 b-keep-bg 2026-10-26 15:20:45 +09:00
minaChoi 0db4b130f0 feat: 쇼츠 페이지에서 마우스로 끌어 넘기기(한 화면 15% 넘게 끌면 다음·이전), 영상을 누르면 일시정지·재생 2026-10-26 15:18:45 +09:00
minaChoi 81dc101239 docs: TODO 에 쇼츠 업로드 직후 목록 갱신 항목 추가 2026-10-26 15:16:59 +09:00
minaChoi ba70fbcd49 feat: 쇼츠 목록을 요청 때가 아니라 워커가 하루 3번(07·12·18시 10분)과 켤 때 받아 둠, 캐시는 2일 — 사용자는 유튜브 응답을 기다리지 않음 2026-10-26 15:16:08 +09:00
minaChoi e0a723a3e4 docs: .env.example 에 유튜브 쇼츠 설정(YOUTUBE_API_KEY·CHANNEL_ID·SHORTS)과 설명 추가 2026-10-26 15:13:38 +09:00
minaChoi d716cf070b feat: 쇼츠 줄 제목 없앰 — 세로 카드만 히어로 아래에 2026-10-26 15:10:48 +09:00
minaChoi fa99ea4f08 feat: 쇼츠를 모달 대신 페이지(/shorts/영상ID)로 — 넘기면 주소도 바뀌어 공유·뒤로 가기 가능, 헤더·탭 바 사이를 채우고 배경은 지금 영상 표지를 흐리게 깔기 2026-10-26 15:08:18 +09:00
minaChoi 9adee6762e fix: 쇼츠 창을 처음 열 때 검은 플레이어가 깜빡이던 문제 — 첫 장면이 재생될 때까지 표지를 보이고 플레이어는 그 뒤에 서서히 띄움 2026-10-26 14:40:10 +09:00
minaChoi b4d09574da fix: 쇼츠 넘길 때 검은 화면·로딩이 잠깐 보이던 문제 — 앞뒤 영상을 소리 없이 틀어 첫 장면을 받아 둔 뒤 멈추고 처음으로, 유튜브 조작 막대는 숨기고 소리 켜기 버튼을 따로 둠 2026-10-26 14:34:29 +09:00
minaChoi ddcb4ee771 fix: 쇼츠 넘길 때마다 깜빡이던 문제 — 앞뒤 영상 플레이어를 미리 띄워 두고, 넘기면 새로 띄우지 않고 재생·일시정지만 바꿈 2026-10-26 14:31:17 +09:00
minaChoi 8ea8c9b368 fix: 쇼츠 전체 화면 창에서 영상이 화면보다 커져 확대·잘려 보이던 문제 — 남은 높이·너비 안에 9:16으로 맞추고, 영상이 뜨기 전엔 표지를 깔기 2026-10-26 14:23:51 +09:00
minaChoi b718955927 feat: 오늘 화면 히어로 아래 날씨각 유튜브 쇼츠 줄 — 첫 카드 소리 없이 자동재생, 누르면 전체 화면에서 위아래로 넘겨 보기. 목록은 /v1/shorts(API 키 있으면 채널 쇼츠, 없으면 설정한 영상 ID), 1시간 캐시 2026-10-26 14:17:36 +09:00
minaChoi f9988855d3 Merge remote-tracking branch 'origin/main' into sns 2026-10-26 13:51:37 +09:00
minaChoi a3271a827b docs: 인스타 카드 사용법(슬래시 명령·흐름·조건)과 루트 README 2026-10-26 13:51:37 +09:00
minaChoi 872d68e738 Merge remote-tracking branch 'origin/main' into fix/seo-no-store 2026-10-26 13:48:47 +09:00
minaChoi 90773081c2 fix: 지역 날씨 페이지(/today·/tomorrow)도 no-store — no-cache 면 모바일 크롬에서 다시 연 탭이 예전 HTML 로 지워진 빌드 파일을 불러 '날씨 불러오는 중'에서 멈춤 2026-10-26 13:47:34 +09:00
minaChoi e22564bc20 docs: 각 카드 그림 36장 기록 2026-10-26 13:47:32 +09:00
minaChoi fb2e6c4fac feat: 가을 각 카드 그림 28장 미리 생성(피크닉·캠핑·단풍·붕어빵·넷플릭스 등, gpt-6-sol) 2026-10-26 13:47:31 +09:00
minaChoi 512ae6b591 feat: 타로 각 카드 — 최근 7일에 쓴 각은 제외하고 상위 15개 안에서 먹거리·계절·집 각도 섞어 고르게(out/tarot-history.json) 2026-10-26 13:22:53 +09:00
minaChoi 01263f4149 docs: 타로 포스트 번호 2026-10-26 13:16:51 +09:00
minaChoi 387929683c docs: 10/26 몸 컨디션 타로 게시 기록 2026-10-26 13:16:19 +09:00
minaChoi a875dfabe6 fix: 슬래시 명령 argument-hint 따옴표(객체로 읽히던 것), 검수 통과 시 피드·인스타까지 바로 올리기 2026-10-26 11:46:12 +09:00
minaChoi 096d1effb0 docs: 10/26 세미정장 코디 게시 기록 2026-10-26 11:41:21 +09:00
minaChoi 928e9053cf feat: 최근 14일 안에 쓴 무신사 스냅은 다시 고르지 않음(out/snap-history.json) 2026-10-26 11:32:03 +09:00
minaChoi e1b5efc01b feat: /daily-ootd·/daily-tarot 슬래시 명령 분리 2026-10-26 11:12:41 +09:00
minaChoi a6251db762 feat: 그날 코디는 포스트 하나에 스타일 하나 — --style 로 스타일 태그(꾸안꾸·오피스룩…) 붙은 스냅만 고르고 제목 통일 2026-10-26 11:09:04 +09:00
minaChoi 814e64931d feat: 그날 코디 — 무신사 인기 스냅에서 사람별 코디 선정, Claude 옷 목록 추출, Codex 참고 사진 첨부 생성(npm run card -- ootd --daily), 카드 이름표 목록 2줄 허용 2026-10-26 10:40:21 +09:00
67 changed files with 1850 additions and 74 deletions

No files matched your search

+8 -8
View File
@@ -1,16 +1,16 @@
--- ---
description: 오늘 날씨 타로·코디 카드를 만들어 검수하고 킹서버에 승인 대기로 저장한다 (올리지는 않는다) description: 오늘 날씨 타로·코디 카드를 둘 다 만들어 검수하고 날씨각 피드와 인스타에 올린다 (/daily-tarot + /daily-ootd)
argument-hint: <타로 주제> <코디 스타일: casual|semi|formal|street|minimal> argument-hint: "<타로 주제> <코디 스타일> 예) 건강 운동 minimal"
--- ---
오늘 인스타 카드를 만든다. 인자: `$ARGUMENTS` (앞은 타로 주제, 마지막 단어는 코디 스타일. 비어 있으면 타로 주제는 비우고 코디는 casual). 오늘 인스타 카드를 만든다. 인자: `$ARGUMENTS` — 앞은 타로 주제(비어 있으면 Claude 가 오늘 날씨에 맞는 주제를 고른다), 마지막 단어가 casual·semi·formal·street·minimal 중 하나면 코디 스타일(없으면 minimal=꾸안꾸). 코디 포스트 하나는 스타일 하나: 네 사람 모두 같은 스타일.
재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. **인스타·날씨각 피드에 올리지 않는다** — 승인 대기 저장까지만. 재확인 질문 없이 순서대로 진행하고, 막히면 그 자리에서 보고하고 멈춘다. 타로는 `/daily-tarot` 의 순서대로, 코디는 `/daily-ootd` 의 순서대로 각각 만들고 검수한 뒤 올린다(두 명령 파일의 단계를 그대로 따른다).
1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다). 1. 관리자 서버: `curl -s http://localhost:5175/api/targets` 에 `king` 이 있어야 한다. 없으면 `admin/` 에서 백그라운드로 켠다 (`admin/AGENTS.md` '켜기', 킹서버 키는 `ssh King_admin` 의 `~/proj/o2o-weather/.env` `ADMIN_API_KEY`, 값은 출력하지 않는다).
2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다. 2. 예보: `curl -s "https://weather.o2o.kr/v1/weather/today?region=1114000000"` 의 `day` 가 오늘인지 보고 slots 의 기온·하늘·비 확률을 적어 둔다.
3. 타로: `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait`. 3. 타로: `cd admin && VITE_API_BASE_URL=https://weather.o2o.kr ADMIN_URL=http://localhost:5175 npm run card -- tarot --topic "<주제>" --color sky --post-wait`.
출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다. 출력된 기획 문구를 2의 예보와 대조한다(숫자·하늘 묘사가 틀리면 `--copy <값> --feedback "실제 수치…"` 로 한 번만 다시). "일부 그림을 못 만들어" 가 나오면 멈추고 보고한다. 크롬이 한 장에서 45초 넘게 멈추면 그 프로세스를 죽이고 그 장만 다시 찍는다.
4. 코디: `{"style":"<스타일>","theme":"sky"}` 를 base64url 로 만들어 `npm run card -- ootd --copy <값> --post-wait`. 빠진 그림은 자동 생성된다(장당 1~5분). 4. 코디(그날 코디): `npm run card -- ootd --daily --style <스타일> --color sky --post-wait`. 무신사 인기 스냅 중 그 스타일 태그(꾸안꾸·오피스룩·캐주얼·스트릿·정장)가 붙은 것에서 사람 4명(20-30대·40대~ 여·남) 코디를 고르고, Claude 가 옷 목록을 뽑고, Codex 가 참고 사진대로 플랫레이 그림을 그린다(사람당 2~4분). 고른 스냅 주소와 옷 목록이 출력된다. "스냅이 없어요"·"저장하지 못했어요" 가 나오면 멈추고 보고한다.
5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 옷 목록 줄의 옷이 그림에 전부 있고 추가 옷이 없는지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다. 5. 검수(예외 없음): 만든 JPEG 전부를 **한 장씩 원본 크기로** Read 로 연다. 축소 시트로 판단하지 않는다. 볼 것: 글자 잘림·겹침, 그림 누락, 그림 속 사람·얼굴·글자, 코디는 그림 아래 옷 목록의 옷이 그림에 전부 있고 추가 옷이 없는지, 스냅 사진(`out/<날짜>/snaps/<사람>/snap.jpg`)과 옷·색이 같은지, 날씨 줄 수치가 예보와 맞는지. 틀리면 고치고 다시 찍어 다시 본다.
6. 새 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/ootd admin/src/assets/tarot-bg` 후 `feat: <날짜> 카드 그림(…)` 로 커밋한다 (Claude 서명 없이). 6. 새 타로 그림이 생겼으면 `git add admin/src/assets/gak-card admin/src/assets/tarot-bg` 후 `feat: <날짜> 각 카드 그림(…)` 로 커밋한다 (Claude 서명 없이). 코디 그림(`admin/public/daily`)은 커밋하지 않는다.
7. 보고(한국어, 짧게): 킹서버 카드 번호 2개(승인 대기), 만든 JPEG 경로, 새 그림 수, 검수에서 고친 것, 남은 이슈. 올리는 건 사용자가 관리자 '만든 카드' 탭이나 "올려" 로 한다. 7. 보고(한국어, 짧게): 킹서버 카드 번호 2개(승인 대기), 만든 JPEG 경로, 참고한 스냅 주소 4개, 검수에서 고친 것, 남은 이슈. 올리는 건 사용자가 관리자 '만든 카드' 탭이나 "올려" 로 한다.
+15
View File
@@ -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개, 검수에서 고친 것, 남은 이슈.
+16
View File
@@ -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. 보고(한국어, 짧게): 인스타 링크, 킹서버 카드·포스트 번호, 새 그림 수, 검수에서 고친 것, 남은 이슈.
+5
View File
@@ -13,6 +13,11 @@ INSTAGRAM_USER_ID=
# 인스타가 카드 이미지를 받아 갈 공개 주소 # 인스타가 카드 이미지를 받아 갈 공개 주소
PUBLIC_BASE_URL=https://weather.o2o.kr PUBLIC_BASE_URL=https://weather.o2o.kr
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.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·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
DB_HOST=localhost DB_HOST=localhost
+34
View File
@@ -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`는 서버에 따로 있다.
+10 -1
View File
@@ -59,6 +59,10 @@
| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` | | [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` |
| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | | | [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | |
| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 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 회의 | | | [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | |
| [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | | | [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | |
| [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | | | [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | |
@@ -268,7 +272,12 @@
| [ ] | 인스타 릴스(20초, 2.5D: Codex 3D 렌더풍 배경 + 카메라 패럴랙스, 무료 BGM, API로 업로드) — 백엔드에 mp4 공개 주소 + REELS 게시 추가 필요 | 사용자 요청 (10/24) | `backend/services/external/instagram.py` | | [ ] | 인스타 릴스(20초, 2.5D: Codex 3D 렌더풍 배경 + 카메라 패럴랙스, 무료 BGM, API로 업로드) — 백엔드에 mp4 공개 주소 + REELS 게시 추가 필요 | 사용자 요청 (10/24) | `backend/services/external/instagram.py` |
| [ ] | 인스타에 올라간 불량 게시물 삭제(앱에서만 가능): 소개 카드 De3SUTtoDGR·De3ycbAIPVw(스샷 잘림)·De31G7VIBEc(7·8번 장 치우침), 릴스 18152745022535272(폰 잘림), 10/25 꾸안꾸 코디 De58VfXINy0(20-30대와 40대~ 옷이 같음)·De5-8gboL-c(40대 여자 롱가디건·여름 옷)·De6B2gwIMXF(이름표 자리 어긋남) — 킹서버 포스트 3961·3962·3963은 deleted=true로 숨김 | 10/24·10/25 검수 실패 | — | | [ ] | 인스타에 올라간 불량 게시물 삭제(앱에서만 가능): 소개 카드 De3SUTtoDGR·De3ycbAIPVw(스샷 잘림)·De31G7VIBEc(7·8번 장 치우침), 릴스 18152745022535272(폰 잘림), 10/25 꾸안꾸 코디 De58VfXINy0(20-30대와 40대~ 옷이 같음)·De5-8gboL-c(40대 여자 롱가디건·여름 옷)·De6B2gwIMXF(이름표 자리 어긋남) — 킹서버 포스트 3961·3962·3963은 deleted=true로 숨김 | 10/24·10/25 검수 실패 | — |
| [ ] | 소개 카드 최종본(`admin/out/2026-10-24/소개카드_1~8.jpg`, 10/24 21:54 — 8장 1:1 검수 완료, 모서리 캐릭터는 1번만·4·6·8번은 3D 스틸 안 캐릭터)과 3D 릴스(`admin/out/2026-10-24/릴스_3D.mp4`·표지 `릴스_3D_표지.jpg`, 21프레임 검수 완료) — 사용자가 "올려"라고 할 때만 올림. 릴스 음악은 HeyGen 로그인(`~/.local/bin/heygen auth login --oauth`) 뒤 `npx hyperframes media-use resolve --type bgm` | 10/24 | `admin/reels/intro3d/` | | [ ] | 소개 카드 최종본(`admin/out/2026-10-24/소개카드_1~8.jpg`, 10/24 21:54 — 8장 1:1 검수 완료, 모서리 캐릭터는 1번만·4·6·8번은 3D 스틸 안 캐릭터)과 3D 릴스(`admin/out/2026-10-24/릴스_3D.mp4`·표지 `릴스_3D_표지.jpg`, 21프레임 검수 완료) — 사용자가 "올려"라고 할 때만 올림. 릴스 음악은 HeyGen 로그인(`~/.local/bin/heygen auth login --oauth`) 뒤 `npx hyperframes media-use resolve --type bgm` | 10/24 | `admin/reels/intro3d/` |
| [ ] | 코디 옷 데이터 — 세미정장·정장·스트릿·꾸안꾸 4스타일은 7개 기온 구간 전부 20-30대와 40대~ 옷이 같음(캐주얼만 다름, warm·꾸안꾸는 10/25 고침). 40대~ 여/남 옷 목록 54개를 새로 써서 검토받고 반영 | 10/25 발견 | `admin/image-prompts/ootd.json` | | [x] | 코디 옷 데이터 — 세미정장·정장·스트릿·꾸안꾸 4스타일은 7개 기온 구간 전부 20-30대와 40대~ 옷이 같음(캐주얼만 다름, warm·꾸안꾸는 10/25 고침). 40대~ 여/남 옷 목록 54개를 새로 써서 검토받고 반영 — 10/26 그날 코디(--daily)로 대체해 고정 데이터는 예비용만 | 10/25 발견 | `admin/image-prompts/ootd.json` |
| [x] | 코디 카드 매일 다르게 — 고정 옷 데이터 대신 무신사 스냅 공개 API에서 오늘 구간 인기 코디를 사람별(40대~ 단정 태그 우선)로 골라 Claude가 옷 목록 추출, Codex가 참고 사진 첨부로 플랫레이 생성(`npm run card -- ootd --daily`, `/daily-cards`). 10/26 4장 검수 통과. 에이블리는 공개 API 없음(앱 전용)이라 미사용 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs`, `snap.mjs`, `outfit.mjs`, `codex-image.mjs` |
| [x] | 10/26 세미정장 코디(그날 코디 첫 게시) — 킹서버 카드 12→포스트 4275, 인스타 https://www.instagram.com/p/De8O2kqATrl/. 무신사 스냅 4개 참고, 4장 1:1 검수 | 사용자 요청 (10/26) | `admin/scripts/daily-ootd.mjs` |
| [x] | 10/26 몸 컨디션 타로(건강: 등산각·자전거각·산책각) — 킹서버 카드 13→포스트 4276, 인스타 https://www.instagram.com/p/De8Zw7MIEVW/. 기획에서 3번 산책각 비 시점 틀린 것 피드백으로 고침. card.mjs --post-wait 가 ECONNRESET 으로 두 번 실패해 post-king.py 로 저장 | 사용자 요청 (10/26) | `admin/scripts/card.mjs` |
| [x] | 각 카드 그림 미리 생성 — 가을에 나올 만한 28장(피크닉·캠핑·놀이공원·빨래·단풍·억새·테니스·골프·군고구마·붕어빵·군밤·사진산책·별보기·환기·세차·이불빨래·데이트·치맥·막걸리·파전·우산·넷플릭스·집콕·한강밤바람·멍뭉산책·센치·감성노래·낚시) + 기존 8 = 36/68. 여름·한겨울 전용 32장은 철 되면 생성 | 사용자 요청 (10/26) | `admin/src/assets/gak-card/` |
| [ ] | 카드 자동화 다음 단계 — ① 생성 직후 자동 검사(Claude 비전: 옷 개수·사람·글자·추가 옷, 불합격 1회 재생성) ② 승인 대기 카드 메일/Teams 알림 + 서명 토큰 승인 링크(`GET /v1/card/{id}/approve`) ③ 맥 launchd 매일 06:30 `claude -p "/daily-cards"` ④ 그림 세트가 차면 킹서버로 이전 | 사용자 요청 (10/26) | `backend/router/v1/card/card.py`, `admin/scripts/` |
| [ ] | 앱 헤더가 400~448px 폭에서 컨테이너를 넘쳐 로그인 버튼이 잘림(`frontend/src/b/BLayout.tsx` TopBar). 캡처는 456px로 찍어 피했지만 실제 폰(430·440px)에서도 잘릴 수 있음 | 10/24 캡처 중 발견 | `frontend/src/b/BLayout.tsx` | | [ ] | 앱 헤더가 400~448px 폭에서 컨테이너를 넘쳐 로그인 버튼이 잘림(`frontend/src/b/BLayout.tsx` TopBar). 캡처는 456px로 찍어 피했지만 실제 폰(430·440px)에서도 잘릴 수 있음 | 10/24 캡처 중 발견 | `frontend/src/b/BLayout.tsx` |
| [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` | | [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` |
| [x] | 10/25 건강·운동 타로(킹서버 카드 7→포스트 3960, 인스타 https://www.instagram.com/p/De5iLg4AS_M/)·꾸안꾸 코디는 처음 올린 카드 8→포스트 3961(인스타 De58VfXINy0)이 40대~ 옷이 20-30대와 같아 숨기고, 40대~ 옷을 새로 써서 카드 9→포스트 3962(인스타 De5-8gboL-c)로 재게시했으나 40대 여자 그림에 롱가디건이 끼고 전체가 여름 옷으로 보여 다시 숨김. 일교차 8도 이상이면 겉옷을 5번째 옷으로 넣게 고쳐 카드 10→포스트 3963(인스타 De6B2gwIMXF)으로 올렸으나 그림 배치와 이름표 자리가 어긋나 숨김. 프롬프트에 옷 자리를 적고 다시 그려 카드 11→포스트 3964, 인스타 https://www.instagram.com/p/De6JRIkoKbT/ 로 최종 게시. 07:52 예약(세션 크론)이 세션 종료로 안 돌아 09:46 수동 실행. 코디는 사용자 결정으로 사람 구분을 20-30대·40대~ 4장으로 바꿈(f30·m30 그림 파일 8장은 남아 있으나 미사용). 새 그림 8장(러닝각·자전거각·warm 꾸안꾸 6) | 사용자 요청 (10/24) | `admin/image-prompts/ootd.json`, `admin/scripts/card.mjs` | | [x] | 10/25 건강·운동 타로(킹서버 카드 7→포스트 3960, 인스타 https://www.instagram.com/p/De5iLg4AS_M/)·꾸안꾸 코디는 처음 올린 카드 8→포스트 3961(인스타 De58VfXINy0)이 40대~ 옷이 20-30대와 같아 숨기고, 40대~ 옷을 새로 써서 카드 9→포스트 3962(인스타 De5-8gboL-c)로 재게시했으나 40대 여자 그림에 롱가디건이 끼고 전체가 여름 옷으로 보여 다시 숨김. 일교차 8도 이상이면 겉옷을 5번째 옷으로 넣게 고쳐 카드 10→포스트 3963(인스타 De6B2gwIMXF)으로 올렸으나 그림 배치와 이름표 자리가 어긋나 숨김. 프롬프트에 옷 자리를 적고 다시 그려 카드 11→포스트 3964, 인스타 https://www.instagram.com/p/De6JRIkoKbT/ 로 최종 게시. 07:52 예약(세션 크론)이 세션 종료로 안 돌아 09:46 수동 실행. 코디는 사용자 결정으로 사람 구분을 20-30대·40대~ 4장으로 바꿈(f30·m30 그림 파일 8장은 남아 있으나 미사용). 새 그림 8장(러닝각·자전거각·warm 꾸안꾸 6) | 사용자 요청 (10/24) | `admin/image-prompts/ootd.json`, `admin/scripts/card.mjs` |
+3
View File
@@ -25,3 +25,6 @@ dist-ssr
# npm run card 결과 # npm run card 결과
out out
# 그날 코디 그림 (scripts/daily-ootd.mjs 가 만들고 카드가 /daily/... 로 읽는다)
public/daily
+23
View File
@@ -33,6 +33,10 @@ VITE_API_BASE_URL=http://localhost:9810 npm run dev # http://localhost:5175
- **카드**: 날씨각 각 카드(`../backend/seed/index_definition.json`, 53장). 오늘 점수가 높은 각 중 질문과 엮이는 3장을 고르고, 각 카드로 질문을 리딩한다. 카드 그림은 그 각의 아이콘. - **카드**: 날씨각 각 카드(`../backend/seed/index_definition.json`, 53장). 오늘 점수가 높은 각 중 질문과 엮이는 3장을 고르고, 각 카드로 질문을 리딩한다. 카드 그림은 그 각의 아이콘.
- 대주제·소주제·아이콘을 늘리려면 `topics.json`만 고친다. 새 꾸밈 모양은 CSS와 `image-prompts/tarot.json`에 같이 더한다. - 대주제·소주제·아이콘을 늘리려면 `topics.json`만 고친다. 새 꾸밈 모양은 CSS와 `image-prompts/tarot.json`에 같이 더한다.
## 매일 올리기 (슬래시 명령)
사용자용 안내는 `docs/인스타_카드_사용법.md`. Claude Code에서 `/daily-tarot <주제>`, `/daily-ootd <스타일>`, `/daily-cards <주제> <스타일>` 을 치면 만들기 → 장마다 검수 → 킹서버 피드·인스타 게시 → 링크 보고까지 한 번에 한다. 명령 정의는 `.claude/commands/`.
## 대화로 만들 때 (Claude·Codex) ## 대화로 만들 때 (Claude·Codex)
사용자가 "오늘 주식 날씨 타로 만들어 줘"처럼 말하면 아래 명령을 실행한다. 관리자 화면(`npm run dev`)이 켜져 있어야 한다. 사용자가 "오늘 주식 날씨 타로 만들어 줘"처럼 말하면 아래 명령을 실행한다. 관리자 화면(`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`와 같은 값. - 관리자 서버가 비밀값을 `/api/post`·`/api/cards`에서만 붙인다. 브라우저엔 안 나간다. 킹서버 키는 킹서버 `.env`의 `ADMIN_API_KEY`와 같은 값.
- 켜는 예: `VITE_API_BASE_URL=http://localhost:9810 ADMIN_API_KEY=… KING_ADMIN_API_KEY=… npm run dev` - 켜는 예: `VITE_API_BASE_URL=http://localhost:9810 ADMIN_API_KEY=… KING_ADMIN_API_KEY=… npm run dev`
## 그날 코디 (무신사 인기 스냅 → 옷 추출 → 참고 사진대로 그림)
코디 카드는 고정 데이터(`image-prompts/ootd.json` 구간×스타일 옷) 대신 **그날 무신사 인기 스냅**으로 만든다. 같은 날씨라도 매일 다른 코디가 나온다.
```bash
VITE_API_BASE_URL=https://weather.o2o.kr npm run card -- ootd --daily --style minimal --color sky --post-wait
```
포스트 하나는 스타일 하나(`--style`, 기본 minimal=꾸안꾸): 네 사람 모두 그 스타일 태그(`scripts/snap.mjs STYLE_TAGS`)가 붙은 스냅에서 고르고 제목도 그 스타일로 통일한다.
흐름(`scripts/daily-ootd.mjs`):
1. 오늘 예보로 기온 구간을 정한다(`scripts/daily-ootd.mjs weatherToday`).
2. `scripts/snap.mjs`: 무신사 스냅 공개 API에서 구간에 맞는 태그(가을코디·간절기코디·겨울코디…)와 단정 키워드(오피스룩·댄디룩…)로 인기 스냅을 모으고, 상품 카테고리로 상의·하의·신발이 다 있는 것만 남긴 뒤 사람별(40대~ 먼저, 단정 태그 가산점)로 하나씩 고른다. 45일 지난 스냅, 구간에 안 맞는 아우터(패딩·코트 등)·반바지는 뺀다. 사진·상품 썸네일은 `out/<날짜>/snaps/<사람>/`에 참고용으로만 받고 어디에도 올리지 않는다.
3. `scripts/outfit.mjs`: Claude CLI(sonnet, Read 로 사진을 봄)가 자리별(top·outer·bottom·shoes·bag) 한글 이름표와 영어 그림 설명을 뽑는다.
4. `scripts/codex-image.mjs`: Codex 에 스냅 사진·상품 썸네일을 첨부(`-i`)해 같은 옷·색으로 우리 플랫레이 스타일 그림을 그린다 → `public/daily/<날짜>-<사람>.webp` (git 에 넣지 않음).
5. 카드는 `copy.outfits`(JSON 문자열)로 이름표·그림 주소를 받는다(`src/cards/ootd.ts dailyOutfits`). 제목은 Claude 가 정한 스타일 한 단어(꾸안꾸·오피스룩…).
에이블리는 공개 API가 없어 쓰지 않는다(앱 전용). 고정 데이터 방식(`--daily` 없이)은 그대로 남아 있다.
## 카드 그림 만들기 (Codex 이미지 생성) ## 카드 그림 만들기 (Codex 이미지 생성)
**그림은 그날 만드는 카드에 필요한 것만 그때 만든다.** 조합(기온 구간 × 스타일 × 사람, 타로 78장)을 미리 일괄로 만들지 않는다. Codex 사용량이 한정돼 있다. **그림은 그날 만드는 카드에 필요한 것만 그때 만든다.** 조합(기온 구간 × 스타일 × 사람, 타로 78장)을 미리 일괄로 만들지 않는다. Codex 사용량이 한정돼 있다.
+28 -4
View File
@@ -6,7 +6,7 @@
// --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post). // --post 면 다 그린 뒤 날씨각 오늘 피드에 바로 올리고, --post-wait 면 승인 대기로 저장한다 (관리자 서버 /api/post).
// 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION) // 지역은 고르지 않는다. 카드는 서울 예보로 만들고 카드에 지역 이름은 나가지 않는다 (src/cards/data.ts BASE_REGION)
import { execFileSync } from 'node:child_process' import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path' import { resolve } from 'node:path'
const SLIDES = { tarot: 5, ootd: 4, intro: 8 } const SLIDES = { tarot: 5, ootd: 4, intro: 8 }
@@ -34,11 +34,14 @@ let copy = flag('--copy')
const topic = flag('--topic') const topic = flag('--topic')
const feedback = flag('--feedback') const feedback = flag('--feedback')
const color = flag('--color') const color = flag('--color')
const styleArg = flag('--style')
const outArg = flag('--out') const outArg = flag('--out')
const take = (name) => args.includes(name) && args.splice(args.indexOf(name), 1).length > 0 const take = (name) => args.includes(name) && args.splice(args.indexOf(name), 1).length > 0
const noImages = take('--no-images') let noImages = take('--no-images')
const postNow = take('--post') const postNow = take('--post')
const postWait = take('--post-wait') const postWait = take('--post-wait')
// --daily: 코디를 고정 데이터 대신 그날 무신사 인기 스냅에서 뽑아 그린다 (scripts/daily-ootd.mjs)
const daily = take('--daily')
const [template] = args const [template] = args
if (!SLIDES[template]) fail(`사용: npm run card -- <${Object.keys(SLIDES).join('|')}> [--topic 주제] [--feedback 피드백] [--color ${THEMES.join('|')}] [--copy 값] [--out 폴더]`) if (!SLIDES[template]) fail(`사용: npm run card -- <${Object.keys(SLIDES).join('|')}> [--topic 주제] [--feedback 피드백] [--color ${THEMES.join('|')}] [--copy 값] [--out 폴더]`)
@@ -62,6 +65,16 @@ if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template
console.log(`주제: ${body.topic}`) console.log(`주제: ${body.topic}`)
for (const [k, v] of Object.entries(body.copy)) console.log(` ${k}: ${v.replaceAll('\n', ' / ')}`) for (const [k, v] of Object.entries(body.copy)) console.log(` ${k}: ${v.replaceAll('\n', ' / ')}`)
copy = Buffer.from(JSON.stringify({ ...current, ...body.copy })).toString('base64url') copy = Buffer.from(JSON.stringify({ ...current, ...body.copy })).toString('base64url')
// 타로: 오늘 고른 각을 적어 두면 다음 7일은 다른 각이 나온다 (scripts/plan.mjs recentCodes)
if (template === 'tarot') {
const file = resolve('out/tarot-history.json')
const today = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
const history = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {}
const codes = ['c1', 'c2', 'c3'].map((k) => body.copy[k]).filter(Boolean)
history[today] = [...new Set([...(history[today] ?? []), ...codes])]
mkdirSync(resolve('out'), { recursive: true })
writeFileSync(file, JSON.stringify(history, null, 1))
}
} }
{ {
@@ -72,6 +85,19 @@ if (topic !== null || feedback !== null || (!copy && AUTO_PLAN.includes(template
console.log(`다시 그리거나 피드백할 때: --copy ${copy}`) console.log(`다시 그리거나 피드백할 때: --copy ${copy}`)
} }
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
const outDir = resolve(outArg ?? `out/${day}`)
if (daily) {
if (template !== 'ootd') fail('--daily 는 ootd 템플릿에서만 써요.')
const { runDailyOotd, toCardOutfits } = await import('./daily-ootd.mjs')
// 포스트 하나는 스타일 하나: --style <casual|semi|formal|street|minimal>, 없으면 --copy 의 style, 그것도 없으면 꾸안꾸
const style = styleArg ?? decode(copy).style ?? 'minimal'
const { outfits } = await runDailyOotd({ outDir, style })
copy = Buffer.from(JSON.stringify({ ...decode(copy), style, outfits: JSON.stringify(toCardOutfits(outfits)) })).toString('base64url')
noImages = true
}
// 그날 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (관리자 서버 /api/gen-image, 한 장씩) // 그날 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (관리자 서버 /api/gen-image, 한 장씩)
if (!noImages) { if (!noImages) {
const start = await fetch(`${ADMIN_URL}/api/gen-image`, { const start = await fetch(`${ADMIN_URL}/api/gen-image`, {
@@ -94,8 +120,6 @@ if (!noImages) {
} }
} }
const day = new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
const outDir = resolve(outArg ?? `out/${day}`)
mkdirSync(outDir, { recursive: true }) mkdirSync(outDir, { recursive: true })
const files = [] const files = []
+44
View File
@@ -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'
}
+101
View File
@@ -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}`)
}
+6 -28
View File
@@ -1,12 +1,9 @@
// 카드 그림을 프롬프트 템플릿(image-prompts/<종류>.json)대로 Codex 이미지 생성으로 만들어 src/assets/<종류>/<id>.webp 에 넣는다. // 카드 그림을 프롬프트 템플릿(image-prompts/<종류>.json)대로 Codex 이미지 생성으로 만들어 src/assets/<종류>/<id>.webp 에 넣는다.
// 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force] // 넣은 그림은 카드에 자동으로 붙는다. 사용: npm run gen-image -- ootd <구간|스타일|구간-사람-스타일|missing> [스타일] [--force]
// 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal // 예: ootd cool casual (12~16도 캐주얼 6명) · ootd semi (세미정장 전 구간) · ootd cool-f20-casual · ootd missing formal
import { execFileSync } from 'node:child_process' import { existsSync, mkdirSync, readFileSync } from 'node:fs'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path' import { join, resolve } from 'node:path'
import { drawWithCodex } from './codex-image.mjs'
const IMAGE_MODEL = process.env.CODEX_IMAGE_MODEL ?? 'gpt-6-sol'
function fail(message) { function fail(message) {
console.error(message) console.error(message)
@@ -77,33 +74,14 @@ for (const band of bands) {
console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`) console.log(`${band.id}: 이미 있어요 (다시 만들려면 --force)`)
continue continue
} }
const prompt = band.prompt let result
const work = mkdtempSync(join(tmpdir(), `gen-${kind}-${band.id}-`))
const task = [
'내장 이미지 생성 도구로 아래 프롬프트 그대로 이미지를 만든다 (비율은 프롬프트를 따른다).',
'만든 이미지를 직접 열어 확인한다: 사람 얼굴·손·마네킹·글자·숫자·로고가 있거나, 프롬프트의 물건이 빠지거나 잘렸으면 한 번만 다시 만든다 (사용량을 아끼려고 최대 2장).',
`통과한 한 장만 이 폴더에 result.png 로 저장한다. 다른 파일은 만들지 않는다.`,
'',
prompt,
].join('\n')
console.log(`${band.id}: Codex로 그리는 중…`)
try { try {
// 그림은 이미지 생성 도구가 만들고 Codex 는 도구를 부르고 결과를 저장하는 역할뿐이라 중간 모델·낮은 추론으로 고정한다 (가장 싼 gpt-6-luna 는 결과를 파일로 저장하지 못하고, 기본 설정의 gpt-6-astra·xhigh 는 한도를 금방 소진한다) result = drawWithCodex({ id: band.id, prompt: band.prompt, outPath: outPath(band.id) })
execFileSync('codex', ['exec', '--skip-git-repo-check', '-C', work, '-s', 'workspace-write', '-m', IMAGE_MODEL, '-c', 'model_reasoning_effort="low"', task], { stdio: ['ignore', 'ignore', 'inherit'] })
} catch (e) { } catch (e) {
rmSync(work, { recursive: true, force: true }) fail(e.message)
fail(`${band.id}: Codex 실행이 실패했어요 (${e.message}). 사용 한도나 로그인을 확인하세요.`)
} }
const png = readdirSync(work).find((f) => f === 'result.png') ?? readdirSync(work).find((f) => f.endsWith('.png'))
// 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤) // 저장을 빼먹는 건 그 한 장 문제라 나머지는 계속 만들고 끝에 모아서 알린다 (한도·로그인 실패는 위에서 바로 멈춤)
if (!png) { if (result !== 'ok') failed.push(band.id)
console.error(`${band.id}: Codex가 그림을 저장하지 않았어요. 작업 폴더: ${work}`)
failed.push(band.id)
continue
}
execFileSync('cwebp', ['-quiet', '-q', '88', '-resize', '1024', '0', join(work, png), '-o', outPath(band.id)])
rmSync(work, { recursive: true, force: true })
console.log(`${band.id}: ${outPath(band.id)}`)
} }
if (failed.length) fail(`못 만든 그림: ${failed.join(", ")} — 다시: npm run gen-image -- ${kind} ${failed.join(" ")}`) if (failed.length) fail(`못 만든 그림: ${failed.join(", ")} — 다시: npm run gen-image -- ${kind} ${failed.join(" ")}`)
+75
View File
@@ -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 })
})
})
}
+31 -8
View File
@@ -1,7 +1,7 @@
// 카드 문구 기획: 템플릿 칸·오늘 날씨·주제·피드백을 Claude CLI(claude -p)에 넘겨 칸별 문구를 받는다. // 카드 문구 기획: 템플릿 칸·오늘 날씨·주제·피드백을 Claude CLI(claude -p)에 넘겨 칸별 문구를 받는다.
// 관리자 서버(/api/plan)와 npm run card --topic 이 같이 쓴다. API 키 없이 이 맥에 로그인된 Claude Code를 쓴다. // 관리자 서버(/api/plan)와 npm run card --topic 이 같이 쓴다. API 키 없이 이 맥에 로그인된 Claude Code를 쓴다.
import { execFile } from 'node:child_process' import { execFile } from 'node:child_process'
import { readdirSync, readFileSync } from 'node:fs' import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os' import { tmpdir } from 'node:os'
import { resolve } from 'node:path' import { resolve } from 'node:path'
@@ -20,6 +20,19 @@ const questionOf = (topic) => {
} }
// 날씨 타로 카드 = 날씨각 각 카드 (서비스와 같은 각 목록) // 날씨 타로 카드 = 날씨각 각 카드 (서비스와 같은 각 목록)
const DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../backend/seed/index_definition.json'), 'utf8')).map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description })) const DECK = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../backend/seed/index_definition.json'), 'utf8')).map((g) => ({ id: g.code, name: g.name, icon: g.icon, meaning: g.description }))
// 최근에 쓴 각은 빼서 매일 같은 카드가 나오지 않게 한다 (card.mjs 가 기획할 때마다 적는다)
const HISTORY_FILE = resolve(import.meta.dirname, '../out/tarot-history.json')
const HISTORY_DAYS = 7
function recentCodes() {
if (!existsSync(HISTORY_FILE)) return []
try {
const history = JSON.parse(readFileSync(HISTORY_FILE, 'utf8'))
const cutoff = Date.now() - HISTORY_DAYS * 86400_000
return [...new Set(Object.entries(history).filter(([day]) => new Date(day).getTime() >= cutoff).flatMap(([, codes]) => codes))]
} catch {
return []
}
}
const categoryOf = (topic) => TOPICS.find((c) => topic.includes(c.name) || c.subtopics.some((s) => topic.includes(s))) const categoryOf = (topic) => TOPICS.find((c) => topic.includes(c.name) || c.subtopics.some((s) => topic.includes(s)))
const RULES = [ const RULES = [
@@ -56,15 +69,25 @@ const TAROT_TONE = [
'키워드(k)는 4~8자 명사구("같이 걷는 시간", "먼저 보내는 한 줄"). 행운 포인트(l)는 시간·날씨·행동 한 줄 22자 이내("저녁 8시, 17도로 걷기 딱 좋아요").', '키워드(k)는 4~8자 명사구("같이 걷는 시간", "먼저 보내는 한 줄"). 행운 포인트(l)는 시간·날씨·행동 한 줄 22자 이내("저녁 8시, 17도로 걷기 딱 좋아요").',
] ]
function tarotSection(topic) { /** 오늘 고를 수 있는 각: 최근 7일에 쓴 각은 뺀다 (관리자가 고정한 카드는 남긴다) */
function availableDeck(fixed = {}) {
const recent = new Set(recentCodes())
const keep = new Set(fixed.cards ?? [])
return DECK.filter((c) => !recent.has(c.id) || keep.has(c.id))
}
function tarotSection(topic, fixed = {}) {
const deck = availableDeck(fixed)
const excluded = DECK.filter((c) => !deck.includes(c)).map((c) => c.name)
return [ return [
'', '',
'## 각 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)', '## 각 카드 (이 목록에서만 고른다. card1·card2·card3에 서로 다른 code)',
questionOf(topic) ? `표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}` : '표지 질문(question)은 주제에 맞는 "오늘 ~할까요?" 꼴 질문 하나를 쓴다.', questionOf(topic) ? `표지 질문(question)은 이것을 쓴다(피드백이 바꾸라고 하면 바꾼다): ${questionOf(topic)}` : '표지 질문(question)은 주제에 맞는 "오늘 ~할까요?" 꼴 질문 하나를 쓴다.',
'오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 각(오늘 실제로 하기 좋은 각) 가운데 질문과 엮을 수 있는 것을 고른다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.', '오늘 날씨 데이터의 오늘_각_점수에서 점수가 높은 편(상위 15개 안)인 각 가운데 질문과 엮을 수 있는 것을 고른다. 매일 같은 야외 운동 각(산책·자전거·등산·드라이브)만 반복하지 말고 먹거리·계절·집·동네 각도 섞어 날마다 다른 카드가 나오게 한다. 세 장은 서로 다른 답(하나는 긍정, 하나는 조건부, 하나는 기다리기 같은 식)이 되게 고르고, 되도록 아침·낮·저녁(밤) 각에서 하나씩 골라 세 장이 하루로 이어지게 한다.',
excluded.length ? `최근 7일에 쓴 각이라 오늘은 고를 수 없음(목록에서 뺐다): ${excluded.join(', ')}` : '',
...TAROT_TONE, ...TAROT_TONE,
'', '',
...DECK.map((c) => `- ${c.id}: ${c.name} — ${c.meaning}`), ...deck.map((c) => `- ${c.id}: ${c.name} — ${c.meaning}`),
] ]
} }
@@ -86,23 +109,23 @@ function buildPrompt(ctx, { topic, feedback, fixed = {} }) {
topic ? `## 주제: ${topic}` : `## 주제: 없음 — 다음 대주제·소주제 중 오늘 날씨와 어울리는 것을 하나 골라 topic에 "대주제 소주제"로 적고 그 주제로 쓴다: ${TOPICS.map((c) => `${c.name}(${c.subtopics.join('·')})`).join(', ')}`, topic ? `## 주제: ${topic}` : `## 주제: 없음 — 다음 대주제·소주제 중 오늘 날씨와 어울리는 것을 하나 골라 topic에 "대주제 소주제"로 적고 그 주제로 쓴다: ${TOPICS.map((c) => `${c.name}(${c.subtopics.join('·')})`).join(', ')}`,
feedback ? `## 피드백 (반드시 반영): ${feedback}` : '', feedback ? `## 피드백 (반드시 반영): ${feedback}` : '',
'', '',
...(isTarot(ctx) ? tarotSection(topic) : []), ...(isTarot(ctx) ? tarotSection(topic, fixed) : []),
fixed.question ? `## 질문은 관리자가 정했다(그대로 쓴다): ${fixed.question}` : '', fixed.question ? `## 질문은 관리자가 정했다(그대로 쓴다): ${fixed.question}` : '',
fixed.cards?.length ? `## 카드는 관리자가 골랐다(card1·card2·card3 순서 그대로): ${fixed.cards.join(', ')}` : '', fixed.cards?.length ? `## 카드는 관리자가 골랐다(card1·card2·card3 순서 그대로): ${fixed.cards.join(', ')}` : '',
'모든 칸을 채운 JSON으로만 답한다. topic에는 쓴 주제를 짧게 적는다.', '모든 칸을 채운 JSON으로만 답한다. topic에는 쓴 주제를 짧게 적는다.',
].join('\n') ].join('\n')
} }
function schema(ctx) { function schema(ctx, fixed = {}) {
const properties = { topic: { type: 'string' } } const properties = { topic: { type: 'string' } }
for (const f of ctx.fields) if (!(isTarot(ctx) && DECK_KEY.test(f.key))) properties[f.key] = { type: 'string' } for (const f of ctx.fields) if (!(isTarot(ctx) && DECK_KEY.test(f.key))) properties[f.key] = { type: 'string' }
if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: DECK.map((c) => c.id) } if (isTarot(ctx)) for (const k of ['card1', 'card2', 'card3']) properties[k] = { type: 'string', enum: availableDeck(fixed).map((c) => c.id) }
return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false } return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false }
} }
/** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */ /** @returns {Promise<{ topic: string, copy: Record<string, string> }>} */
export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) { export function runPlan(ctx, { topic = '', feedback = '', fixed = {} } = {}) {
const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx)), '--tools', '', '--no-session-persistence', '--model', 'sonnet'] const args = ['-p', buildPrompt(ctx, { topic, feedback, fixed }), '--output-format', 'json', '--json-schema', JSON.stringify(schema(ctx, fixed)), '--tools', '', '--no-session-persistence', '--model', 'sonnet']
return new Promise((done, fail) => { return new Promise((done, fail) => {
execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => { execFile('claude', args, { cwd: tmpdir(), timeout: 180_000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`)) if (err) return fail(new Error(`Claude CLI 실행 실패: ${err.message}. 터미널에서 claude 로그인 상태를 확인하세요.`))
+233
View File
@@ -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) })
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 218 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 255 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 348 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 237 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

+7 -6
View File
@@ -133,7 +133,7 @@
top: 350px; top: 350px;
left: 80px; left: 80px;
width: 920px; width: 920px;
height: 800px; height: 760px;
border-radius: 44px; border-radius: 44px;
overflow: hidden; overflow: hidden;
background: var(--stage); background: var(--stage);
@@ -141,7 +141,7 @@
.ootd-stage > img { .ootd-stage > img {
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: cover; object-fit: contain;
} }
.ootd-labels { .ootd-labels {
position: absolute; position: absolute;
@@ -159,7 +159,7 @@
/* 그림 아래 옷 목록: 그림 속 위치에 기대지 않고 따로 적는다 */ /* 그림 아래 옷 목록: 그림 속 위치에 기대지 않고 따로 적는다 */
.ootd-items { .ootd-items {
position: absolute; position: absolute;
top: 1168px; top: 1126px;
left: 80px; left: 80px;
right: 80px; right: 80px;
margin: 0; margin: 0;
@@ -168,13 +168,14 @@
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
justify-content: center; justify-content: center;
gap: 10px; align-content: flex-start;
gap: 8px;
} }
.ootd-items li { .ootd-items li {
padding: 8px 18px; padding: 7px 16px;
border-radius: 99px; border-radius: 99px;
background: #fff; background: #fff;
font-size: 28px; font-size: 26px;
font-weight: 700; font-weight: 700;
box-shadow: 0 6px 16px #28304a1f; box-shadow: 0 6px 16px #28304a1f;
white-space: nowrap; white-space: nowrap;
+12 -1
View File
@@ -3,7 +3,7 @@ import spec from '../../image-prompts/ootd.json'
/** 낮 최고기온 구간 × 스타일 × 사람별 옷. 옷 목록·카드 글자는 image-prompts/ootd.json 한 곳에서 정한다. /** 낮 최고기온 구간 × 스타일 × 사람별 옷. 옷 목록·카드 글자는 image-prompts/ootd.json 한 곳에서 정한다.
* 그림은 src/assets/ootd/<구간>-<사람>-<스타일>.webp 가 있으면 자동으로 붙는다 (npm run gen-image -- ootd <구간|스타일>). * 그림은 src/assets/ootd/<구간>-<사람>-<스타일>.webp 가 있으면 자동으로 붙는다 (npm run gen-image -- ootd <구간|스타일>).
* 일교차가 크면(OUTER_GAP_C 이상) 겉옷을 5번째 옷으로 그린 <구간>-<사람>-<스타일>-outer.webp 를 쓰고 이름표에도 겉옷을 더한다 */ * 일교차가 크면(OUTER_GAP_C 이상) 겉옷을 5번째 옷으로 그린 <구간>-<사람>-<스타일>-outer.webp 를 쓰고 이름표에도 겉옷을 더한다 */
export type Outfit = { persona: string; label: string; labels: string[]; outer: string; imageId: string; image?: string } export type Outfit = { persona: string; label: string; style?: string; labels: string[]; outer: string; imageId: string; image?: string }
export type OotdBand = { id: string; from: number } export type OotdBand = { id: string; from: number }
const IMAGES = import.meta.glob<string>('../assets/ootd/*.webp', { eager: true, import: 'default' }) const IMAGES = import.meta.glob<string>('../assets/ootd/*.webp', { eager: true, import: 'default' })
@@ -27,6 +27,17 @@ export function ootdBand(maxC: number) {
return OOTD_BANDS.find((b) => maxC >= b.from) ?? OOTD_BANDS[OOTD_BANDS.length - 1] return OOTD_BANDS.find((b) => maxC >= b.from) ?? OOTD_BANDS[OOTD_BANDS.length - 1]
} }
/** 그날 무신사 스냅에서 뽑은 코디 (scripts/daily-ootd.mjs 가 copy.outfits 에 JSON 문자열로 넣는다). 없으면 undefined */
export function dailyOutfits(copy: Record<string, string>): Outfit[] | undefined {
if (!copy.outfits) return undefined
try {
const list = JSON.parse(copy.outfits) as { persona: string; label: string; style?: string; labels: string[]; image: string }[]
return list.map((o) => ({ persona: o.persona, label: o.label, style: o.style, labels: o.labels, outer: '', imageId: o.image, image: o.image }))
} catch {
return undefined
}
}
/** 그 구간·스타일의 사람별 옷. bandId 를 주면 기온 대신 그 구간 (예시 카드용). withOuter 면 겉옷 포함 그림·이름표 */ /** 그 구간·스타일의 사람별 옷. bandId 를 주면 기온 대신 그 구간 (예시 카드용). withOuter 면 겉옷 포함 그림·이름표 */
export function ootdOutfits(maxC: number, style?: string, bandId?: string, withOuter = false): Outfit[] { export function ootdOutfits(maxC: number, style?: string, bandId?: string, withOuter = false): Outfit[] {
const band = spec.bands.find((b) => b.id === (bandId || ootdBand(maxC).id))! const band = spec.bands.find((b) => b.id === (bandId || ootdBand(maxC).id))!
+4 -3
View File
@@ -8,7 +8,7 @@ import stillNight from '../assets/intro/still-night.webp'
import type { CardData } from './data' import type { CardData } from './data'
import { Frame, Lines } from './Frame' import { Frame, Lines } from './Frame'
import { tidy } from './text' import { tidy } from './text'
import { DEFAULT_STYLE, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd' import { DEFAULT_STYLE, dailyOutfits, needsOuter, ootdBand, ootdOutfits, styleLabel } from './ootd'
import { gakArt, gakByCode } from './gaks' import { gakArt, gakByCode } from './gaks'
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경 // 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
@@ -65,6 +65,7 @@ const ootd: Template = {
hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상', hashtags: '#날씨각 #오늘의코디 #OOTD #데일리룩 #옷차림 #코디추천 #날씨 #오늘날씨 #서울날씨 #일상',
}), }),
warnings: (d, c) => { warnings: (d, c) => {
if (dailyOutfits(c)) return []
const missing = ootdOutfits(d.maxC, c.style, undefined, needsOuter(d.maxC, d.morningC)).filter((o) => !o.image) const missing = ootdOutfits(d.maxC, c.style, undefined, needsOuter(d.maxC, d.morningC)).filter((o) => !o.image)
const id = `${ootdBand(d.maxC).id}` const id = `${ootdBand(d.maxC).id}`
return missing.length return missing.length
@@ -72,11 +73,11 @@ const ootd: Template = {
: [] : []
}, },
slides: (d, c) => slides: (d, c) =>
ootdOutfits(d.maxC, c.style, c.band, needsOuter(d.maxC, d.morningC)).map((o, i, all) => ( (dailyOutfits(c) ?? ootdOutfits(d.maxC, c.style, c.band, needsOuter(d.maxC, d.morningC))).map((o, i, all) => (
<Frame page={i} total={all.length} theme={c.theme} className="ootd" key={o.persona}> <Frame page={i} total={all.length} theme={c.theme} className="ootd" key={o.persona}>
<p className="meta">{d.dateLabel} · 오늘의 코디</p> <p className="meta">{d.dateLabel} · 오늘의 코디</p>
<h1 className="ootd-title"> <h1 className="ootd-title">
<Lines text={`*${o.label}* ${styleLabel(c.style)}${c.title ? ` ${c.title}` : ''}`} /> <Lines text={`*${o.label}* ${o.style ?? styleLabel(c.style)}${c.title ? ` ${c.title}` : ''}`} />
</h1> </h1>
<div className="ootd-stage"> <div className="ootd-stage">
{o.image ? ( {o.image ? (
+20 -1
View File
@@ -1,5 +1,7 @@
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
import { createReadStream, existsSync } from 'node:fs'
import type { IncomingMessage, ServerResponse } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http'
import { basename, resolve } from 'node:path'
import tailwindcss from '@tailwindcss/vite' import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
import { defineConfig, type Plugin } from 'vite' import { defineConfig, type Plugin } from 'vite'
@@ -171,9 +173,26 @@ function postApi(): Plugin {
} }
} }
/** GET /daily/<날짜>-<사람>.webp → public/daily (scripts/daily-ootd.mjs 가 만든 그날 코디 그림). publicDir 는 프론트 아이콘용이라 따로 서빙 */
function dailyImages(): Plugin {
return {
name: 'daily-images',
configureServer(server) {
server.middlewares.use('/daily', (req, res, next) => {
const name = basename((req.url ?? '').split('?')[0])
const file = resolve(import.meta.dirname, 'public/daily', name)
if (!name.endsWith('.webp') || !existsSync(file)) return next()
res.setHeader('Content-Type', 'image/webp')
res.setHeader('Cache-Control', 'no-cache')
createReadStream(file).pipe(res)
})
},
}
}
// 각 아이콘·캐릭터는 서비스와 같은 파일을 쓴다 (/icons/*.png) // 각 아이콘·캐릭터는 서비스와 같은 파일을 쓴다 (/icons/*.png)
export default defineConfig({ export default defineConfig({
plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi()], plugins: [react(), tailwindcss(), planApi(), imageApi(), postApi(), dailyImages()],
publicDir: '../frontend/public', publicDir: '../frontend/public',
server: { port: 5175, strictPort: true }, server: { port: 5175, strictPort: true },
}) })
+5
View File
@@ -51,6 +51,11 @@ class Settings(BaseSettings):
azure_blob_base_url: str = "" azure_blob_base_url: str = ""
azure_blob_sas_token: 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 (공개값). 비면 구글 로그인을 받지 않는다 # 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
google_client_id: str = "" google_client_id: str = ""
+2
View File
@@ -18,6 +18,7 @@ from router.v1.reaction.reaction import router as reaction_router
from router.v1.region.region import router as region_router from router.v1.region.region import router as region_router
from router.v1.season.season import router as season_router from router.v1.season.season import router as season_router
from router.v1.seo.seo import router as seo_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.sky.sky import router as sky_router
from router.v1.talk.talk import router as talk_router from router.v1.talk.talk import router as talk_router
from router.v1.watch.watch import router as watch_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(seo_router)
app.include_router(card_router) app.include_router(card_router)
app.include_router(reel_router) app.include_router(reel_router)
app.include_router(shorts_router)
class Res_Health(Res_WebPacketProtocol): class Res_Health(Res_WebPacketProtocol):
+4 -4
View File
@@ -14,7 +14,7 @@ async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path
err, html = await service.page(f"today/{sido}/{place}") err, html = await service.page(f"today/{sido}/{place}")
if err is not ErrorType.SUCCESS: if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404) return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) return HTMLResponse(html, headers={"Cache-Control": "no-store"})
@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)") @router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)")
@@ -22,7 +22,7 @@ async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = P
err, html = await service.page(f"today/{sido}/{place}/{gu}") err, html = await service.page(f"today/{sido}/{place}/{gu}")
if err is not ErrorType.SUCCESS: if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404) return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) return HTMLResponse(html, headers={"Cache-Control": "no-store"})
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)") @router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
@@ -30,7 +30,7 @@ async def get_tomorrow_page(sido: str = Path(..., pattern=_SLUG), place: str = P
err, html = await service.page(f"tomorrow/{sido}/{place}") err, html = await service.page(f"tomorrow/{sido}/{place}")
if err is not ErrorType.SUCCESS: if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404) return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) return HTMLResponse(html, headers={"Cache-Control": "no-store"})
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지") @router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
@@ -38,4 +38,4 @@ async def get_tomorrow_gu_page(sido: str = Path(..., pattern=_SLUG), place: str
err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}") err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}")
if err is not ErrorType.SUCCESS: if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404) return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) return HTMLResponse(html, headers={"Cache-Control": "no-store"})
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
class ShortItem(WebPacketProtocol):
id: str # 유튜브 영상 ID
title: str
class Res_ShortList(Res_WebPacketProtocol):
items: list[ShortItem] = []
+16
View File
@@ -0,0 +1,16 @@
from fastapi import APIRouter, Depends
from common.enums import ErrorType
from common.models.errors import error_info
from router.v1.shorts.protocol import Res_ShortList, ShortItem
from services.shorts_service import ShortsService
router = APIRouter(prefix="/v1/shorts", tags=["shorts"])
@router.get("", response_model=Res_ShortList, response_model_exclude_none=True, summary="오늘 화면 쇼츠 줄: 날씨각 유튜브 채널의 쇼츠, 최신순")
async def list_shorts(service: ShortsService = Depends()) -> Res_ShortList:
err, items = await service.items()
if err is not ErrorType.SUCCESS:
return Res_ShortList(result=error_info(err))
return Res_ShortList(items=[ShortItem(**i) for i in items])
+8
View File
@@ -21,6 +21,7 @@ from services.external.culture_api import SIDO_NAME
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
from services.feed_service import build_feed_day, clear_feed_cache 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.week_service import collect_events, drop_known
from services.weekend_rank import WeekendRank 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.error(f"[scheduler] refresh_events done mark: {e}")
LOG.info(f"[scheduler] refresh_events: {detail}") LOG.info(f"[scheduler] refresh_events: {detail}")
return ErrorType.SUCCESS if ok else ErrorType.EXTERNAL_API_ERROR 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
+55
View File
@@ -0,0 +1,55 @@
import re
from typing import Optional
import httpx
# YouTube Data API v3 (API 키). 채널 업로드 목록 → 영상 정보로 쇼츠만 고른다
API_URL = "https://www.googleapis.com/youtube/v3"
# 키 없이 영상 제목만 받을 때
OEMBED_URL = "https://www.youtube.com/oembed"
SHORT_MAX_SEC = 180 # 쇼츠는 3분 이하
_DURATION = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$")
def seconds(iso: str) -> Optional[int]:
"""ISO 8601 길이("PT1M5S") → 초. 형식이 다르면 None."""
m = _DURATION.match(iso or "")
if not m:
return None
h, mi, s = (int(g or 0) for g in m.groups())
return h * 3600 + mi * 60 + s
async def channel_shorts(client: httpx.AsyncClient, key: str, channel_id: str, limit: int) -> list[dict]:
"""채널의 공개·퍼가기 허용 쇼츠 [{id, title, published}], 최신순."""
res = await client.get(f"{API_URL}/channels", params={"part": "contentDetails", "id": channel_id, "key": key})
res.raise_for_status()
channels = res.json().get("items") or []
if not channels:
return []
uploads = channels[0]["contentDetails"]["relatedPlaylists"]["uploads"]
res = await client.get(f"{API_URL}/playlistItems", params={"part": "contentDetails", "playlistId": uploads, "maxResults": 50, "key": key})
res.raise_for_status()
ids = [i["contentDetails"]["videoId"] for i in res.json().get("items") or []]
if not ids:
return []
res = await client.get(f"{API_URL}/videos", params={"part": "snippet,contentDetails,status", "id": ",".join(ids), "key": key})
res.raise_for_status()
found = []
for v in res.json().get("items") or []:
status, sec = v.get("status", {}), seconds(v["contentDetails"].get("duration", ""))
if status.get("privacyStatus") != "public" or not status.get("embeddable") or sec is None or sec > SHORT_MAX_SEC:
continue
found.append({"id": v["id"], "title": v["snippet"]["title"], "published": v["snippet"]["publishedAt"]})
found.sort(key=lambda x: x["published"], reverse=True)
return found[:limit]
async def video_title(client: httpx.AsyncClient, video_id: str) -> Optional[str]:
"""영상 제목. 없거나 퍼가기가 막힌 영상이면 None."""
res = await client.get(OEMBED_URL, params={"url": f"https://www.youtube.com/shorts/{video_id}", "format": "json"})
if res.status_code in (401, 403, 404):
return None
res.raise_for_status()
return res.json().get("title")
+51
View File
@@ -0,0 +1,51 @@
import asyncio
import json
import httpx
from redis.exceptions import RedisError
from common.cache.redis_client import REDIS
from common.enums import ErrorType
from common.logger import LOG
from config.settings import settings
from services.external import youtube
CACHE_KEY = "shorts:list"
# 워커가 하루 3번(07·12·18시 10분) 새로 받는다. 한 번 실패해도 다음 회차까지 이전 목록을 쓰게 넉넉히 둔다
CACHE_SEC = 2 * 86400
MAX_ITEMS = 10
class ShortsService:
async def items(self) -> tuple[ErrorType, list[dict]]:
"""오늘 화면 쇼츠 줄 [{id, title}]. 워커가 받아 둔 목록을 읽고, 없을 때만(처음 켰을 때) 바로 받는다."""
try:
cached = await REDIS.conn.get(CACHE_KEY)
except RedisError as e:
LOG.error(f"[shorts] cache get: {e}")
cached = None
if cached:
return ErrorType.SUCCESS, json.loads(cached)
return await self.refresh()
async def refresh(self) -> tuple[ErrorType, list[dict]]:
"""유튜브에서 새로 받아 캐시에 둔다. API 키가 있으면 채널에서, 없으면 설정의 영상 ID 목록으로."""
try:
async with httpx.AsyncClient(timeout=10) as client:
items = await self._fetch(client)
except (httpx.HTTPError, KeyError, ValueError) as e:
LOG.error(f"[shorts] fetch: {e}")
return ErrorType.EXTERNAL_API_ERROR, []
try:
await REDIS.conn.set(CACHE_KEY, json.dumps(items, ensure_ascii=False), ex=CACHE_SEC)
except RedisError as e:
LOG.error(f"[shorts] cache set: {e}")
return ErrorType.SUCCESS, items
async def _fetch(self, client: httpx.AsyncClient) -> list[dict]:
if settings.youtube_api_key:
found = await youtube.channel_shorts(client, settings.youtube_api_key, settings.youtube_channel_id, MAX_ITEMS)
return [{"id": v["id"], "title": v["title"]} for v in found]
ids = [i.strip() for i in settings.youtube_shorts.split(",") if i.strip()][:MAX_ITEMS]
titles = await asyncio.gather(*(youtube.video_title(client, i) for i in ids))
return [{"id": i, "title": t} for i, t in zip(ids, titles) if t]
+73
View File
@@ -0,0 +1,73 @@
import json
import httpx
import pytest
from common.cache.redis_client import REDIS
from common.enums import ErrorType
from services import shorts_service
from services.external.youtube import channel_shorts, seconds, video_title
from services.shorts_service import CACHE_KEY, ShortsService
def test_seconds_parses_iso_duration():
assert seconds("PT45S") == 45
assert seconds("PT1M5S") == 65
assert seconds("PT1H") == 3600
assert seconds("P1D") is None
def _api(videos: list[dict]) -> httpx.MockTransport:
def handle(req: httpx.Request) -> httpx.Response:
if req.url.path.endswith("/channels"):
return httpx.Response(200, json={"items": [{"contentDetails": {"relatedPlaylists": {"uploads": "UUtest"}}}]})
if req.url.path.endswith("/playlistItems"):
assert req.url.params["playlistId"] == "UUtest"
return httpx.Response(200, json={"items": [{"contentDetails": {"videoId": v["id"]}} for v in videos]})
return httpx.Response(200, json={"items": videos})
return httpx.MockTransport(handle)
def _video(vid: str, duration: str, published: str, embeddable: bool = True, privacy: str = "public") -> dict:
return {"id": vid, "snippet": {"title": f"제목 {vid}", "publishedAt": published}, "contentDetails": {"duration": duration},
"status": {"embeddable": embeddable, "privacyStatus": privacy}}
@pytest.mark.anyio
async def test_channel_shorts_keeps_public_embeddable_short_videos_newest_first():
videos = [
_video("old", "PT30S", "2026-10-20T00:00:00Z"),
_video("new", "PT58S", "2026-10-26T00:00:00Z"),
_video("long", "PT10M", "2026-10-25T00:00:00Z"),
_video("noembed", "PT20S", "2026-10-24T00:00:00Z", embeddable=False),
_video("private", "PT20S", "2026-10-23T00:00:00Z", privacy="unlisted"),
]
async with httpx.AsyncClient(transport=_api(videos)) as client:
found = await channel_shorts(client, "key", "UCtest", 10)
assert [v["id"] for v in found] == ["new", "old"]
@pytest.mark.anyio
async def test_video_title_none_when_embedding_blocked():
def handle(req: httpx.Request) -> httpx.Response:
if "blocked" in req.url.params["url"]:
return httpx.Response(401)
return httpx.Response(200, content=json.dumps({"title": "오늘 자전거각"}))
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:
assert await video_title(client, "ok") == "오늘 자전거각"
assert await video_title(client, "blocked") is None
@pytest.mark.anyio
async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch):
calls = []
async def fake_fetch(self, client):
calls.append(1)
return [{"id": "abc", "title": "오늘 자전거각"}]
monkeypatch.setattr(shorts_service.ShortsService, "_fetch", fake_fetch)
await REDIS.conn.delete(CACHE_KEY)
assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}])
assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}])
assert len(calls) == 1
+5 -2
View File
@@ -5,7 +5,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.logger import LOG 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: 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, "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_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) 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() 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() stop = asyncio.Event()
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
+58
View File
@@ -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`
+2
View File
@@ -3,6 +3,7 @@ import { BLayout } from './b/BLayout'
import { FoliagePage } from './b/FoliagePage' import { FoliagePage } from './b/FoliagePage'
import { GakPage } from './b/GakPage' import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage' import { SeasonPage } from './b/SeasonPage'
import { ShortsPage } from './b/Shorts'
import { SkyPage } from './b/SkyPage' import { SkyPage } from './b/SkyPage'
import { TalkPage } from './b/TalkPage' import { TalkPage } from './b/TalkPage'
import { TodayPage } from './b/TodayPage' import { TodayPage } from './b/TodayPage'
@@ -22,6 +23,7 @@ export default function App() {
<Route path="season" element={<SeasonPage />} /> <Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} /> <Route path="foliage" element={<FoliagePage />} />
<Route path="talk" element={<TalkPage />} /> <Route path="talk" element={<TalkPage />} />
<Route path="shorts/:id?" element={<ShortsPage />} />
<Route path="*" element={<TodayPage />} /> <Route path="*" element={<TodayPage />} />
</Route> </Route>
</Routes> </Routes>
@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen'; import { client } from '../client.gen';
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen'; import { 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, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen'; 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> = [ export type QueryKey<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & { Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -1259,6 +1259,23 @@ export const rejectCardMutation = (options?: Partial<Options<RejectCardData>>):
return mutationOptions; return mutationOptions;
}; };
/**
* 카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만
*/
export const publishInstagramMutation = (options?: Partial<Options<PublishInstagramData>>): UseMutationOptions<PublishInstagramResponse, PublishInstagramError, Options<PublishInstagramData>> => {
const mutationOptions: UseMutationOptions<PublishInstagramResponse, PublishInstagramError, Options<PublishInstagramData>> = {
mutationFn: async (fnOptions) => {
const { data } = await publishInstagram({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const getCardImageQueryKey = (options: Options<GetCardImageData>) => createQueryKey('getCardImage', options); export const getCardImageQueryKey = (options: Options<GetCardImageData>) => createQueryKey('getCardImage', options);
/** /**
@@ -1277,6 +1294,112 @@ export const getCardImageOptions = (options: Options<GetCardImageData>) => query
queryKey: getCardImageQueryKey(options) queryKey: getCardImageQueryKey(options)
}); });
export const listReelsQueryKey = (options?: Options<ListReelsData>) => createQueryKey('listReels', options);
/**
* 릴스 목록 (관리자)
*/
export const listReelsOptions = (options?: Options<ListReelsData>) => queryOptions<ListReelsResponse, ListReelsError, ListReelsResponse, ReturnType<typeof listReelsQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listReels({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listReelsQueryKey(options)
});
/**
* 릴스 mp4 저장 (관리자). 공개 주소가 생기고, 인스타엔 따로 올린다
*/
export const createReelMutation = (options?: Partial<Options<CreateReelData>>): UseMutationOptions<CreateReelResponse, CreateReelError, Options<CreateReelData>> => {
const mutationOptions: UseMutationOptions<CreateReelResponse, CreateReelError, Options<CreateReelData>> = {
mutationFn: async (fnOptions) => {
const { data } = await createReel({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 릴스를 인스타그램에 올리기 (관리자). 같은 릴스는 한 번만
*/
export const publishInstagram2Mutation = (options?: Partial<Options<PublishInstagram2Data>>): UseMutationOptions<PublishInstagram2Response, PublishInstagram2Error, Options<PublishInstagram2Data>> => {
const mutationOptions: UseMutationOptions<PublishInstagram2Response, PublishInstagram2Error, Options<PublishInstagram2Data>> = {
mutationFn: async (fnOptions) => {
const { data } = await publishInstagram2({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const getReelVideoQueryKey = (options: Options<GetReelVideoData>) => createQueryKey('getReelVideo', options);
/**
* 릴스 영상 (인스타가 받아 가는 공개 주소, Range 지원)
*/
export const getReelVideoOptions = (options: Options<GetReelVideoData>) => queryOptions<unknown, GetReelVideoError, unknown, ReturnType<typeof getReelVideoQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getReelVideo({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getReelVideoQueryKey(options)
});
export const getReelCoverQueryKey = (options: Options<GetReelCoverData>) => createQueryKey('getReelCover', options);
/**
* 릴스 표지
*/
export const getReelCoverOptions = (options: Options<GetReelCoverData>) => queryOptions<unknown, GetReelCoverError, unknown, ReturnType<typeof getReelCoverQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getReelCover({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getReelCoverQueryKey(options)
});
export const 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); export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
/** /**
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts // This file is auto-generated by @hey-api/openapi-ts
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen'; export { 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';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type LiLine truncated export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetReelCoverData, type GetReelCoverError, type GetReelCoverErrors, type GetReelCoverResponses, type GetReelVideoData, type GetReelVideoError, type GetReelVideoErrors, type GetReelVideoResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsRespoLine truncated
+43 -1
View File
@@ -2,7 +2,7 @@
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client'; import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
import { client } from './client.gen'; import { client } from './client.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen'; import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, CreateReelData, CreateReelErrors, CreateReelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetReelCoverData, GetReelCoverErrors, GetReelCoverResponses, GetReelVideoData, GetReelVideoErrors, GetReelVideoResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListReelsData, ListReelsErrors, ListReelsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListShortsData, ListShortsResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, PublishInstagram2Data, PublishInstagram2Errors, PublishInstagram2Responses, PublishInstagramData, PublishInstagramErrors, PublishInstagramResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & { export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/** /**
@@ -408,11 +408,53 @@ export const publishCard = <ThrowOnError extends boolean = true>(options: Option
*/ */
export const rejectCard = <ThrowOnError extends boolean = true>(options: Options<RejectCardData, ThrowOnError>): RequestResult<RejectCardResponses, RejectCardErrors, ThrowOnError> => (options.client ?? client).post<RejectCardResponses, RejectCardErrors, ThrowOnError>({ url: '/v1/card/{card_id}/reject', ...options }); export const rejectCard = <ThrowOnError extends boolean = true>(options: Options<RejectCardData, ThrowOnError>): RequestResult<RejectCardResponses, RejectCardErrors, ThrowOnError> => (options.client ?? client).post<RejectCardResponses, RejectCardErrors, ThrowOnError>({ url: '/v1/card/{card_id}/reject', ...options });
/**
* 카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만
*/
export const publishInstagram = <ThrowOnError extends boolean = true>(options: Options<PublishInstagramData, ThrowOnError>): RequestResult<PublishInstagramResponses, PublishInstagramErrors, ThrowOnError> => (options.client ?? client).post<PublishInstagramResponses, PublishInstagramErrors, ThrowOnError>({ url: '/v1/card/{card_id}/instagram', ...options });
/** /**
* 카드뉴스 이미지 * 카드뉴스 이미지
*/ */
export const getCardImage = <ThrowOnError extends boolean = true>(options: Options<GetCardImageData, ThrowOnError>): RequestResult<GetCardImageResponses, GetCardImageErrors, ThrowOnError> => (options.client ?? client).get<GetCardImageResponses, GetCardImageErrors, ThrowOnError>({ url: '/v1/card/{card_id}/{seq}.jpg', ...options }); export const getCardImage = <ThrowOnError extends boolean = true>(options: Options<GetCardImageData, ThrowOnError>): RequestResult<GetCardImageResponses, GetCardImageErrors, ThrowOnError> => (options.client ?? client).get<GetCardImageResponses, GetCardImageErrors, ThrowOnError>({ url: '/v1/card/{card_id}/{seq}.jpg', ...options });
/**
* 릴스 목록 (관리자)
*/
export const listReels = <ThrowOnError extends boolean = true>(options?: Options<ListReelsData, ThrowOnError>): RequestResult<ListReelsResponses, ListReelsErrors, ThrowOnError> => (options?.client ?? client).get<ListReelsResponses, ListReelsErrors, ThrowOnError>({ url: '/v1/reel', ...options });
/**
* 릴스 mp4 저장 (관리자). 공개 주소가 생기고, 인스타엔 따로 올린다
*/
export const createReel = <ThrowOnError extends boolean = true>(options: Options<CreateReelData, ThrowOnError>): RequestResult<CreateReelResponses, CreateReelErrors, ThrowOnError> => (options.client ?? client).post<CreateReelResponses, CreateReelErrors, ThrowOnError>({
url: '/v1/reel',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 릴스를 인스타그램에 올리기 (관리자). 같은 릴스는 한 번만
*/
export const publishInstagram2 = <ThrowOnError extends boolean = true>(options: Options<PublishInstagram2Data, ThrowOnError>): RequestResult<PublishInstagram2Responses, PublishInstagram2Errors, ThrowOnError> => (options.client ?? client).post<PublishInstagram2Responses, PublishInstagram2Errors, ThrowOnError>({ url: '/v1/reel/{reel_id}/instagram', ...options });
/**
* 릴스 영상 (인스타가 받아 가는 공개 주소, Range 지원)
*/
export const getReelVideo = <ThrowOnError extends boolean = true>(options: Options<GetReelVideoData, ThrowOnError>): RequestResult<GetReelVideoResponses, GetReelVideoErrors, ThrowOnError> => (options.client ?? client).get<GetReelVideoResponses, GetReelVideoErrors, ThrowOnError>({ url: '/v1/reel/{reel_id}.mp4', ...options });
/**
* 릴스 표지
*/
export const getReelCover = <ThrowOnError extends boolean = true>(options: Options<GetReelCoverData, ThrowOnError>): RequestResult<GetReelCoverResponses, GetReelCoverErrors, ThrowOnError> => (options.client ?? client).get<GetReelCoverResponses, GetReelCoverErrors, ThrowOnError>({ url: '/v1/reel/{reel_id}/cover.jpg', ...options });
/**
* 오늘 화면 쇼츠 줄: 날씨각 유튜브 채널의 쇼츠, 최신순
*/
export const listShorts = <ThrowOnError extends boolean = true>(options?: Options<ListShortsData, ThrowOnError>): RequestResult<ListShortsResponses, unknown, ThrowOnError> => (options?.client ?? client).get<ListShortsResponses, unknown, ThrowOnError>({ url: '/v1/shorts', ...options });
/** /**
* 헬스체크 * 헬스체크
*/ */
+373 -1
View File
@@ -1,7 +1,7 @@
// This file is auto-generated by @hey-api/openapi-ts // This file is auto-generated by @hey-api/openapi-ts
export type ClientOptions = { export type ClientOptions = {
baseUrl: `${string}://${string}` | (string & {}); baseUrl: 'http://localhost:9811' | (string & {});
}; };
/** /**
@@ -285,6 +285,10 @@ export type CardItem = {
* Image Urls * Image Urls
*/ */
image_urls?: Array<string>; image_urls?: Array<string>;
/**
* Ig Media Id
*/
ig_media_id?: string | null;
}; };
/** /**
@@ -1485,6 +1489,36 @@ export type RankData = {
situation_label?: string | null; situation_label?: string | null;
}; };
/**
* ReelItem
*/
export type ReelItem = {
/**
* Reel Id
*/
reel_id: number;
/**
* Title
*/
title: string;
/**
* Created At
*/
created_at: string;
/**
* Video Url
*/
video_url: string;
/**
* Cover Url
*/
cover_url?: string | null;
/**
* Ig Media Id
*/
ig_media_id?: string | null;
};
/** /**
* RegionData * RegionData
*/ */
@@ -1533,6 +1567,12 @@ export type ReqCardCreate = {
* Caption * Caption
*/ */
caption?: string; caption?: string;
/**
* Hashtags
*
* 인스타 캡션 뒤에만 붙는 해시태그. 날씨각 피드에는 안 나간다
*/
hashtags?: string;
/** /**
* Texts * Texts
* *
@@ -1624,6 +1664,40 @@ export type ReqMyGakScore = {
rules: Array<MyGakRule>; rules: Array<MyGakRule>;
}; };
/**
* Req_ReelCreate
*/
export type ReqReelCreate = {
/**
* Title
*
* 인스타 캡션 첫 줄
*/
title: string;
/**
* Caption
*/
caption?: string;
/**
* Hashtags
*
* 인스타 캡션 뒤에 붙는 해시태그
*/
hashtags?: string;
/**
* Video
*
* mp4(H.264, 9:16), base64, 30MB 이하
*/
video: string;
/**
* Cover
*
* 표지 JPEG, base64 (없으면 인스타가 첫 장면을 쓴다)
*/
cover?: string | null;
};
/** /**
* Req_Refresh * Req_Refresh
*/ */
@@ -1797,6 +1871,10 @@ export type ResCard = {
* Image Urls * Image Urls
*/ */
image_urls?: Array<string>; image_urls?: Array<string>;
/**
* Ig Media Id
*/
ig_media_id?: string | null;
}; };
/** /**
@@ -2166,6 +2244,48 @@ export type ResPostSave = {
saved?: boolean | null; saved?: boolean | null;
}; };
/**
* Res_Reel
*/
export type ResReel = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Reel Id
*/
reel_id?: number | null;
/**
* Video Url
*/
video_url?: string | null;
/**
* Cover Url
*/
cover_url?: string | null;
/**
* Ig Media Id
*/
ig_media_id?: string | null;
};
/**
* Res_ReelList
*/
export type ResReelList = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Items
*/
items?: Array<ReelItem>;
};
/** /**
* Res_Region * Res_Region
*/ */
@@ -2261,6 +2381,21 @@ export type ResSeasonWeek = {
news?: Array<ArticleSummary>; news?: Array<ArticleSummary>;
}; };
/**
* Res_ShortList
*/
export type ResShortList = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Items
*/
items?: Array<ShortItem>;
};
/** /**
* Res_Sky * Res_Sky
*/ */
@@ -2674,6 +2809,20 @@ export type ScoreBand = {
current: boolean; current: boolean;
}; };
/**
* ShortItem
*/
export type ShortItem = {
/**
* Id
*/
id: string;
/**
* Title
*/
title: string;
};
/** /**
* Sky * Sky
*/ */
@@ -5719,6 +5868,42 @@ export type RejectCardResponses = {
export type RejectCardResponse = RejectCardResponses[keyof RejectCardResponses]; export type RejectCardResponse = RejectCardResponses[keyof RejectCardResponses];
export type PublishInstagramData = {
body?: never;
headers?: {
/**
* X-Admin-Key
*/
'x-admin-key'?: string | null;
};
path: {
/**
* Card Id
*/
card_id: number;
};
query?: never;
url: '/v1/card/{card_id}/instagram';
};
export type PublishInstagramErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type PublishInstagramError = PublishInstagramErrors[keyof PublishInstagramErrors];
export type PublishInstagramResponses = {
/**
* Successful Response
*/
200: ResCard;
};
export type PublishInstagramResponse = PublishInstagramResponses[keyof PublishInstagramResponses];
export type GetCardImageData = { export type GetCardImageData = {
body?: never; body?: never;
path: { path: {
@@ -5755,6 +5940,193 @@ export type GetCardImageResponses = {
200: unknown; 200: unknown;
}; };
export type ListReelsData = {
body?: never;
headers?: {
/**
* X-Admin-Key
*/
'x-admin-key'?: string | null;
};
path?: never;
query?: {
/**
* Limit
*/
limit?: number;
};
url: '/v1/reel';
};
export type ListReelsErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type ListReelsError = ListReelsErrors[keyof ListReelsErrors];
export type ListReelsResponses = {
/**
* Successful Response
*/
200: ResReelList;
};
export type ListReelsResponse = ListReelsResponses[keyof ListReelsResponses];
export type CreateReelData = {
body: ReqReelCreate;
headers?: {
/**
* X-Admin-Key
*/
'x-admin-key'?: string | null;
};
path?: never;
query?: never;
url: '/v1/reel';
};
export type CreateReelErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type CreateReelError = CreateReelErrors[keyof CreateReelErrors];
export type CreateReelResponses = {
/**
* Successful Response
*/
200: ResReel;
};
export type CreateReelResponse = CreateReelResponses[keyof CreateReelResponses];
export type PublishInstagram2Data = {
body?: never;
headers?: {
/**
* X-Admin-Key
*/
'x-admin-key'?: string | null;
};
path: {
/**
* Reel Id
*/
reel_id: number;
};
query?: never;
url: '/v1/reel/{reel_id}/instagram';
};
export type PublishInstagram2Errors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type PublishInstagram2Error = PublishInstagram2Errors[keyof PublishInstagram2Errors];
export type PublishInstagram2Responses = {
/**
* Successful Response
*/
200: ResReel;
};
export type PublishInstagram2Response = PublishInstagram2Responses[keyof PublishInstagram2Responses];
export type GetReelVideoData = {
body?: never;
path: {
/**
* Reel Id
*/
reel_id: number;
};
query?: never;
url: '/v1/reel/{reel_id}.mp4';
};
export type GetReelVideoErrors = {
/**
* Not Found
*/
404: unknown;
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetReelVideoError = GetReelVideoErrors[keyof GetReelVideoErrors];
export type GetReelVideoResponses = {
/**
* Successful Response
*/
200: unknown;
/**
* Partial Content
*/
206: unknown;
};
export type GetReelCoverData = {
body?: never;
path: {
/**
* Reel Id
*/
reel_id: number;
};
query?: never;
url: '/v1/reel/{reel_id}/cover.jpg';
};
export type GetReelCoverErrors = {
/**
* Not Found
*/
404: unknown;
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetReelCoverError = GetReelCoverErrors[keyof GetReelCoverErrors];
export type GetReelCoverResponses = {
/**
* Successful Response
*/
200: unknown;
};
export type ListShortsData = {
body?: never;
path?: never;
query?: never;
url: '/v1/shorts';
};
export type ListShortsResponses = {
/**
* Successful Response
*/
200: ResShortList;
};
export type ListShortsResponse = ListShortsResponses[keyof ListShortsResponses];
export type HealthzHealthzGetData = { export type HealthzHealthzGetData = {
body?: never; body?: never;
path?: never; path?: never;
+338
View File
@@ -0,0 +1,338 @@
import { useQuery } from '@tanstack/react-query'
import { type CSSProperties, type PointerEvent as ReactPointerEvent, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router'
import { listShortsOptions } from '../api/client/@tanstack/react-query.gen'
import type { ShortItem } from '../api/client'
import { cx } from '../lib/utils'
import { Rail, Skel, SkelRail, TAP44 } from './ui'
// 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다.
// 위 로고·아래 제목 줄이 작은 카드에서 겹쳐 보이지 않게 가운데를 1.4배로 키워 위아래를 잘라 낸다
const CARD_W = 120
const PLAYER_W = 200
const SCALE = (CARD_W / PLAYER_W) * 1.4
// 쇼츠 페이지의 영상 칸: 위 헤더(54px)·버튼 줄(48px)과 아래 탭 바(--shorts-tab) 사이 높이와 화면 너비 안에 9:16으로 맞춘다
const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 54px - 48px - var(--shorts-tab, 0px)) * 9 / 16))', aspectRatio: '9 / 16' }
/** 아래 탭 바 높이 (기기마다 안전 영역이 달라 실제로 잰다) */
function useTabBarHeight() {
const [h, setH] = useState(0)
useLayoutEffect(() => {
const nav = document.querySelector<HTMLElement>('nav.b-tabbar')
if (!nav) return
const ro = new ResizeObserver(() => setH(nav.offsetHeight))
ro.observe(nav)
return () => ro.disconnect()
}, [])
return h
}
const YT_ORIGIN = 'https://www.youtube-nocookie.com'
function embed(id: string) {
const q = new URLSearchParams({
autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1',
enablejsapi: '1', origin: window.location.origin,
})
return `${YT_ORIGIN}/embed/${id}?${q}`
}
type Func = 'playVideo' | 'pauseVideo' | 'seekTo' | 'mute' | 'unMute'
/** 이미 띄운 플레이어에 명령 (IFrame API 메시지) */
function command(frame: HTMLIFrameElement | null | undefined, func: Func, args: unknown[] = []) {
frame?.contentWindow?.postMessage(JSON.stringify({ event: 'command', func, args }), YT_ORIGIN)
}
const PLAYING = 1
// 마우스로 이만큼 끌면 다음·이전 영상으로 넘긴다
const SWIPE_PX = 30
/** 화면에 보이는 동안만 true */
function useVisible<T extends Element>(threshold = 0.5) {
const [el, ref] = useState<T | null>(null)
const [visible, setVisible] = useState(false)
useEffect(() => {
if (!el) return
const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold })
io.observe(el)
return () => io.disconnect()
}, [el, threshold])
return [ref, visible] as const
}
/** 오늘 화면 히어로 아래 쇼츠 줄: 첫 카드만 소리 없이 재생, 누르면 쇼츠 페이지(/shorts/영상ID)에서 위아래로 넘겨 본다 */
export function ShortsRail() {
const q = useQuery(listShortsOptions())
const items = q.data?.items ?? []
const [ref, visible] = useVisible<HTMLElement>()
if (q.isPending) {
return (
<section aria-hidden="true">
<SkelRail>
{[0, 1, 2, 3].map((i) => (
<Skel key={i} className="aspect-[9/16] w-[120px] rounded-xl" />
))}
</SkelRail>
</section>
)
}
if (!items.length) return null
return (
<section ref={ref} aria-label="날씨각 쇼츠">
<Rail label="쇼츠 목록">
{items.map((s, i) => (
<ShortCard key={s.id} s={s} playing={i === 0 && visible} />
))}
</Rail>
</section>
)
}
function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) {
return (
<Link to={`/shorts/${s.id}`} aria-label={`${s.title} 보기`} className="relative block aspect-[9/16] w-[120px] cursor-pointer overflow-hidden rounded-xl bg-[#1d2233] p-0 text-left text-white">
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" loading="lazy" className="absolute inset-0 size-full object-cover" />
{playing && (
<iframe
src={embed(s.id)}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
tabIndex={-1}
className="pointer-events-none absolute top-1/2 left-1/2 border-0"
style={{ width: PLAYER_W, height: (PLAYER_W * 16) / 9, transform: `translate(-50%, -50%) scale(${SCALE})` }}
/>
)}
<span className="b-keep-bg absolute inset-0 bg-[linear-gradient(180deg,transparent_55%,rgba(0,0,0,.65))]" aria-hidden="true" />
<span className="absolute inset-x-2 bottom-2 line-clamp-3 text-[12px] leading-[1.3] font-bold">{s.title}</span>
</Link>
)
}
/** 쇼츠 페이지(/shorts/영상ID): 그 영상부터 위아래로 넘겨 보고, 넘기면 주소도 그 영상으로 바뀌어 그대로 공유할 수 있다 */
export function ShortsPage() {
const { id } = useParams()
const navigate = useNavigate()
const q = useQuery(listShortsOptions())
// 처음 들어온 영상만 시작점으로 쓴다 (넘기며 주소가 바뀌어도 다시 맞추지 않는다)
const [firstId] = useState(id)
const listed = q.data?.items ?? []
const items = firstId && listed.length && !listed.some((s) => s.id === firstId) ? [{ id: firstId, title: '' }, ...listed] : listed
const start = Math.max(0, items.findIndex((s) => s.id === firstId))
// 앱 안에서 들어왔으면 뒤로, 링크로 바로 들어왔으면 오늘 화면으로
const close = () => ((window.history.state as { idx?: number } | null)?.idx ? navigate(-1) : navigate('/', { replace: true }))
if (!items.length) return <div className="fixed inset-0 z-[70] bg-[#1d2233]" aria-busy={q.isPending} />
return <ShortsViewer items={items} start={start} onClose={close} onAt={(s) => navigate(`/shorts/${s.id}`, { replace: true })} />
}
/**
* 처음 열 때·넘길 때 검은 화면이 보이지 않게, 첫 장면을 받을 때까지는 표지를 보이고 앞뒤 영상도 소리 없이 틀어 첫 장면을 받아 둔 뒤 멈춰 두고, 보이는 것만 처음부터 재생한다
*/
function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; start: number; onClose: () => void; onAt: (s: ShortItem) => void }) {
const list = useRef<HTMLDivElement>(null)
const [at, setAt] = useState(start)
const [sound, setSound] = useState(false)
const tabH = useTabBarHeight()
// 첫 장면을 받은 플레이어. 그 전엔 플레이어의 검은 화면 대신 표지를 보인다
const [ready, setReady] = useState<ReadonlySet<number>>(new Set())
const frames = useRef(new Map<number, HTMLIFrameElement>())
const atRef = useRef(start)
const soundRef = useRef(false)
// 누르기로 멈춘 상태. 다른 영상으로 넘어가면 다시 재생 중으로
const paused = useRef(false)
// 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다
const startRef = useRef(start)
useEffect(() => {
// scrollIntoView 는 바깥 칸까지 굴려 버튼 줄이 헤더 밑으로 숨으므로 목록만 옮긴다
const box = list.current
if (box) box.scrollTop = box.clientHeight * startRef.current
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
return () => {
root.style.overflow = before
}
}, [])
const onEscape = useEffectEvent((e: KeyboardEvent) => e.key === 'Escape' && onClose())
useEffect(() => {
window.addEventListener('keydown', onEscape)
return () => window.removeEventListener('keydown', onEscape)
}, [])
useEffect(() => {
const box = list.current
if (!box) return
const io = new IntersectionObserver(
(entries) => {
for (const e of entries) if (e.isIntersecting) setAt(Number((e.target as HTMLElement).dataset.i))
},
{ root: box, threshold: 0.6 },
)
for (const c of box.children) io.observe(c)
return () => io.disconnect()
}, [])
// 미리 띄운 영상이 재생되기 시작하면(첫 장면을 받음) 보이는 영상이 아닐 때 멈추고 처음으로
useEffect(() => {
const onMessage = (e: MessageEvent) => {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string') return
let msg: { info?: { playerState?: number } }
try {
msg = JSON.parse(e.data)
} catch {
return
}
if (msg.info?.playerState !== PLAYING) return
for (const [i, f] of frames.current) {
if (f.contentWindow !== e.source) continue
setReady((r) => (r.has(i) ? r : new Set(r).add(i)))
if (i === atRef.current) continue
command(f, 'pauseVideo')
command(f, 'seekTo', [0, true])
}
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [])
const moved = useEffectEvent((s: ShortItem) => onAt(s))
useEffect(() => {
if (atRef.current !== at) moved(items[at])
atRef.current = at
paused.current = false
for (const [i, f] of frames.current) {
if (i === at) {
command(f, soundRef.current ? 'unMute' : 'mute')
command(f, 'playVideo')
} else {
command(f, 'pauseVideo')
command(f, 'mute')
}
}
}, [at, items])
// 마우스로도 끌어 넘긴다: 영상 위는 유튜브 iframe 이 마우스를 가져가서, 그 위에 투명한 판을 깔고 끈 만큼 목록을 옮긴다.
// 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 재생·일시정지
const drag = useRef<{ y: number; top: number; moved: boolean } | null>(null)
const lastPointer = useRef('')
const [dragging, setDragging] = useState(false)
const togglePause = () => {
paused.current = !paused.current
command(frames.current.get(atRef.current), paused.current ? 'pauseVideo' : 'playVideo')
}
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
lastPointer.current = e.pointerType
const box = list.current
if (e.pointerType !== 'mouse' || !box) return
e.currentTarget.setPointerCapture(e.pointerId)
drag.current = { y: e.clientY, top: box.scrollTop, moved: false }
setDragging(true)
}
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current
const box = list.current
if (!d || !box) return
const dy = e.clientY - d.y
if (Math.abs(dy) > 6) d.moved = true
box.scrollTop = d.top - dy
}
const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const d = drag.current
const box = list.current
drag.current = null
setDragging(false)
if (!d || !box) return
if (!d.moved) return togglePause()
// 30px 만 끌어도 다음·이전 영상으로, 그보다 덜 끌면 제자리로
const h = box.clientHeight
const dy = e.clientY - d.y
const base = Math.round(d.top / h)
const target = Math.min(items.length - 1, Math.max(0, base + (dy < -SWIPE_PX ? 1 : dy > SWIPE_PX ? -1 : 0)))
box.scrollTo({ top: target * h, behavior: 'smooth' })
}
const toggleSound = () => {
const on = !sound
soundRef.current = on
setSound(on)
command(frames.current.get(at), on ? 'unMute' : 'mute')
}
return (
// 헤더·탭 바는 그대로 두고 그 사이를 채운다. 흐린 배경은 반투명 헤더·탭 바 뒤까지 깐다
<div
role="region"
aria-label="날씨각 쇼츠"
className="fixed inset-0 flex flex-col overflow-hidden bg-[#1d2233] pt-[calc(54px+env(safe-area-inset-top,0px))] pb-(--shorts-tab) text-white"
style={{ '--shorts-tab': `${tabH}px` } as CSSProperties}
>
{/* 배경: 지금 영상 표지를 크게 흐려 깔아 영상 색이 번져 보이게 */}
<img
key={items[at].id}
src={`https://i.ytimg.com/vi/${items[at].id}/hqdefault.jpg`}
alt=""
aria-hidden="true"
className="absolute inset-0 size-full scale-125 object-cover opacity-70 blur-3xl"
/>
<div className="absolute inset-0 bg-black/35" aria-hidden="true" />
<div className="relative mx-auto flex h-12 w-full max-w-[440px] shrink-0 items-center justify-between px-3">
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-xl text-white', TAP44)}>
×
</button>
<button type="button" onClick={toggleSound} aria-pressed={sound} className="h-9 cursor-pointer rounded-full bg-white/15 px-3.5 text-[13px] font-bold text-white">
{sound ? '소리 끄기' : '소리 켜기'}
</button>
</div>
<div ref={list} className={cx('relative min-h-0 flex-1 overflow-y-auto [scrollbar-width:none]', !dragging && 'snap-y snap-mandatory')}>
{items.map((s, i) => (
<div key={s.id} data-i={i} className="relative grid h-full snap-start place-items-center">
<div className="relative" style={FIT}>
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" className="absolute inset-0 size-full object-cover" />
{Math.abs(i - at) <= 1 && (
<iframe
ref={(f) => {
if (f) frames.current.set(i, f)
else frames.current.delete(i)
}}
src={embed(s.id)}
title={s.title}
allow="autoplay; encrypted-media; picture-in-picture"
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => {
e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)
// 앞뒤 밖으로 밀려나 내려갔다 다시 뜬 플레이어는 첫 장면을 새로 받을 때까지 다시 숨긴다
setReady((r) => {
if (!r.has(i)) return r
const next = new Set(r)
next.delete(i)
return next
})
}}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', !ready.has(i) && 'opacity-0')}
/>
)}
<div
aria-hidden="true"
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={() => {
drag.current = null
setDragging(false)
}}
onClick={() => lastPointer.current !== 'mouse' && togglePause()}
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab')}
/>
</div>
</div>
))}
</div>
</div>
)
}
+2
View File
@@ -24,6 +24,7 @@ import { MyGakRow } from './myGak'
import { fromShare } from './myGakState' import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post' import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike, type PinnedKey } from './pinnedLike' import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { ShortsRail } from './Shorts'
import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk' import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk'
import { topicName, useTalkGroups } from './talkState' import { topicName, useTalkGroups } from './talkState'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
@@ -639,6 +640,7 @@ export function TodayPage() {
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다 // 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}> <section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} /> <Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<ShortsRail />
<FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} /> <FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} />
{mine.map((t) => ( {mine.map((t) => (
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} /> <TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
+3 -2
View File
@@ -2,9 +2,10 @@ type P = { className?: string }
const line = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' } as const const line = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' } as const
// 좋아요·댓글·보내기 세 아이콘이 나란히 놓일 때 크기가 같아 보이게: 하트는 원래 그림이 작아 10% 키우고(보이는 칸을 좁힘), 보내기는 커서 5% 줄인다
export function HeartIcon({ className }: P) { export function HeartIcon({ className }: P) {
return ( return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true"> <svg viewBox="1.1 2.75 21.8 21.8" className={className} aria-hidden="true">
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" /> <path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
</svg> </svg>
) )
@@ -20,7 +21,7 @@ export function CommentIcon({ className }: P) {
export function SendIcon({ className }: P) { export function SendIcon({ className }: P) {
return ( return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true"> <svg viewBox="-0.65 -0.65 25.3 25.3" className={className} aria-hidden="true">
<path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" /> <path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
</svg> </svg>
) )