Compare commits

...
6 Commits
92 changed files with 5834 additions and 272 deletions

No files matched your search

+1
View File
@@ -15,6 +15,7 @@ venv/
# 생성물: python backend/scripts/export_openapi.py 로 다시 만든다
backend/openapi.json
backend/uploads/
# 도구 캐시·설정 (impeccable 디자인 도구)
.impeccable/
+35
View File
@@ -15,6 +15,33 @@
| [x] | 노을 판정 확인 방법·SEO 방식 — 추천안을 아래 [결정 필요] 행에 정리 | 출시 전 | |
| [ ] | `release/launch-1008` → main 병합, 킹서버 배포, 시드 재적재·`feed:*` 캐시 삭제, 운영 JWT 비밀키 교체 (운영 영향, 확인 받고) | 출시 | `deploy.sh`, `backend/scripts/load_seed.py` |
## 월요일 논의 (받은 피드백)
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [ ] | **[결정 필요]** 사용자 포스팅(인스타식) — 지금 포스트는 스케줄러가 만든 것만 있음. 정할 것: 올릴 수 있는 것(사진·글·각 점수 첨부), 로그인 필수 여부, 피드 노출 위치·순서, 신고·숨김, 사진 저장소 | 피드백. 기존 '커뮤니티' 행과 합쳐 논의 | `backend/services/feed_service.py`, `backend/services/reaction_service.py` |
| [ ] | **[결정 필요]** 로그인 없이 좋아요·댓글 — 지금은 좋아요·댓글·댓글 좋아요 모두 로그인 필수, 댓글 보기만 비로그인 가능. 정할 것: 중복 좋아요 막는 기준(기기 ID·IP), 비로그인 댓글 이름 표시(익명 n), 지우기 권한, 도배 방지 | 피드백 | `backend/router/v1/reaction/reaction.py:30`, `:71`, `:87` |
| [ ] | **[결정 필요]** 로그인하면 더 되는 것 정의 — 지금 로그인 전용은 저장(북마크)·닉네임·내 정보뿐. 위 두 건이 정해지면 후보: 포스팅, 내 글·댓글 모아 보기, 지역 기억(기기 바뀌어도), 알림 | 피드백 | `backend/router/v1/auth/account.py`, `backend/router/v1/reaction/reaction.py:40` |
## 10/20 회의 (최미나 담당, `docs/meetings/2026-10-20.md`)
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [x] | 오늘의 각을 일반 포스트 크기 카드로 + 공유 (금일 핵심) — 순위 5개 카드, 히어로도 포스트 틀, 보내기만 있음(좋아요·댓글은 서버에 포스트로 저장해야 붙음), TOP 5 띠 뺌 | 10/20 회의 결정 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/Sheets.tsx` |
| [ ] | '+' 버튼 포스팅 → 오늘 피드에 섞기. 이야기 탭 없앰, 피드 위 글쓰기 칸 상시, 사람 글은 운영 포스트 3개마다 1개(방금 쓴 글은 글쓰기 칸 아래). 남은 것: 이미지 올리기, 노출 방식 대표 보고(보고서 https://claude.ai/artifact/A7ELGoAy17cnZXzhuvdF5b 추천은 캐러셀) | 10/20 회의 결정 | `frontend/src/b/talk.tsx`, `frontend/src/b/TodayPage.tsx` |
| [x] | 피드 순서: 히어로 → 오늘의 각 → 포스트. 주말 날씨·행사·노을 앞으로, 각·공기·자외선·상식 뒤로 | 10/20 회의 | `backend/services/feed_service.py` |
| [ ] | 시간대 지정 각(야장·별보기)을 시간 밖에도 뒤쪽에 노출, 억새각 노출 조건 확인 | 10/20 회의 (담당 김성경 확인 필요) | `backend/services/index_service.py`, `backend/seed/index_definition.json` |
| [ ] | 단풍 지도·단풍 포스트, 새 각 — 야구각 문장(숫자 뺌)만 반영. 농구·배구·제철 수산물각 초안은 보류(scratchpad `new_gak_draft.json`) | 10/20 회의 | `backend/seed/index_definition.json`, `backend/seed/article.json` |
| [x] | 불쾌지수 항상 표시 | 10/20 회의 결정 (10/8도 결정) | `backend/services/hero_stats.py:70` |
| [x] | 나만의 각을 '이름+조건(기온·비·바람·미세먼지·습도·시간대 수치) 저장'으로 바꿈 — 섞기 방식 대체, 점수는 서버가 그 동네 예보로 계산(조건에서 멀수록 깎기), 받은 링크에 조건을 담아 친구 동네 점수로. 피드에 올려 좋아요는 아직 | 10/20 회의 결정 (조합 방식 대체) | `frontend/src/b/myGak.tsx` |
| [ ] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글 로그인 여부 확인 필요 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` |
| [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` |
| [ ] | 사람 글 사진 올리기 — 보여 주기(talk.image)는 됨, 올리기는 패키지 설치 확인 후(python-multipart·Pillow, 위치 정보 지우기) | 10/20 회의 결정 | `backend/router/v1/talk/talk.py`, `frontend/src/b/talk.tsx` |
| [ ] | 날씨 타로·오늘 날씨 코디 기획 (옷차림 [보류] 행과 합침) | 10/20 회의 | |
| [ ] | **[결정 필요]** 피드 각 카드에서 빨래각 같은 평이한 각 빼기 — 피드 각 3개는 전체 순위로 골라 빨래각(priority 1)이 들어감. priority를 낮추면 히어로·각 탭 순위도 바뀜. priority 조정 vs 피드에선 is_fun 각 먼저 | 피드 순서 작업 중 발견 | `backend/seed/index_definition.json`, `backend/services/feed_service.py` |
| [ ] | 오늘의 각 카드 순위와 점수 순서가 다름(1위 83점, 2위 97점) — 순위에 중요도를 섞어서. 카드로 보이니 어색함 | 카드화 중 발견 | `backend/services/index_service.py` |
| [ ] | 테스트 실패 2건: `test_feed.py::test_feed_assembles_hero_stories_posts_and_bands`(각 57개, 기대 40 — 커밋 전 각 추가 영향), `test_weather_today.py:60`(날짜 따라 18시 아이콘 moon) | 피드 순서 작업 중 발견 | `backend/tests/` |
## 진행 순서
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
@@ -120,6 +147,9 @@
| [x] | 히어로 두 칸을 상황별로 고름(비→미세먼지→자외선→일교차→체감→불쾌지수, 모자라면 기본값), 아이콘·색도 상태별 (시안 A, 사용자 결정). 히어로 내용 전체 다시 보기 — 아이콘이 뜻과 안 맞음: 불쾌지수에 온도계(불쾌지수는 기온+습도), '지금 비'는 비가 안 와도 우산. 칸마다 무엇을 보여줄지(불쾌지수가 필요한지 포함)부터 다시 정하기 | 사용자 지적 | `frontend/src/b/TodayPage.tsx` (`HeroStat`) |
| [x] | 검색 노출 1단계: 메타는 `index.html` 하나로 유지 + canonical, `robots.txt`·`sitemap.xml`(메인 한 줄) 추가 — 탭별 HTML로 나누는 안은 효과(탭별 공유 미리보기·탭별 색인)가 작아 보류. 도메인 `weather.o2o.kr` 고정이라 바뀌면 두 파일도 수정 | 10/8 논의 | `frontend/index.html`, `frontend/public/robots.txt`, `frontend/public/sitemap.xml` |
| [ ] | **[보류]** AEO·일반 검색어 유입 — 본문이 HTML에 없어 네이버 Yeti·AI 크롤러(GPTBot 등)는 메타만 읽고, 일반 검색어("세차하기 좋은 날씨" 등)는 메타만으로 순위에 못 듦. 지금 탭 내용은 지역별·매일 바뀌는 값이라 색인돼도 금방 틀림. 하려면 검색어용 페이지(각 기준·월별 노을 시간·노을 명소·계절 글·월별 행사)를 새로 만들어야 함 → 기획 결정 필요. 계절 이야기 글은 지역 무관이라 글마다 주소만 붙이면 바로 후보 | 10/8 논의 | [검색 유입 기획](https://claude.ai/artifact/SKz9SipYyguERGF8weUpZs), [검색어 리서치](https://claude.ai/artifact/Eu5ax3DbR9SdnhKdMRzE3p) |
| [ ] | 구로 나뉜 13개 시의 구마다 자기 주소(`/today/gyeonggi/seongnam/bundang`, 39장) — 운영 반영(`96cbd19`, 10/20). 남은 것: 서치 콘솔·서치어드바이저에 sitemap 다시 제출 | 구글 '분당구 오늘 날씨' 상위는 모두 구 단위 페이지, 우리는 성남시 한 장에 묶여 분당구 주소가 없었음 | `backend/scripts/gen_region_pages.py`, `frontend/vite.config.ts`, `frontend/nginx.conf`, `backend/router/v1/seo/seo.py` |
| [ ] | **[보류]** 날씨별 옷차림 콘텐츠 — 후보: ① `/outfit` 기온별 옷차림 고정 페이지 ② 지역 페이지·오늘 탭에 '오늘 옷차림' 한 줄. 형태 미정 | 구글 트렌드 '옷차림'≈'노을'(세차의 0.8배), 네이버 자동완성 '기온별 옷차림'·'20도 옷차림'·'서울 오늘 날씨 옷차림'. 지금은 주말 탭·히어로의 '겉옷' 팁뿐 | `docs/검색어_인기_리서치.md`, `backend/services/weekend_plan.py` |
| [ ] | 서치 콘솔: 홈 URL 검사(구조화 데이터 '날씨각' 인식 확인)·재크롤링 요청, 색인 생성 보고서에서 지역 페이지 몇 장 색인됐는지 확인 / 네이버 서치어드바이저: 주요 지역 페이지 수집 요청(네이버 색인 10/235) | 사이트 이름 '에이아이오투오' 표시, 지역 페이지 색인 부족 | `docs/구글_검색_정책_리서치.md` |
| [x] | 구글 서치 콘솔·네이버 서치어드바이저에 사이트 등록, `sitemap.xml` 제출 — 배포 뒤 (둘 다 등록됨, 10/13 확인) | 등록·제출 없으면 새 도메인은 색인이 늦음 | https://search.google.com/search-console , https://searchadvisor.naver.com |
| [x] | 세션 여러 개가 같은 테스트 DB·Redis를 쓰면 서로 지움 — `TEST_DB_NAME`·`TEST_REDIS_DB`로 폴더마다 다르게 줄 수 있게 함 | 테스트 충돌 (10/7 두 번) | `backend/tests/conftest.py` |
| [x] | 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 돌아가며 고름 (사용자 결정). 피드 행사 카드(최대 3장)가 연주회로 채워짐 — 시작일이 오늘에 가까운 순이라 하루짜리 콘서트(서울 170건)가 위를 차지. 기획엔 "축제·행사"만 있고 콘서트·팝업을 어떻게 섞을지 없음. 안: 종류별 1장씩(축제·전시·팝업 우선) 또는 피드에서 콘서트 제외 | 사용자 지적 | `backend/services/week_service.py` (`events` 정렬), `backend/services/feed_service.py` (`PostType.EVENT`), `docs/피드_기획.html` |
@@ -158,3 +188,8 @@
| [ ] | **[결정 필요]** 각 순위가 점수 순이 아니라 보임 — 순위가 점수 × 중요도라 환기각 92점(하)이 5위, 골프각 89점이 3위, 빨래각 83점이 2위. 각 탭 받침대·스토리에서 높은 점수가 뒤에 있어 어색함. 점수를 순위대로 보여줄지, 중요도 가중을 줄일지 | 화면 직접 확인 중 발견 (10/12) | `backend/services/calc/index_calc.py` (`PRIORITY_WEIGHT`), `frontend/src/b/GakPage.tsx` |
| [x] | 노을 점수 29점(잿빛)인데 결론 '나가 볼 만해요' — 결론이 구름 분포만 보고 공기 보정(가시거리·습도)을 안 봤음 → 공기 보정 0.7배 미만이면 결론 한 단계 낮추고 이유에 공기 표시, '해 질 무렵(N시) 예보 기준' 표시. 운영 DB에 `sky_score.air` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 사용자 지적 (10/12, 분당구) | `backend/services/sky_service.py` (`day_verdict`, `build_plan`), `backend/services/calc/sky_score.py` (`air_note`) |
| [x] | 노을 탭 다시 짜기 → 시안 A(사용자 선택): 히어로 '오늘은 애매해요 / 18:10쯤 가장 붉어요 / 쉬운 이유', 내일 안내 바로 아래, 숫자는 '자세히', 시간표에 가장 붉을 때 — 처음 보면 '그래서 가?'에서 멈춤: 히어로 18:00이 무슨 시각인지 없음, 결론 카드가 좋은 말·나쁜 말을 섞음, 구름 %·예보 모델 수 같은 전문 용어, '가장 붉을 때'가 시간표에 없음, '내일이 더 나아요'가 맨 아래. 시안 먼저 보고 결정 | 사용자 지적 (10/12) | `frontend/src/b/SkyPage.tsx`, `backend/services/calc/sky_score.py` (`reason`) |
| [x] | 각 늘리기 53→68 — 리서치로 고른 8개(한강·놀이공원·데이트·곱슬머리·보일러·선크림·모기·테니스) + 감성 7개(효도·감사·선물·파티·게임·셀카·센치), 아이콘 15개(Codex) | 사용자 요청 (10/20, 리서치 https://claude.ai/artifact/3ZQbtGKRLVZViRRC5voBzY) | `backend/seed/index_definition.json`, `frontend/public/icons/`, `frontend/src/b/lib.ts` |
| [ ] | **[결정 필요]** 한강각·놀이공원각이 강·놀이공원 없는 동네에도 나옴 — 각을 지역별로 가려 보여 주는 기능이 없음(한강밤바람각도 같음). 서울·한강 인접 구만 보일지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json`, `backend/services/index_service.py` |
| [ ] | **[결정 필요]** 기존 각과 겹침 — 센치↔감성노래, 게임↔넷플릭스·집콕, 곱슬머리↔화장붕괴, 효도↔트로트, 셀카↔사진산책. 둘 다 둘지 합칠지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json` |
| [ ] | 감사각은 '어제보다 날씨가 크게 바뀐 날'을 못 봄 — 지금은 덥거나 춥거나 비 오면 높음. 전날 대비 기온 변화 요소를 계산에 넣을지 | 새 각 추가 중 발견 (10/20) | `backend/services/calc/index_calc.py` |
| [ ] | 테스트 2개가 날짜·시각에 따라 깨짐 — `test_feed` 스토리 수 40 고정(10월엔 계절 각이 늘어 다름, 각 추가 전 42·후 57), `test_weather_today` 7번째 칸이 시각에 따라 노을/달 | 새 각 추가 중 테스트에서 발견 (10/20) | `backend/tests/test_feed.py:64`, `backend/tests/test_weather_today.py` |
+75
View File
@@ -336,6 +336,14 @@ class PostLike(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class PostLikeAnon(Base):
__tablename__ = "post_like_anon"
post_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class PostSave(Base):
__tablename__ = "post_save"
@@ -362,3 +370,70 @@ class CommentLike(Base):
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class CommentLikeAnon(Base):
__tablename__ = "comment_like_anon"
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class MyGak(Base):
__tablename__ = "my_gak"
my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
name: Mapped[str] = mapped_column(String(12))
rule: Mapped[dict] = mapped_column(JSONB)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class Talk(Base):
__tablename__ = "talk"
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
region_code: Mapped[str] = mapped_column(String(10))
body: Mapped[str] = mapped_column(String(100))
weather: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
image: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
like_count: Mapped[int] = mapped_column(Integer, default=0)
report_count: Mapped[int] = mapped_column(Integer, default=0)
hidden: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
class TalkLike(Base):
__tablename__ = "talk_like"
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class TalkLikeAnon(Base):
__tablename__ = "talk_like_anon"
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
ip_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class TalkReport(Base):
__tablename__ = "talk_report"
talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
reason: Mapped[int] = mapped_column(SmallInteger)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
class UserBlock(Base):
__tablename__ = "user_block"
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+9
View File
@@ -19,6 +19,8 @@ class ErrorType(Enum):
EXTERNAL_API_ERROR = 2001
NOT_FOUND = 3001
INVALID_INPUT = 3002
DAILY_LIMIT = 3003 # 하루에 쓸 수 있는 수를 넘음
LINK_NOT_ALLOWED = 3004 # 글에 링크·전화번호
AUTH_REQUIRED = 4001
AUTH_FAILED = 4002
AUTH_DUPLICATE_ID = 4003
@@ -113,6 +115,13 @@ class IndexCategory(CodeEnum):
LIFE = 4
class TalkReport(CodeEnum):
ABUSE = 1 # 욕설·비하
SPAM = 2 # 광고·도배
PRIVACY = 3 # 개인정보 노출
ETC = 4
class ArticleCategory(CodeEnum):
SEASON = 1
TIP = 2
+38
View File
@@ -0,0 +1,38 @@
import hashlib
import hmac
import uuid
from dataclasses import dataclass
from typing import Optional
from fastapi import Depends, Request
from common.auth import optional_user
from common.database.model.models import User
from config.settings import settings
@dataclass(frozen=True)
class Liker:
"""좋아요를 누른 사람. 로그인했으면 user_id, 아니면 IP 해시로 한 번만 센다."""
user_id: Optional[uuid.UUID]
ip_hash: str
def client_ip(request: Request) -> str:
"""nginx 가 X-Forwarded-For 맨 끝에 붙인 접속 주소만 믿는다. 앞쪽은 클라이언트가 마음대로 넣을 수 있다."""
xff = request.headers.get("x-forwarded-for", "")
last = xff.rsplit(",", 1)[-1].strip()
if last:
return last
return request.client.host if request.client else ""
def ip_hash(ip: str) -> str:
"""IP 원문은 저장하지 않는다. 서버 비밀값으로 HMAC 한 값만 남긴다."""
if not settings.jwt_refresh_secret:
raise RuntimeError("JWT_REFRESH_SECRET is empty")
return hmac.new(settings.jwt_refresh_secret.encode(), f"like-ip:{ip}".encode(), hashlib.sha256).hexdigest()
async def liker(request: Request, user: Optional[User] = Depends(optional_user)) -> Liker:
return Liker(user_id=user.user_id if user else None, ip_hash=ip_hash(client_ip(request)))
+3
View File
@@ -34,6 +34,9 @@ class Settings(BaseSettings):
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
frontend_internal_url: str = "http://frontend"
# 사람 글 사진을 저장할 폴더 (compose 볼륨)
upload_dir: str = "uploads"
jwt_access_secret: str = ""
jwt_refresh_secret: str = ""
jwt_access_minutes: int = 60
+24
View File
@@ -0,0 +1,24 @@
import uuid
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import MyGak
class MyGakCRUD:
async def of_user(self, s: AsyncSession, user_id: uuid.UUID) -> list[MyGak]:
return list((await s.scalars(select(MyGak).where(MyGak.user_id == user_id).order_by(MyGak.my_gak_id))).all())
async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int:
return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id))
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict) -> MyGak:
row = MyGak(user_id=user_id, name=name, rule=rule)
s.add(row)
await s.flush()
return row
async def delete(self, s: AsyncSession, user_id: uuid.UUID, my_gak_id: int) -> bool:
res = await s.execute(delete(MyGak).where(MyGak.my_gak_id == my_gak_id, MyGak.user_id == user_id).returning(MyGak.my_gak_id))
return res.first() is not None
+24 -13
View File
@@ -5,17 +5,25 @@ from sqlalchemy import delete, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Comment, CommentLike, Post, PostLike, PostSave, User
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, Post, PostLike, PostLikeAnon, PostSave, User
from common.liker import Liker
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
model, keys = (member, {id_name: id_value, "user_id": who.user_id}) if who.user_id is not None else (anon, {id_name: id_value, "ip_hash": who.ip_hash})
id_col = getattr(model, id_name)
if on:
res = await s.execute(insert(model).values(**keys).on_conflict_do_nothing().returning(id_col))
else:
res = await s.execute(delete(model).where(*(getattr(model, k) == v for k, v in keys.items())).returning(id_col))
return res.first() is not None
class ReactionCRUD:
async def toggle_post_like(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, on: bool) -> int:
async def toggle_post_like(self, s: AsyncSession, post_id: int, who: Liker, on: bool) -> int:
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
if on:
res = await s.execute(insert(PostLike).values(post_id=post_id, user_id=user_id).on_conflict_do_nothing().returning(PostLike.post_id))
else:
res = await s.execute(delete(PostLike).where(PostLike.post_id == post_id, PostLike.user_id == user_id).returning(PostLike.post_id))
if res.first() is not None:
if await toggle_like_row(s, who, PostLike, PostLikeAnon, "post_id", post_id, on):
await s.execute(update(Post).where(Post.post_id == post_id).values(like_count=Post.like_count + (1 if on else -1)))
return await s.scalar(select(Post.like_count).where(Post.post_id == post_id))
@@ -34,6 +42,9 @@ class ReactionCRUD:
saved = set((await s.scalars(select(PostSave.post_id).where(PostSave.user_id == user_id, PostSave.post_id.in_(post_ids)))).all())
return liked, saved
async def anon_liked_posts(self, s: AsyncSession, ip_hash: str, post_ids: list[int]) -> set[int]:
return set((await s.scalars(select(PostLikeAnon.post_id).where(PostLikeAnon.ip_hash == ip_hash, PostLikeAnon.post_id.in_(post_ids)))).all())
async def saved_posts(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Post, PostSave]]:
stmt = select(Post, PostSave).join(PostSave, PostSave.post_id == Post.post_id).where(PostSave.user_id == user_id, Post.deleted.is_(False))
if cursor is not None:
@@ -50,6 +61,10 @@ class ReactionCRUD:
stmt = select(CommentLike.comment_id).where(CommentLike.user_id == user_id, CommentLike.comment_id.in_(comment_ids))
return set((await s.scalars(stmt)).all())
async def anon_liked_comments(self, s: AsyncSession, ip_hash: str, comment_ids: list[int]) -> set[int]:
stmt = select(CommentLikeAnon.comment_id).where(CommentLikeAnon.ip_hash == ip_hash, CommentLikeAnon.comment_id.in_(comment_ids))
return set((await s.scalars(stmt)).all())
async def add_comment(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, body: str) -> Comment:
c = Comment(post_id=post_id, user_id=user_id, body=body)
s.add(c)
@@ -68,14 +83,10 @@ class ReactionCRUD:
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
return True
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, on: bool) -> Optional[int]:
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
if exists is None:
return None
if on:
res = await s.execute(insert(CommentLike).values(comment_id=comment_id, user_id=user_id).on_conflict_do_nothing().returning(CommentLike.comment_id))
else:
res = await s.execute(delete(CommentLike).where(CommentLike.comment_id == comment_id, CommentLike.user_id == user_id).returning(CommentLike.comment_id))
if res.first() is not None:
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
+66
View File
@@ -0,0 +1,66 @@
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import delete, func, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Region, Talk, TalkLike, TalkLikeAnon, TalkReport, User, UserBlock
from common.liker import Liker
from crud.reaction_crud import toggle_like_row
class TalkCRUD:
async def page(self, s: AsyncSession, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Talk, User, Optional[str]]]:
"""최신 글부터. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다."""
stmt = (
select(Talk, User, Region.short_name)
.join(User, User.user_id == Talk.user_id)
.outerjoin(Region, Region.code == Talk.region_code)
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False))
)
if viewer is not None:
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
if cursor is not None:
stmt = stmt.where(Talk.talk_id < cursor)
return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all())
async def liked(self, s: AsyncSession, user_id: uuid.UUID, talk_ids: list[int]) -> set[int]:
return set((await s.scalars(select(TalkLike.talk_id).where(TalkLike.user_id == user_id, TalkLike.talk_id.in_(talk_ids)))).all())
async def anon_liked(self, s: AsyncSession, ip_hash: str, talk_ids: list[int]) -> set[int]:
return set((await s.scalars(select(TalkLikeAnon.talk_id).where(TalkLikeAnon.ip_hash == ip_hash, TalkLikeAnon.talk_id.in_(talk_ids)))).all())
async def count_since(self, s: AsyncSession, user_id: uuid.UUID, since: datetime) -> int:
return await s.scalar(select(func.count()).select_from(Talk).where(Talk.user_id == user_id, Talk.created_at >= since))
async def add(self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str], image: Optional[str] = None) -> Talk:
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image)
s.add(t)
await s.flush()
await s.refresh(t)
return t
async def get(self, s: AsyncSession, talk_id: int) -> Optional[Talk]:
return await s.scalar(select(Talk).where(Talk.talk_id == talk_id, Talk.deleted.is_(False)))
async def delete(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID) -> bool:
res = await s.execute(update(Talk).where(Talk.talk_id == talk_id, Talk.user_id == user_id, Talk.deleted.is_(False)).values(deleted=True).returning(Talk.talk_id))
return res.first() is not None
async def toggle_like(self, s: AsyncSession, talk_id: int, who: Liker, on: bool) -> int:
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
if await toggle_like_row(s, who, TalkLike, TalkLikeAnon, "talk_id", talk_id, on):
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(like_count=Talk.like_count + (1 if on else -1)))
return await s.scalar(select(Talk.like_count).where(Talk.talk_id == talk_id))
async def report(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, reason: int, hide_at: int) -> None:
"""한 사람은 한 번만 센다. hide_at 건이 되면 숨긴다."""
res = await s.execute(insert(TalkReport).values(talk_id=talk_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(TalkReport.talk_id))
if res.first() is None:
return
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(report_count=Talk.report_count + 1, hidden=Talk.report_count + 1 >= hide_at))
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
+72
View File
@@ -211,6 +211,14 @@ CREATE TABLE IF NOT EXISTS public.post_like (
PRIMARY KEY (post_id, user_id)
);
-- 로그인 없이 누른 좋아요. IP 원문 대신 HMAC-SHA256 해시로 한 IP 에 한 번만 센다. like_count 는 post_like 와 이 표를 합한 수
CREATE TABLE IF NOT EXISTS public.post_like_anon (
post_id BIGINT NOT NULL,
ip_hash CHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (post_id, ip_hash)
);
CREATE TABLE IF NOT EXISTS public.post_save (
post_id BIGINT NOT NULL,
user_id UUID NOT NULL,
@@ -248,6 +256,70 @@ CREATE TABLE IF NOT EXISTS public.comment_like (
PRIMARY KEY (comment_id, user_id)
);
CREATE TABLE IF NOT EXISTS public.comment_like_anon (
comment_id BIGINT NOT NULL,
ip_hash CHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (comment_id, ip_hash)
);
-- 나만의 각: 사용자가 이름과 날씨 조건(수치)을 정해 저장. 점수는 저장하지 않고 볼 때 그 동네 예보로 계산한다
CREATE TABLE IF NOT EXISTS public.my_gak (
my_gak_id BIGSERIAL PRIMARY KEY,
user_id UUID NOT NULL,
name VARCHAR(12) NOT NULL, -- 사용자가 지은 이름 (소맥각)
rule JSONB NOT NULL, -- 조건: temp [lo,hi]·rain·wind_max·air·humidity [lo,hi]·slots
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
CREATE TABLE IF NOT EXISTS public.talk (
talk_id BIGSERIAL PRIMARY KEY,
user_id UUID NOT NULL,
region_code VARCHAR(10) NOT NULL,
body VARCHAR(100) NOT NULL,
weather VARCHAR(30), -- 쓸 때 날씨 한 줄 (예: 18° 맑음)
image VARCHAR(200), -- 올린 사진 경로 (위치 정보를 지운 사본)
like_count INTEGER NOT NULL DEFAULT 0,
report_count INTEGER NOT NULL DEFAULT 0, -- 로그인한 사람의 신고만 센다
hidden BOOLEAN NOT NULL DEFAULT FALSE, -- 신고가 쌓이면 자동으로 숨김
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX IF NOT EXISTS idx_talk_list ON public.talk (talk_id DESC) WHERE deleted = FALSE AND hidden = FALSE;
CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at);
CREATE TABLE IF NOT EXISTS public.talk_like (
talk_id BIGINT NOT NULL,
user_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (talk_id, user_id)
);
CREATE TABLE IF NOT EXISTS public.talk_like_anon (
talk_id BIGINT NOT NULL,
ip_hash CHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (talk_id, ip_hash)
);
CREATE TABLE IF NOT EXISTS public.talk_report (
talk_id BIGINT NOT NULL,
user_id UUID NOT NULL,
reason SMALLINT NOT NULL, -- TalkReport: 1=욕설·비하 2=광고·도배 3=개인정보 노출 4=기타
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (talk_id, user_id)
);
-- 이 사람 글 안 보기
CREATE TABLE IF NOT EXISTS public.user_block (
user_id UUID NOT NULL,
blocked_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, blocked_id)
);
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
-- 구 목록.
+2
View File
@@ -12,3 +12,5 @@ apscheduler>=3.10,<4
pytest
python-jose[cryptography]
bcrypt
python-multipart
Pillow
+4
View File
@@ -11,11 +11,13 @@ from router.v1.auth.account import router as auth_router
from router.v1.feed.feed import router as feed_router
from router.v1.image.image import router as image_router
from router.v1.index.index import router as index_router
from router.v1.my_gak.my_gak import router as my_gak_router
from router.v1.reaction.reaction import router as reaction_router
from router.v1.region.region import router as region_router
from router.v1.season.season import router as season_router
from router.v1.seo.seo import router as seo_router
from router.v1.sky.sky import router as sky_router
from router.v1.talk.talk import router as talk_router
from router.v1.watch.watch import router as watch_router
from router.v1.weather.weather import router as weather_router
from router.v1.week.week import router as week_router
@@ -42,6 +44,8 @@ app.include_router(season_router)
app.include_router(feed_router)
app.include_router(auth_router)
app.include_router(reaction_router)
app.include_router(my_gak_router)
app.include_router(talk_router)
app.include_router(watch_router)
app.include_router(image_router)
app.include_router(seo_router)
+6 -1
View File
@@ -5,6 +5,7 @@ from fastapi import APIRouter, Depends, Path, Query
from common.auth import optional_user
from common.database.model.models import User
from common.enums import ErrorType
from common.liker import Liker, liker
from common.models.errors import error_info
from router.v1.feed.protocol import Res_Feed, Res_Post
from services.feed_service import FeedService
@@ -15,7 +16,7 @@ router = APIRouter(prefix="/v1/feed", tags=["feed"])
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
async def get_feed(
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user),
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: FeedService = Depends(), reactions: ReactionService = Depends(),
) -> Res_Feed:
err, feed = await service.feed(region)
@@ -24,10 +25,14 @@ async def get_feed(
ids = [p.post_id for p in feed.posts]
counts = await reactions.counts(ids)
liked, saved = await reactions.marks(user, ids)
# 캐시된 피드는 모두에게 같으니, 로그인 안 한 사람의 좋아요 표시는 캐시 밖에서 IP 해시로 덧붙인다
anon_liked = await reactions.anon_liked(who.ip_hash, ids) if user is None else set()
for p in feed.posts:
p.like_count, p.comment_count = counts.get(p.post_id, (p.like_count, p.comment_count))
if user is not None:
p.liked, p.saved = p.post_id in liked, p.post_id in saved
else:
p.liked = p.post_id in anon_liked
return feed
Whitespace-only changes.
+47
View File
@@ -0,0 +1,47 @@
from typing import Optional
from fastapi import APIRouter, Depends, Path
from common.auth import current_user, optional_user
from common.database.model.models import MyGak, User
from common.enums import ErrorType
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from router.v1.my_gak.protocol import MyGakData, MyGakRule, MyGakScore, Req_MyGak, Req_MyGakScore, Res_MyGak, Res_MyGakList, Res_MyGakScore
from services.my_gak_service import MyGakService
router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"])
def _data(g: MyGak) -> MyGakData:
return MyGakData(my_gak_id=g.my_gak_id, name=g.name, rule=MyGakRule(**g.rule))
@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각 목록 (로그인하지 않았으면 빈 목록)")
async def list_my_gak(user: Optional[User] = Depends(optional_user), service: MyGakService = Depends()) -> Res_MyGakList:
if user is None:
return Res_MyGakList()
err, rows = await service.mine(user)
if err is not ErrorType.SUCCESS:
return Res_MyGakList(result=error_info(err))
return Res_MyGakList(items=[_data(g) for g in rows])
@router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="이름과 날씨 조건으로 내 각 만들기")
async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak:
err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True))
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
@router.post("/score", response_model=Res_MyGakScore, response_model_exclude_none=True, summary="조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)")
async def score_my_gak(req: Req_MyGakScore, service: MyGakService = Depends()) -> Res_MyGakScore:
err, got = await service.score(req.region_code, [r.model_dump(exclude_none=True) for r in req.rules])
if err is not ErrorType.SUCCESS or got is None:
return Res_MyGakScore(result=error_info(err))
now_slot, scores = got
return Res_MyGakScore(now_slot=now_slot, scores=[MyGakScore(**x) for x in scores])
@router.delete("/{my_gak_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 각 지우기")
async def delete_my_gak(my_gak_id: int = Path(...), user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.delete(user, my_gak_id)))
+62
View File
@@ -0,0 +1,62 @@
from typing import Literal, Optional
from pydantic import Field, model_validator
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
Slot = Literal["morning", "day", "evening", "night"]
class MyGakRule(WebPacketProtocol):
temp: Optional[list[float]] = Field(None, min_length=2, max_length=2, description="체감온도 범위 [최저, 최고]° (-20~40)")
rain: Optional[Literal["dry", "wet"]] = Field(None, description="dry: 비 안 와야 / wet: 비 와야 / 없으면 상관없음")
wind_max: Optional[float] = Field(None, ge=1, le=20, description="바람 상한 m/s")
air: Optional[Literal["good", "normal"]] = Field(None, description="미세먼지 허용 단계: good 좋음까지 / normal 보통까지")
humidity: Optional[list[int]] = Field(None, min_length=2, max_length=2, description="습도 범위 [최저, 최고]%")
slots: list[Slot] = Field(default=["morning", "day", "evening", "night"], min_length=1, max_length=4, description="볼 시간대")
@model_validator(mode="after")
def _check(self) -> "MyGakRule":
if self.temp and not (-20 <= self.temp[0] < self.temp[1] <= 40):
raise ValueError("temp 는 -20~40 안에서 최저 < 최고")
if self.humidity and not (0 <= self.humidity[0] < self.humidity[1] <= 100):
raise ValueError("humidity 는 0~100 안에서 최저 < 최고")
if not (self.temp or self.rain or self.wind_max is not None or self.air or self.humidity):
raise ValueError("조건을 하나 이상 정해야 함")
return self
class MyGakData(WebPacketProtocol):
my_gak_id: int
name: str
rule: MyGakRule
class Req_MyGak(Req_WebPacketProtocol):
name: str = Field(min_length=1, max_length=12, description="내 각 이름 (끝에 '각'이 없으면 붙인다)")
rule: MyGakRule
class Res_MyGakList(Res_WebPacketProtocol):
items: list[MyGakData] = Field(default=[], description="내 각. 로그인하지 않았으면 비어 있음")
class Res_MyGak(Res_WebPacketProtocol):
item: Optional[MyGakData] = None
class Req_MyGakScore(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
rules: list[MyGakRule] = Field(min_length=1, max_length=21)
class MyGakScore(WebPacketProtocol):
score: Optional[int] = Field(None, description="지금 시간대 점수. 지금이 고른 시간대가 아니면 고른 시간대 중 가장 좋은 점수. 예보가 없으면 null")
slot: Optional[Slot] = Field(None, description="score 가 어느 시간대 점수인지")
slots: dict[str, int] = Field(default={}, description="고른 시간대별 점수 (아침·낮·저녁·밤 순)")
reasons: list[str] = Field(default=[], description="score 근거: 조건마다 그 시간대 실제 값")
class Res_MyGakScore(Res_WebPacketProtocol):
now_slot: Optional[Slot] = None
scores: list[MyGakScore] = []
+18 -16
View File
@@ -5,6 +5,7 @@ from fastapi import APIRouter, Depends, Path, Query
from common.auth import current_user, optional_user
from common.database.model.models import User
from common.enums import ErrorType, PostType
from common.liker import Liker, liker
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST
@@ -21,19 +22,19 @@ def _comment(v: CommentView) -> CommentData:
return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, created_at=c.created_at.astimezone(KST))
async def _like(post_id: int, user: User, on: bool, service: ReactionService) -> Res_PostLike:
err, count = await service.like_post(post_id, user, on)
async def _like(post_id: int, who: Liker, on: bool, service: ReactionService) -> Res_PostLike:
err, count = await service.like_post(post_id, who, on)
return Res_PostLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_PostLike(liked=on, like_count=count)
@router.post("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요")
async def like_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
return await _like(post_id, user, True, service)
@router.post("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요 (로그인 없으면 IP 당 한 번)")
async def like_post(post_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_PostLike:
return await _like(post_id, who, True, service)
@router.delete("/post/{post_id}/like", response_model=Res_PostLike, response_model_exclude_none=True, summary="좋아요 취소")
async def unlike_post(post_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_PostLike:
return await _like(post_id, user, False, service)
async def unlike_post(post_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_PostLike:
return await _like(post_id, who, False, service)
@router.post("/post/{post_id}/save", response_model=Res_PostSave, response_model_exclude_none=True, summary="저장")
@@ -59,9 +60,10 @@ async def list_saved(cursor: Optional[int] = Query(None), user: User = Depends(c
@router.get("/post/{post_id}/comment/list", response_model=Res_CommentList, response_model_exclude_none=True, summary="댓글 목록 (로그인 없이 보기)")
async def list_comments(
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), service: ReactionService = Depends()
post_id: int = Path(...), cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: ReactionService = Depends(),
) -> Res_CommentList:
err, items = await service.comments(post_id, user, cursor)
err, items = await service.comments(post_id, user, who.ip_hash, cursor)
if err is not ErrorType.SUCCESS:
return Res_CommentList(result=error_info(err))
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
@@ -78,16 +80,16 @@ async def delete_comment(comment_id: int = Path(...), user: User = Depends(curre
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, user)))
async def _clike(comment_id: int, user: User, on: bool, service: ReactionService) -> Res_CommentLike:
err, count = await service.like_comment(comment_id, user, on)
async def _clike(comment_id: int, who: Liker, on: bool, service: ReactionService) -> Res_CommentLike:
err, count = await service.like_comment(comment_id, who, on)
return Res_CommentLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_CommentLike(liked=on, like_count=count)
@router.post("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요")
async def like_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
return await _clike(comment_id, user, True, service)
@router.post("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 (로그인 없으면 IP 당 한 번)")
async def like_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
return await _clike(comment_id, who, True, service)
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
async def unlike_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
return await _clike(comment_id, user, False, service)
async def unlike_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
return await _clike(comment_id, who, False, service)
View File
Whitespace-only changes.
+51
View File
@@ -0,0 +1,51 @@
from datetime import datetime
from typing import Optional
from pydantic import Field
from common.enums import TalkReport
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
class TalkData(WebPacketProtocol):
talk_id: int
nickname: str
character: str
color: str
mood: Optional[str] = None
region_name: Optional[str] = Field(None, description="쓴 사람이 고른 동네 (성남시 분당구)")
weather: Optional[str] = Field(None, description="쓸 때 그 동네 날씨 (18° 맑음)")
body: str
image: Optional[str] = Field(None, description="올린 사진 주소")
like_count: int
liked: bool
mine: bool
created_at: datetime
class Req_Talk(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
body: str = Field(min_length=1, max_length=200, description="공백을 줄인 뒤 100자까지")
image: Optional[str] = Field(None, max_length=200, description="먼저 올린 사진 주소 (POST /v1/talk/image 결과)")
class Req_TalkReport(Req_WebPacketProtocol):
reason: TalkReport
class Res_TalkList(Res_WebPacketProtocol):
talks: list[TalkData] = []
next_cursor: Optional[int] = None
class Res_Talk(Res_WebPacketProtocol):
talk: Optional[TalkData] = None
class Res_TalkLike(Res_WebPacketProtocol):
liked: Optional[bool] = None
like_count: Optional[int] = None
class Res_TalkImage(Res_WebPacketProtocol):
image: Optional[str] = Field(None, description="글에 붙일 사진 주소")
+89
View File
@@ -0,0 +1,89 @@
from typing import Optional
import asyncio
from fastapi import APIRouter, Depends, File, HTTPException, Path, Query, UploadFile
from fastapi.responses import FileResponse
from common.auth import current_user, optional_user
from common.database.model.models import User
from common.enums import ErrorType
from common.liker import Liker, liker
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
from services.talk_service import PAGE, TalkService, TalkView
router = APIRouter(prefix="/v1/talk", tags=["talk"])
def _data(v: TalkView) -> TalkData:
t, u = v.talk, v.author
return TalkData(
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
body=t.body, image=t.image, like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
)
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국, 최신순, 로그인 없이 보기)")
async def list_talks(
cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: TalkService = Depends()
) -> Res_TalkList:
err, views = await service.page(user, who.ip_hash, cursor)
if err is not ErrorType.SUCCESS:
return Res_TalkList(result=error_info(err))
talks = [_data(v) for v in views]
return Res_TalkList(talks=talks, next_cursor=talks[-1].talk_id if len(talks) == PAGE else None)
@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)")
async def add_talk(req: Req_Talk, user: User = Depends(current_user), service: TalkService = Depends()) -> Res_Talk:
err, v = await service.add(user, req.region_code, req.body, req.image)
return Res_Talk(result=error_info(err)) if err is not ErrorType.SUCCESS or v is None else Res_Talk(talk=_data(v))
@router.post("/image", response_model=Res_TalkImage, response_model_exclude_none=True, summary="글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)")
async def upload_talk_image(file: UploadFile = File(...), user: User = Depends(current_user)) -> Res_TalkImage:
data = await file.read(MAX_BYTES + 1)
err, url = await asyncio.to_thread(save, data)
return Res_TalkImage(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkImage(image=url)
@router.get("/image/{name}", summary="올린 사진", response_class=FileResponse)
async def get_talk_image(name: str = Path(..., max_length=40)) -> FileResponse:
path = file_of(URL_PREFIX + name)
if path is None:
raise HTTPException(status_code=404)
return FileResponse(path, media_type="image/webp", headers={"Cache-Control": "public, max-age=31536000, immutable"})
@router.delete("/{talk_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 이야기 지우기")
async def delete_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.delete(user, talk_id)))
async def _like(talk_id: int, who: Liker, on: bool, service: TalkService) -> Res_TalkLike:
err, count = await service.like(who, talk_id, on)
return Res_TalkLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkLike(liked=on, like_count=count)
@router.post("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 (로그인 없으면 IP 당 한 번)")
async def like_talk(talk_id: int = Path(...), who: Liker = Depends(liker), service: TalkService = Depends()) -> Res_TalkLike:
return await _like(talk_id, who, True, service)
@router.delete("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 취소")
async def unlike_talk(talk_id: int = Path(...), who: Liker = Depends(liker), service: TalkService = Depends()) -> Res_TalkLike:
return await _like(talk_id, who, False, service)
@router.post("/{talk_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이야기 신고 (서로 다른 3명이면 숨김)")
async def report_talk(req: Req_TalkReport, talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.report(user, talk_id, req.reason)))
@router.post("/{talk_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 글 쓴 사람의 글 안 보기")
async def block_talk_author(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.block_author(user, talk_id)))
+6 -2
View File
@@ -5,7 +5,7 @@ import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from services.calc.index_calc import PRIORITY_WEIGHT # noqa: E402
from services.calc.index_calc import PRIORITY_WEIGHT, _cond # noqa: E402
SEED = os.path.join(ROOT, "seed", "index_definition.json")
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
@@ -64,12 +64,16 @@ def tim(r):
return "달이 어두울수록 좋음 (보름 20점 → 그믐 100점)"
if t == "sunset_score":
return "그날 노을 점수를 그대로 씀"
if t == "sunrise_score":
return "그날 일출 하늘 점수를 그대로 씀"
return f"고정 {r['value']}점"
def zero(z):
if z["field"] == "warning":
return f"{z['value']} 특보가 있으면"
if z["field"] not in FIELD:
return _cond(z)[2] + (f" 최대 {z['cap']}점" if "cap" in z else " 0점")
name, unit = FIELD[z["field"]]
op = "이상" if z["op"] == ">=" else "미만"
s = f"{name} {z['value']}{unit} {op}이면"
@@ -83,7 +87,7 @@ def air(r):
AX = [("temp", "기온", temp), ("rain", "비", rain), ("wind", "바람", wind), ("humidity", "습도", hum), ("air", "미세먼지", air),
("uv", "자외선", lambda r: f"자외선 {r['full']} 이하면 만점, {r['zero']} 이상이면 0점 (Open-Meteo)"),
("uv", "자외선", lambda r: f"자외선 {r['full']} {'이상이면' if r['full'] > r['zero'] else '이하면'} 만점, {r['zero']} {'이하면' if r['full'] > r['zero'] else '이상이면'} 0점 (Open-Meteo)"),
("sun", "햇빛", lambda r: f"해 난 비율 {round(r['full'] * 100)}% 이상이면 만점, {round(r['zero'] * 100)}% 이하면 0점 (Open-Meteo)"),
("view", "가시거리", lambda r: f"{r['full']}km 이상이면 만점, {r['zero']}km 이하면 0점 (Open-Meteo)"),
("time", "시간·요일", tim)]
File diff suppressed because it is too large. Load diff
+52
View File
@@ -0,0 +1,52 @@
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Literal, Optional
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS
Rain = Literal["dry", "wet"]
Air = Literal["good", "normal"]
# 미세먼지 허용 단계 → 초미세먼지(㎍/㎥) 점수 규칙. 단계 경계(좋음 15·보통 35)까지 100, 넘으면 깎는다
_AIR = {"good": {"zero": 35, "full": 15}, "normal": {"zero": 75, "full": 35}}
_WIND_LIMIT_OVER = 6 # 바람 상한에서 이만큼 더 세지면 0점
def _n(v: float) -> float:
"""근거 문구에 15.0° 대신 15° 로 나오게."""
return int(v) if float(v).is_integer() else v
@dataclass(frozen=True)
class MyRule:
"""사용자가 정한 내 각 조건. None 인 항목은 보지 않는다."""
temp: Optional[tuple[float, float]] = None # 체감온도 범위(°)
rain: Optional[Rain] = None # dry: 안 와야, wet: 와야
wind_max: Optional[float] = None # 바람 상한(m/s)
air: Optional[Air] = None # 미세먼지 허용 단계
humidity: Optional[tuple[int, int]] = None # 습도 범위(%)
slots: tuple[str, ...] = SLOTS # 볼 시간대
def axes(rule: MyRule) -> list[str]:
return [a for a, on in (("temp", rule.temp), ("rain", rule.rain), ("wind", rule.wind_max is not None), ("air", rule.air), ("humidity", rule.humidity)) if on]
def definition(rule: MyRule) -> SimpleNamespace:
"""공식 각과 같은 계산(evaluate)에 넣을 정의. 고른 조건끼리 가중치를 똑같이 나눈다."""
used = axes(rule)
share = {a: 100 // len(used) + (1 if i < 100 % len(used) else 0) for i, a in enumerate(used)} if used else {}
return SimpleNamespace(
**{f"weight_{a}": share.get(a, 0) for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")},
factor_rules={
"temp": {"type": "range", "lo": _n(rule.temp[0]), "hi": _n(rule.temp[1])} if rule.temp else {"type": "range", "lo": -50, "hi": 60},
"rain": {"dir": rule.rain or "dry"},
"wind": {"type": "calm", "ok": _n(rule.wind_max), "limit": rule.wind_max + _WIND_LIMIT_OVER} if rule.wind_max is not None else {"type": "ignore"},
"humidity": {"type": "range", "lo": rule.humidity[0], "hi": rule.humidity[1]} if rule.humidity else {"type": "ignore"},
"air": _AIR[rule.air] if rule.air else None,
"time": {"type": "fixed", "value": 100},
},
zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [],
windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
)
+8 -6
View File
@@ -76,12 +76,13 @@ def sido_of(region_code: str) -> str:
def post_scope(post_type: PostType, region_code: str) -> str:
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 앞쪽 절반 사이사이 무작위.
# 알림은 비·특보가 있을 때만 켜지니 맨 앞, 주말·노을처럼 공유할 만한 카드를 그다음, 공기·자외선·상식 같은 평이한 정보는 뒤로.
ORDER = {
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
"evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
"night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE],
"morning": [PostType.ALERT, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SUNSET, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
"day": [PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
"evening": [PostType.SUNSET, PostType.ALERT, PostType.WEEK, PostType.MOON, PostType.WEEKEND_PLAN, PostType.GAK, PostType.TOMORROW, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
"night": [PostType.TOMORROW, PostType.ALERT, PostType.MOON, PostType.WEEK, PostType.SUNSET, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
}
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
@@ -220,7 +221,8 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
if slot == "night":
rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE]
events = pool.get(PostType.EVENT, [])
gaps = sorted(random.Random(seed).sample(range(1, len(rest)), min(len(events), max(0, len(rest) - 1))), reverse=True)
front = range(1, max(1, len(rest) // 2 + 1))
gaps = sorted(random.Random(seed).sample(front, min(len(events), len(front))), reverse=True)
for gap, e in zip(gaps, reversed(events[:len(gaps)])):
rest.insert(gap, e)
return head + rest
+2 -3
View File
@@ -11,7 +11,6 @@ Tone = Literal["normal", "warn", "rain"]
UV_HIGH = 6.0
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
DISCOMFORT_MONTHS = range(6, 10) # 기상청처럼 6~9월에만. 더위 지표라 선선한 철엔 비 와도 '쾌적'으로 나온다
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
TEMP_SWING_C = 10.0
WIND_CHILL_C = 3.0
@@ -67,11 +66,11 @@ def humidity_label(h: int) -> str:
def hero_status(x: HeroInput) -> list[HeroStatItem]:
"""히어로 상태 한 줄: 습도·불쾌지수(6~9월)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
out: list[HeroStatItem] = []
if x.humidity is not None:
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
if x.discomfort is not None and x.now.month in DISCOMFORT_MONTHS:
if x.discomfort is not None:
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
if not x.after_dark and x.uv is not None:
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
+30
View File
@@ -365,6 +365,36 @@ class IndexService:
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
)
async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]:
"""공식 각이 아닌 정의(내 각)들을 그 동네 오늘 아침·낮·저녁·밤으로 계산한다. (지금 구간, 정의마다 구간별 결과)"""
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
if err is not ErrorType.SUCCESS:
return err, None
if region is None:
return ErrorType.NOT_FOUND, None
now = now_kst()
_, _, ultra = await asyncio.gather(self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), ultra_hours(region, now))
today = now.date()
start = kst_midnight(today)
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start - timedelta(days=1), start + timedelta(days=2)))
if err is not ErrorType.SUCCESS:
return err, None
if not rows:
return ErrorType.EXTERNAL_API_ERROR, None
air = await self.air_service.nearest(region)
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
ctx = Context(
day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), wind_warning=False,
pm25=air.pm25 if air else None, air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
)
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
cur = current_slot(now, sunset_at)
out = []
for d in defns:
parts = slot_results(d, today, region, by_at, {}, ctx, sunset_at, now)
out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)})
return ErrorType.SUCCESS, (shown_slot(cur), out)
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
_, _, _, warnings, ultra = await asyncio.gather(
+77
View File
@@ -0,0 +1,77 @@
import re
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import MyGak, User
from common.enums import ErrorType
from crud.my_gak_crud import MyGakCRUD
from services.calc.day_slot import SLOTS
from services.calc.my_gak_calc import MyRule, axes, definition
from services.index_service import IndexService
# 한 사람이 만들 수 있는 내 각 수
MAX_PER_USER = 20
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b|\d{3,}", re.I)
def gak_name(name: str) -> Optional[str]:
"""앞뒤 공백을 빼고 끝에 '각'을 붙인다. 링크·긴 숫자(전화번호 등)는 받지 않는다."""
name = " ".join(name.split())
if not name or _LINK.search(name):
return None
name = name if name.endswith("각") else f"{name}각"
return name if len(name) <= 12 else None
def my_rule(rule: dict) -> MyRule:
return MyRule(
temp=tuple(rule["temp"]) if rule.get("temp") else None, rain=rule.get("rain"), wind_max=rule.get("wind_max"), air=rule.get("air"),
humidity=tuple(rule["humidity"]) if rule.get("humidity") else None, slots=tuple(s for s in SLOTS if s in (rule.get("slots") or SLOTS)),
)
class MyGakService:
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexService = Depends(IndexService)) -> None:
self.crud, self.index = crud, index
async def mine(self, user: User) -> tuple[ErrorType, list[MyGak]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
return err, rows or []
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]:
name = gak_name(name)
if name is None:
return ErrorType.INVALID_INPUT, None
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count(s, user.user_id))
if err is not ErrorType.SUCCESS:
return err, None
if n >= MAX_PER_USER:
return ErrorType.INVALID_INPUT, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule))
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]:
"""조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수."""
mine = [my_rule(r) for r in rules]
err, got = await self.index.custom(region_code, [definition(r) for r in mine])
if err is not ErrorType.SUCCESS or got is None:
return err, None
now_slot, parts = got
out = []
for r, p in zip(mine, parts):
picked = {k: v for k, v in p.items() if k in r.slots}
key = now_slot if now_slot in picked else max(picked, key=lambda k: picked[k].score, default=None)
res = picked.get(key) if key else None
out.append({
"score": res.score if res else None, "slot": key if res else None,
"slots": {k: v.score for k, v in picked.items()},
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
})
return ErrorType.SUCCESS, (now_slot, out)
+16 -6
View File
@@ -7,6 +7,7 @@ from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Comment, Post, User
from common.enums import ErrorType
from common.liker import Liker
from crud.feed_crud import FeedCRUD
from crud.reaction_crud import ReactionCRUD
@@ -41,11 +42,11 @@ class ReactionService:
return err
return ErrorType.SUCCESS if post is not None else ErrorType.NOT_FOUND
async def like_post(self, post_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
async def like_post(self, post_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, user.user_id, on))
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
err = await self._post_exists(post_id)
@@ -60,6 +61,12 @@ class ReactionService:
err, marks = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.my_marks(s, user.user_id, post_ids))
return marks if err is ErrorType.SUCCESS else (set(), set())
async def anon_liked(self, ip_hash: str, post_ids: list[int]) -> set[int]:
if not post_ids:
return set()
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_posts(s, ip_hash, post_ids))
return liked if err is ErrorType.SUCCESS else set()
async def counts(self, post_ids: list[int]) -> dict[int, tuple[int, int]]:
"""피드는 캐시돼 있어서 좋아요·댓글 수는 매번 DB 에서 덮어쓴다."""
if not post_ids:
@@ -71,13 +78,16 @@ class ReactionService:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.saved_posts(s, user.user_id, cursor, PAGE))
return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []]
async def comments(self, post_id: int, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
ids = [c.comment_id for c, *_ in rows]
if user is not None and rows:
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, [c.comment_id for c, *_ in rows]))
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, ids))
elif rows:
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids))
return ErrorType.SUCCESS, [
CommentView(comment=c, nickname=n, character=ch, color=co, mood=mo, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id)
for c, n, ch, co, mo in rows
@@ -99,8 +109,8 @@ class ReactionService:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
async def like_comment(self, comment_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, user.user_id, on))
async def like_comment(self, comment_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, who, on))
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
+45
View File
@@ -0,0 +1,45 @@
import io
import os
import re
import uuid
from typing import Optional
from PIL import Image, ImageOps, UnidentifiedImageError
from config.settings import settings
from common.enums import ErrorType
MAX_BYTES = 10 * 1024 * 1024 # 올릴 수 있는 원본 크기
MAX_SIDE = 1080 # 긴 변을 이만큼으로 줄인다
URL_PREFIX = "/v1/talk/image/"
_NAME = re.compile(r"^[0-9a-f]{32}\.webp$")
def folder() -> str:
path = os.path.join(settings.upload_dir, "talk")
os.makedirs(path, exist_ok=True)
return path
def file_of(url: str) -> Optional[str]:
"""올린 사진 주소 → 저장된 파일 경로. 우리가 만든 이름이 아니거나 파일이 없으면 None."""
name = url.removeprefix(URL_PREFIX)
if not url.startswith(URL_PREFIX) or not _NAME.match(name):
return None
path = os.path.join(folder(), name)
return path if os.path.isfile(path) else None
def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
"""사진을 다시 그려 저장한다. 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
if len(data) > MAX_BYTES:
return ErrorType.INVALID_INPUT, None
try:
with Image.open(io.BytesIO(data)) as src:
img = ImageOps.exif_transpose(src).convert("RGB")
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
return ErrorType.INVALID_INPUT, None
img.thumbnail((MAX_SIDE, MAX_SIDE))
name = f"{uuid.uuid4().hex}.webp"
img.save(os.path.join(folder(), name), "WEBP", quality=82)
return ErrorType.SUCCESS, URL_PREFIX + name
+137
View File
@@ -0,0 +1,137 @@
import re
from dataclasses import dataclass
from datetime import timedelta
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Talk, User, WeatherHourly
from common.enums import ErrorType, RainType, Sky, TalkReport
from common.liker import Liker
from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.talk_crud import TalkCRUD
from crud.weather_crud import WeatherCRUD
from services.talk_image import file_of
BODY_MAX = 100
DAILY_MAX = 5
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
HIDE_AT = 3
PAGE = 20
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
_PHONE = re.compile(r"0\d{1,2}[-.\s]?\d{3,4}[-.\s]?\d{4}")
_SKY = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
_RAIN = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
def weather_line(row: Optional[WeatherHourly]) -> Optional[str]:
"""글에 붙일 그때 날씨: 18° 맑음 / 12° 비."""
if row is None:
return None
rain = RainType(row.rain_type)
word = _RAIN.get(rain) or _SKY.get(Sky(row.sky), "")
return f"{round(float(row.temp_c))}° {word}".strip()
@dataclass
class TalkView:
talk: Talk
author: User
region_name: Optional[str]
liked: bool
mine: bool
class TalkService:
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
self.crud, self.regions, self.weather = crud, regions, weather
async def page(self, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView]]:
viewer = user.user_id if user else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
if rows:
ids = [t.talk_id for t, *_ in rows]
if user is not None:
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
else:
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
if err is not ErrorType.SUCCESS:
return err, []
return ErrorType.SUCCESS, [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows]
async def _weather_now(self, region_code: str) -> Optional[str]:
"""지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다."""
now = now_kst()
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region_code, now - timedelta(hours=1), now + timedelta(hours=2)))
if err is not ErrorType.SUCCESS or not rows:
return None
return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now)))
async def add(self, user: User, region_code: str, body: str, image: Optional[str] = None) -> tuple[ErrorType, Optional[TalkView]]:
body = " ".join(body.split())
if not body or len(body) > BODY_MAX:
return ErrorType.INVALID_INPUT, None
if image is not None and file_of(image) is None:
return ErrorType.INVALID_INPUT, None
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
if err is not ErrorType.SUCCESS:
return err, None
if region is None:
return ErrorType.INVALID_INPUT, None
today = kst_midnight(now_kst().date())
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count_since(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
if n >= DAILY_MAX:
return ErrorType.DAILY_LIMIT, None
weather = await self._weather_now(region_code)
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image))
if err is not ErrorType.SUCCESS or t is None:
return err, None
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
async def delete(self, user: User, talk_id: int) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, talk_id, user.user_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
async def _talk(self, talk_id: int) -> tuple[ErrorType, Optional[Talk]]:
err, t = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, talk_id))
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.SUCCESS, t) if t is not None else (ErrorType.NOT_FOUND, None)
async def like(self, who: Liker, talk_id: int, on: bool) -> tuple[ErrorType, Optional[int]]:
err, _ = await self._talk(talk_id)
if err is not ErrorType.SUCCESS:
return err, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_like(s, talk_id, who, on))
async def report(self, user: User, talk_id: int, reason: TalkReport) -> ErrorType:
err, t = await self._talk(talk_id)
if err is not ErrorType.SUCCESS or t is None:
return err
if t.user_id == user.user_id:
return ErrorType.INVALID_INPUT
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.report(s, talk_id, user.user_id, reason.value, HIDE_AT))
return err
async def block_author(self, user: User, talk_id: int) -> ErrorType:
err, t = await self._talk(talk_id)
if err is not ErrorType.SUCCESS or t is None:
return err
if t.user_id == user.user_id:
return ErrorType.INVALID_INPUT
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.block(s, user.user_id, t.user_id))
return err
+1 -1
View File
@@ -43,7 +43,7 @@ def anyio_backend():
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users",
)
+87
View File
@@ -0,0 +1,87 @@
import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
REGION = "1144000000"
IP_A = {"X-Forwarded-For": "203.0.113.10"}
IP_B = {"X-Forwarded-For": "203.0.113.20"}
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
return {"Authorization": f"Bearer {body['access_token']}"}
@pytest.mark.anyio
async def test_anon_post_like_counts_once_per_ip(offline):
async with client() as c:
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
url = f"/v1/reaction/post/{post_id}/like"
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
h = await _login(c, "anon_like_01")
assert (await c.post(url, headers={**h, **IP_A})).json()["like_count"] == 3
feed_a = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json()
p = next(x for x in feed_a["posts"] if x["post_id"] == post_id)
assert p["liked"] is True and p["like_count"] == 3 and "saved" not in p
other = (await c.get("/v1/feed", params={"region": REGION}, headers={"X-Forwarded-For": "203.0.113.30"})).json()
assert next(x for x in other["posts"] if x["post_id"] == post_id)["liked"] is False
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
@pytest.mark.anyio
async def test_only_last_forwarded_ip_counts(offline):
"""클라이언트가 X-Forwarded-For 앞쪽을 바꿔도 nginx 가 붙인 마지막 주소가 같으면 같은 사람이다."""
async with client() as c:
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
url = f"/v1/reaction/post/{post_id}/like"
assert (await c.post(url, headers={"X-Forwarded-For": "1.1.1.1, 203.0.113.10"})).json()["like_count"] == 1
assert (await c.post(url, headers={"X-Forwarded-For": "2.2.2.2, 203.0.113.10"})).json()["like_count"] == 1
@pytest.mark.anyio
async def test_anon_comment_like(offline):
async with client() as c:
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
h = await _login(c, "anon_like_02")
comment_id = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "맑아요"})).json()["comment"]["comment_id"]
url = f"/v1/reaction/comment/{comment_id}/like"
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
assert (await c.post(url, headers=h)).json()["like_count"] == 3
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=IP_A)).json()["comments"]
assert listed[0]["liked"] is True
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["comments"]
assert listed[0]["liked"] is False
assert (await c.delete(url, headers=IP_B)).json()["like_count"] == 2
@pytest.mark.anyio
async def test_anon_talk_like():
async with client() as c:
h = await _login(c, "anon_like_03")
talk_id = (await c.post("/v1/talk", json={"region_code": REGION, "body": "바람 불어요"}, headers=h)).json()["talk"]["talk_id"]
url = f"/v1/talk/{talk_id}/like"
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
assert (await c.post(url, headers=h)).json()["like_count"] == 3
talks = (await c.get("/v1/talk/list", headers=IP_A)).json()["talks"]
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is True
talks = (await c.get("/v1/talk/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["talks"]
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is False
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
+2 -2
View File
@@ -50,11 +50,11 @@ async def test_signup_rejects_bad_input():
@pytest.mark.anyio
async def test_reactions_require_login_and_update_feed(offline):
async def test_comment_requires_login_and_reactions_update_feed(offline):
async with client() as c:
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
post_id = feed["posts"][0]["post_id"]
assert (await c.post(f"/v1/reaction/post/{post_id}/like")).status_code == 401
assert (await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "안녕"})).status_code == 401
token = (await _signup(c))["access_token"]
h = {"Authorization": f"Bearer {token}"}
+21
View File
@@ -151,6 +151,27 @@ def test_arrange_orders_by_slot_and_keeps_same_types_apart():
assert night[:3] == [PostType.ALERT, PostType.WEATHER, PostType.TOMORROW] and night[-1] is PostType.QUOTE
def test_arrange_puts_shareable_cards_before_plain_info():
"""주말·노을·행사는 앞쪽 절반, 공기·자외선·상식은 각 뒤로."""
from datetime import datetime
from common.utils.kma_time import KST
from services.feed_service import arrange
sunset = datetime(2026, 10, 1, 18, 10, tzinfo=KST)
cards = [_card(t, n) for n, t in enumerate([
PostType.WEATHER, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.TOMORROW, PostType.WEEK,
PostType.EVENT, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.WEEKEND_PLAN, PostType.AIR, PostType.UV, PostType.MOON,
])]
for slot, h in (("morning", 8), ("day", 13), ("evening", 17), ("evening", 19), ("night", 22)):
out = [c.post_type for c in arrange(cards, slot, datetime(2026, 10, 1, h, tzinfo=KST), sunset, False, "2026-10-01:1114000000")]
half = len(out) // 2
assert PostType.SUNSET in out[:half] and PostType.WEEK in out[:half], (slot, out)
assert all(i < half + 2 for i, t in enumerate(out) if t is PostType.EVENT), (slot, out)
first_gak = out.index(PostType.GAK)
assert all(out.index(t) > first_gak for t in (PostType.AIR, PostType.TIP) if t in out), (slot, out)
def test_arrange_scatters_up_to_three_events_same_spot_all_day():
from datetime import datetime
+2 -3
View File
@@ -60,10 +60,9 @@ def test_status_line_has_four_by_day_and_warns_only_caution():
assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")]
def test_status_line_shows_discomfort_only_june_to_september():
"""불쾌지수는 더위 지표라 10월 비 오는 날에도 '쾌적'이 나온다. 기상청처럼 6~9월에만."""
def test_status_line_shows_discomfort_all_year():
x = HeroInput(now=NOW, night=False, humidity=95, discomfort=66, uv=1.0, air=AirGrade.GOOD)
assert [s.label for s in hero_status(x)] == ["습도", "자외선", "미세먼지"]
assert [s.label for s in hero_status(x)] == ["습도", "불쾌지수", "자외선", "미세먼지"]
def test_status_line_drops_uv_at_night_and_missing_values():
+22
View File
@@ -275,6 +275,28 @@ def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
assert _seed_score(code, **bad) <= 30
@pytest.mark.parametrize("code, good, bad", [
("hangang", dict(feels=20.0, wind=1.5, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("themepark", dict(day=_WED, feels=20.0, wind=2.0), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("date", dict(feels=20.0, wind=1.5), dict(feels=5.0, prob=90, rain=RainType.RAIN, pm25=60)),
("frizz", dict(feels=28.0, prob=90, rain=RainType.RAIN, hum=90), dict(feels=12.0, hum=35)),
("boiler", dict(feels=2.0, hum=85, prob=60), dict(feels=22.0, hum=40)),
("sunscreen", dict(feels=26.0, uv=8.0), dict(feels=8.0, uv=0.5)),
("mosquito", dict(feels=27.0, hum=85, wind=0.5), dict(feels=15.0, hum=40, wind=6.0)),
("tennis", dict(feels=18.0, wind=1.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("hyodo", dict(feels=20.0, wind=1.5), dict(feels=20.0, prob=80, rain=RainType.RAIN)),
("thanks", dict(feels=0.0, prob=90, rain=RainType.RAIN), dict(feels=20.0)),
("gift", dict(feels=17.0, wind=1.5), dict(feels=17.0, prob=80, rain=RainType.RAIN)),
("party", dict(feels=3.0, prob=90, rain=RainType.RAIN), dict(day=_WED, feels=20.0)),
("game", dict(feels=3.0, prob=90, rain=RainType.RAIN, pm25=70), dict(day=_WED, feels=20.0)),
("selfie", dict(wind=1.0, hum=35, sunshine_ratio=0.8), dict(prob=90, rain=RainType.RAIN, hum=90, wind=8.0, sunshine_ratio=0.0)),
("sentimental", dict(feels=13.0, prob=90, rain=RainType.RAIN, wind=3.0, hum=85), dict(feels=28.0, hum=40, wind=0.5)),
])
def test_trend_and_mood_gak_good_day_high_bad_day_low(code, good, bad):
assert _seed_score(code, **good) >= 80
assert _seed_score(code, **bad) <= 30
def test_new_gak_100_only_when_every_factor_is_perfect():
perfect = dict(feels=19.5, wind=1.0, hum=35)
assert _seed_score("golf", **perfect) == 100
+86
View File
@@ -0,0 +1,86 @@
from datetime import date
import pytest
from httpx import ASGITransport, AsyncClient
from common.enums import RainType, Sky
from router.router import app
from services.calc.index_calc import Context, Hour, evaluate
from services.calc.my_gak_calc import MyRule, axes, definition
from services.my_gak_service import MAX_PER_USER, gak_name
RULE = {"temp": [15, 25], "rain": "dry", "slots": ["evening", "night"]}
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "조건토끼"})).json()
return {"Authorization": f"Bearer {body['access_token']}"}
def _hours(feels: float, rain: RainType = RainType.NONE, prob: int = 0, wind: float = 1.0, humidity: int = 50) -> list[Hour]:
return [Hour(hour=h, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=humidity, sky=Sky.CLEAR) for h in (19, 20, 21)]
def _score(rule: MyRule, hours: list[Hour], pm25: int | None = 10) -> int:
ctx = Context(day=date(2026, 10, 20), is_holiday=False, pm25=pm25, air_label=None, moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
return evaluate(definition(rule), [hours], ctx).score
def test_name_gets_gak_suffix_and_rejects_links_and_numbers():
assert gak_name(" 소맥 ") == "소맥각"
assert gak_name("야독각") == "야독각"
assert gak_name("naver.com") is None
assert gak_name("01012345678") is None
assert gak_name("가" * 12) is None
def test_only_chosen_conditions_count_and_score_falls_with_distance():
rule = MyRule(temp=(15, 25), rain="dry")
assert axes(rule) == ["temp", "rain"]
inside = _score(rule, _hours(20))
near = _score(rule, _hours(27))
far = _score(rule, _hours(33))
assert inside >= 90 and inside > near > far
# 고르지 않은 바람·습도는 아무리 나빠도 점수에 안 들어간다
assert _score(rule, _hours(20, wind=15, humidity=95)) == inside
def test_dry_rule_caps_when_raining_and_wet_rule_likes_rain():
assert _score(MyRule(rain="dry"), _hours(20, RainType.RAIN, 90)) <= 20
assert _score(MyRule(rain="wet"), _hours(20, RainType.RAIN, 90)) >= 90
def test_wind_and_air_limits():
assert _score(MyRule(wind_max=4), _hours(20, wind=2)) > _score(MyRule(wind_max=4), _hours(20, wind=9))
assert _score(MyRule(air="good"), _hours(20), pm25=10) > _score(MyRule(air="good"), _hours(20), pm25=40)
@pytest.mark.anyio
async def test_add_list_delete_and_limits():
async with client() as c:
assert (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE})).status_code == 401
h = await _login(c, "rule_01")
assert (await c.get("/v1/my-gak")).json()["items"] == []
item = (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE}, headers=h)).json()["item"]
assert item["name"] == "소맥각" and item["rule"]["temp"] == [15, 25] and item["rule"]["slots"] == ["evening", "night"]
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [item["my_gak_id"]]
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["success"] is True
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
for i in range(MAX_PER_USER):
assert (await c.post("/v1/my-gak", json={"name": f"각{chr(0xAC00 + i)}", "rule": RULE}, headers=h)).json()["item"]
assert (await c.post("/v1/my-gak", json={"name": "하나더", "rule": RULE}, headers=h)).json()["result"]["desc"] == "INVALID_INPUT"
@pytest.mark.anyio
async def test_rejects_bad_rules():
async with client() as c:
h = await _login(c, "rule_02")
bad = lambda rule: c.post("/v1/my-gak", json={"name": "야독", "rule": rule}, headers=h) # noqa: E731
assert (await bad({})).status_code == 422
assert (await bad({"temp": [25, 15]})).status_code == 422
assert (await bad({"temp": [15, 25], "slots": []})).status_code == 422
assert (await bad({"humidity": [10, 120]})).status_code == 422
+89
View File
@@ -0,0 +1,89 @@
import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
from services.talk_service import DAILY_MAX, HIDE_AT, weather_line
REGION = "1144000000"
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
return {"Authorization": f"Bearer {body['access_token']}"}
async def _write(c, h, body="망원동 하늘 진짜 맑아요"):
return (await c.post("/v1/talk", json={"region_code": REGION, "body": body}, headers=h)).json()
@pytest.mark.anyio
async def test_write_list_like_delete():
async with client() as c:
assert (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕"})).status_code == 401
h = await _login(c, "talk_01")
t = (await _write(c, h, " 바람 많이 불어요 "))["talk"]
assert t["body"] == "바람 많이 불어요" and t["mine"] is True and t["region_name"]
anon = (await c.get("/v1/talk/list")).json()["talks"]
mine = next(x for x in anon if x["talk_id"] == t["talk_id"])
assert mine["mine"] is False and mine["nickname"] == "talk_01"
liked = (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()
assert liked["liked"] is True and liked["like_count"] == 1
assert (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 1
assert (await c.delete(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 0
other = await _login(c, "talk_02")
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=other)).json()["result"]["desc"] == "NOT_FOUND"
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=h)).json()["result"]["success"] is True
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
@pytest.mark.anyio
async def test_rejects_links_phone_long_and_daily_limit():
async with client() as c:
h = await _login(c, "talk_03")
assert (await _write(c, h, "여기 보세요 https://spam.example"))["result"]["desc"] == "LINK_NOT_ALLOWED"
assert (await _write(c, h, "연락 주세요 010-1234-5678"))["result"]["desc"] == "LINK_NOT_ALLOWED"
assert (await _write(c, h, "가" * 101))["result"]["desc"] == "INVALID_INPUT"
bad_region = (await c.post("/v1/talk", json={"region_code": "0000000000", "body": "안녕"}, headers=h)).json()
assert bad_region["result"]["desc"] == "INVALID_INPUT"
for i in range(DAILY_MAX):
assert (await _write(c, h, f"오늘 {i}번째"))["talk"]
assert (await _write(c, h))["result"]["desc"] == "DAILY_LIMIT"
@pytest.mark.anyio
async def test_reports_hide_and_block_hides_author():
async with client() as c:
author = await _login(c, "talk_04")
t = (await _write(c, author))["talk"]
assert (await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 1}, headers=author)).json()["result"]["desc"] == "INVALID_INPUT"
viewer = await _login(c, "talk_05")
assert (await c.post(f"/v1/talk/{t['talk_id']}/block", headers=viewer)).json()["result"]["success"] is True
seen = [x["talk_id"] for x in (await c.get("/v1/talk/list", headers=viewer)).json()["talks"]]
assert t["talk_id"] not in seen
assert t["talk_id"] in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
for i in range(HIDE_AT):
h = await _login(c, f"talk_r{i}")
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
def test_weather_line():
class Row:
temp_c, sky, rain_type = 18.4, 1, 1
class Wet:
temp_c, sky, rain_type = 11.6, 3, 2
assert weather_line(Row()) == "18° 맑음"
assert weather_line(Wet()) == "12° 비"
assert weather_line(None) is None
+59
View File
@@ -0,0 +1,59 @@
import io
import pytest
from httpx import ASGITransport, AsyncClient
from PIL import Image
from router.router import app
REGION = "1144000000"
GPS_IFD = 0x8825
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
return {"Authorization": f"Bearer {body['access_token']}"}
def _jpeg_with_gps(w: int = 2400, h: int = 1600) -> bytes:
exif = Image.Exif()
exif[0x010F] = "PhoneMaker"
exif[GPS_IFD] = {1: "N", 2: (37.0, 33.0, 0.0), 3: "E", 4: (126.0, 58.0, 0.0)}
buf = io.BytesIO()
Image.new("RGB", (w, h), (120, 180, 230)).save(buf, "JPEG", exif=exif)
return buf.getvalue()
@pytest.mark.anyio
async def test_upload_strips_location_resizes_and_attaches_to_talk():
src = _jpeg_with_gps()
assert Image.open(io.BytesIO(src)).getexif().get_ifd(GPS_IFD)
async with client() as c:
assert (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")})).status_code == 401
h = await _login(c, "photo_01")
url = (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")}, headers=h)).json()["image"]
got = await c.get(url)
assert got.status_code == 200 and got.headers["content-type"] == "image/webp"
img = Image.open(io.BytesIO(got.content))
assert max(img.size) == 1080
assert not img.getexif()
talk = (await c.post("/v1/talk", json={"region_code": REGION, "body": "하늘 사진", "image": url}, headers=h)).json()["talk"]
assert talk["image"] == url
listed = (await c.get("/v1/talk/list")).json()["talks"][0]
assert listed["image"] == url
@pytest.mark.anyio
async def test_rejects_non_images_and_foreign_paths():
async with client() as c:
h = await _login(c, "photo_02")
bad = (await c.post("/v1/talk/image", files={"file": ("a.txt", b"not an image", "text/plain")}, headers=h)).json()
assert bad["result"]["desc"] == "INVALID_INPUT"
for image in ("https://evil.example/a.webp", "/v1/talk/image/../../etc/passwd", "/v1/talk/image/" + "0" * 32 + ".webp"):
res = (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕", "image": image}, headers=h)).json()
assert res["result"]["desc"] == "INVALID_INPUT"
assert (await c.get("/v1/talk/image/" + "0" * 32 + ".webp")).status_code == 404
+3
View File
@@ -43,6 +43,8 @@ services:
REDIS_PORT: "6379"
ports:
- "${API_BIND:-9810}:9800"
volumes:
- uploads:/app/uploads # 사람 글 사진
depends_on:
postgres:
condition: service_healthy
@@ -104,3 +106,4 @@ services:
volumes:
pgdata:
redisdata:
uploads:
@@ -0,0 +1,96 @@
# 2026-10-14 작업 정리: 지역 검색 페이지 · 첫 접속 각 비어 보임
운영 반영: `ba94a38` (https://weather.o2o.kr)
## 1. 처음 들어온 지역에 "오늘 계산된 각이 없어요"가 뜸
- **문제**: 아무도 안 본 지역을 처음 열면 각이 비어 보였다. 1분쯤 지나야 채워졌다.
- **원인**
- 각은 그 지역에 처음 접속한 사람이 생길 때 계산한다.
- 예보를 받아 오는 동안 다른 요청은 3초만 기다렸다. 3초 안에 못 받으면 빈 피드를 만들었다.
- 그 빈 피드를 1분 동안 캐시에 저장해서, 그사이 들어온 사람도 계속 빈 화면을 봤다.
- **해결** (`fix/first-region-feed`)
- 기다리는 시간을 최대 15초로 늘렸다 (`backend/services/weather_service.py`).
- 각이 없는 피드는 캐시에 저장하지 않는다 (`backend/services/feed_service.py`). 다음 요청에서 바로 채워진다.
- **상태**: 운영 반영. 김해시·인제군·분당구 피드에서 각 42개가 다 나오는 것 확인.
## 2. 검색에 지역별 날씨 페이지가 잡히지 않음
- **문제**: 다른 날씨 사이트처럼 "성남시 날씨" 같은 검색에 우리 페이지가 따로 뜨지 않았다.
- **원인**
- 사이트가 SPA 한 장이라, 검색엔진에는 모든 주소가 같은 제목과 같은 본문으로 보였다.
- 지역별 주소도 없었다.
- **해결** (`feat/region-seo-pages`)
- 빌드할 때 지역 페이지 HTML 230장을 만든다 (`frontend/vite.config.ts`).
- `sitemap.xml`도 빌드가 자동으로 만든다. 주소는 235개다.
- 주소: `/today/{시도}/{시군구}`. 예: `/today/gyeonggi/seongnam`, `/today/seoul/mapo`
- **페이지 단위를 이렇게 정했다**
- 우리 날씨 데이터는 구 단위뿐이다.
- 구로 나뉜 13개 시는 시 페이지 하나로 묶었다: 수원·성남·고양·용인·화성·부천·안산·안양·창원·청주·포항·전주·천안. 사람들은 "성남 날씨"로 검색하지 "중원구 날씨"로는 덜 찾는다.
- 시 페이지는 시청이 있는 구의 날씨를 보여 준다. 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구를 보여 준다.
- 나머지(서울·광역시의 구, 군, 일반 시)는 지금 단위 그대로 페이지를 만든다.
- 중구·동구·고성군처럼 이름이 겹치는 곳이 있어서 주소 앞에 시도를 붙였다.
- **앱 동작** (`frontend/src/b/region.tsx`)
- 지역 주소로 들어오면 그 지역을 보여 준다. 위치 권한은 묻지 않고 저장된 선택도 덮어쓰지 않는다.
- 지역 페이지에서 다른 지역을 고르면 주소도 그 지역 주소로 바뀐다.
- `/`로 들어오면 예전 그대로다.
- **지역 목록이 바뀌면**: `python backend/scripts/gen_region_pages.py`를 실행해 `frontend/seo/region.json`을 다시 만든다.
- **매일 돌릴 스케줄은 필요 없다**: 주소와 소개 글은 그대로이고, 그날 값은 요청이 올 때 채운다.
## 3. 검색 결과에 실제 날씨가 안 보임
- **문제**
- AccuWeather·weather.com은 검색 결과 요약에 기온·습도 같은 실제 값이 보인다.
- 우리 정적 페이지에는 고정 소개 글만 있었다.
- **원인**: 정적 HTML에는 그날 값이 들어갈 수 없다.
- **해결 (가벼운 SSR)**
- nginx가 `/today/...` 요청을 백엔드로 넘긴다 (`frontend/nginx.conf`).
- 백엔드는 정적 HTML을 받아 와서 설명 메타와 본문에 오늘 값을 채운다 (`backend/services/seo_service.py`, `/v1/seo/today/{sido}/{place}`). React 화면은 지금처럼 브라우저에서 그린다.
- 피드 캐시를 그대로 써서 추가 계산은 없다.
- 백엔드가 응답하지 않거나 오류가 나면 정적 HTML을 그대로 보여 준다.
- **검색어에 맞춘 제목과 요약**
```
성남시 오늘 날씨, 뭐 할까? · 경기 | 날씨각
최저 9°·최고 19°, 강수확률 0%, 맑음. 지금 15°, 습도 보통·자외선 낮음·미세먼지 좋음. 아침은 드라이브각, 낮은 빨래각, 저녁은 자전거각, 밤은 러닝각. 해 지는 시각 오후 5시 57분.
```
- **상태**: 운영 반영. 백엔드를 끈 상태에서 정적 HTML로 돌아가는 것도 로컬에서 확인했다.
## 4. "날씨각" 검색 결과 요약에 게시물 글이 나옴
- **문제**: "날씨각"으로 검색하면 요약에 "날씨각포근한 빗속, 우산 돌리며…"처럼 게시물 문장이 나왔다.
- **원인**
- 구글은 JS로 그려진 화면도 읽는다.
- 게시물마다 작성자 이름 "날씨각" 바로 뒤에 그날 문장이 붙어 있다. 그래서 검색어 "날씨각"과 맞는 그 부분을 요약으로 뽑았다.
- **해결**
- 처음에는 게시물 카드에만 `data-nosnippet`을 달았다.
- 색인된 지역 페이지 요약에 시간대 칸("9시 : 낮음…")과 행사 장소·기간도 섞여 나왔다. 그래서 앱 영역 전체(`#root`, `#boot`)에 `data-nosnippet`을 달았다 (`frontend/index.html`, `0d6ab29`). 이제 요약은 description(지역 페이지는 서버가 채운 오늘 날씨)을 쓴다.
- React가 뜨면 서버가 채운 `<main>` 글은 지워지기 때문에, 요약에 쓸 글은 description뿐이다.
- 홈 설명이 "날씨각은 …"으로 시작하게 바꿨다.
- **상태**: 운영 반영. 구글이 다시 읽어 가야 검색 결과가 바뀐다.
## 5. 사이트 이름이 "에이아이오투오"로 나옴
- **원인**: 구글이 사이트 이름을 상위 도메인 `o2o.kr`(회사)의 이름으로 잡은 것으로 보인다.
- **해결**
- 우리 쪽에 필요한 표시는 이미 다 있다: 구조화 데이터 `WebSite` name "날씨각", `og:site_name`, "날씨각"으로 시작하는 제목.
- 코드로 바로 바꿀 수는 없다. 서치콘솔에서 홈을 색인 요청하고 몇 주 기다린다.
- **상태**: 대기
## 해야 할 일
| 상태 | 할 일 | 이유 | 관련 |
|---|---|---|---|
| [ ] | 네이버 서치어드바이저에 sitemap 제출, 대표 페이지 몇 개 수집 요청 | 네이버는 제출하지 않으면 새 페이지를 늦게 가져간다 | https://searchadvisor.naver.com |
| [x] | 구글 서치콘솔에 sitemap 제출 (2026-10-14) | 색인을 앞당긴다 | https://search.google.com/search-console |
| [ ] | 구글 URL 검사로 홈과 성남 페이지 색인 요청 | 색인과 사이트 이름 반영을 앞당긴다 | https://search.google.com/search-console |
| [ ] | 휴대폰에서 지역 페이지 확인 | 시 안에서 내 구로 바뀌는지, 지역을 바꾸면 주소가 바뀌는지 로컬에서 확인 못 했다 | `frontend/src/b/region.tsx` |
| [ ] | 1~2주 뒤 색인된 페이지 수 확인 | 다음 개선(문구, 홈에서 지역 페이지로 가는 링크)을 정한다 | 서치콘솔 |
| [ ] | `test_feed_assembles_hero_stories_posts_and_bands` 기대값 40 → 42 | `0aeceac`에서 각 2개를 추가하며 안 고쳐서 main에서도 실패한다 | `backend/tests/test_feed.py:64` |
| [ ] | 없는 지역 주소가 200으로 홈을 보여 주는 것 | SPA 기본 동작이다. canonical이 홈이라 당장 문제는 없다 | `frontend/nginx.conf` |
| [ ] | 요약의 "해 지는 시각"을 노을이 가장 붉은 시각으로 바꿀지 | 지금은 계산으로 나온 일몰 시각이다 | `backend/services/seo_service.py` |
## 작업 중 있었던 일
- main에 push할 때 그사이 `feat/meeting-1008`이 먼저 합쳐져 있었다.
- 그 브랜치의 탭 다시 누르면 맨 위로 기능과 `BLayout.tsx`에서 충돌이 났고, 두 변경을 다 살려 해결했다.
- 이 저장소는 Gitea라서 `gh`로 PR을 만들 수 없다. main에 바로 합쳐서 배포했다.
+61
View File
@@ -0,0 +1,61 @@
# 2026-10-20(화) 회의 — 날씨각
방향: 'AI가 날씨에 대해 쓰고 사람도 함께 올리는 날씨 소셜미디어' (대표)
## 금일 핵심 업무 (최미나)
1. 오늘의 각을 일반 포스트 크기 카드로 만들고 공유 가능하게 (결정)
2. '+' 사용자 포스팅을 메인 피드에 어떻게 섞을지 검토 → 대표 보고 (캐러셀로 묶기 의견 포함)
## 공유
- 공유는 지금 보이는 화면을 링크로 그대로. 미리보기는 날씨각 대표 이미지 1장 고정 + 설명·링크 (결정) — 지금은 포스트를 이미지로 만들어 공유(`frontend/src/b/Sheets.tsx` `ShareSheet`, `storyImage.ts`), 아침·낮·저녁·밤을 한 장에 못 담음. 대표 이미지는 이미 `og.png` 1장(`frontend/index.html:28`)
- 공유 이미지 잘림 수정, 공유 아이콘(종이비행기) 유지
- 담당이 회의록상 김성경(확인 필요) — 오늘의 각 카드 공유(최미나)와 겹치므로 나눌 범위 확인
## 사용자 포스팅·피드
- 별도 탭 없이 '+' 버튼으로 글·이미지 올리면 오늘 피드에 노출 (결정) — 지금 브랜치(feat/my-gak)는 '이야기' 탭(/talk)에 글만 100자. 탭 → '+'로, 이미지 추가로 바꿔야 함
- 피드 순서: 날씨 히어로 → 오늘의 각 → 포스트 무한 피드 (결정)
- 운영 포스트가 밀리지 않게 사용자 글은 중간중간 섞는 정도로 시작, 많아지면 순서 알고리즘 고민
## 피드 콘텐츠
- 빨래각처럼 평이한 정보는 줄이고 주말 날씨('토요일 비 소식 없음')·동네 행사·노을을 앞쪽으로
- 노을각 카드를 메인 피드 중간에
- 단풍각 강화 — 단풍 지도(설악산 등 절정 지역, 서울 절정 시기), 시즌 동안 단풍 포스트 계속 노출. 단풍각 자체는 이미 있음(`backend/seed/index_definition.json:2940`)
- 새 각: 시즌 스포츠각(프로야구·농구·배구), 제철 수산물각(전어·꽃게)
- 시간대 지정 각(야장·별보기 등)은 그 시간이 아니어도 숨기지 말고 뒤쪽에 — 낮에도 '오늘 밤 별보기' 보이게
- 억새각 시간대 설정 때문에 노출 조건이 안 맞음 — 확인 필요
## 날씨 점수·나만의 각
- 날씨 점수 전체 하향 — 맑고 적당한 날도 96이 아니라 92 수준
- 날씨 점수 누르면 산정 이유 설명
- 불쾌지수 항상 표시 (결정) — 지금은 6~9월에만 (`backend/services/hero_stats.py:70`). 10/8에도 같은 결정이었음
- 나만의 각: 기존 각 조합(지금 만든 1단계, `a8a126f`) 대신 사용자가 이름(소맥각·새우깡각·야독각)과 조건(기온·날씨 등)을 자유롭게 써서 등록 → 피드에 올려 좋아요 받기 (결정) → 프로토타입 대표 시연
## 로그인·앱인토스
- 로그인 유지. 비로그인은 좋아요·댓글·공유까지, 포스팅할 때 로그인 요청 (결정) — 댓글 로그인 필요 여부는 확인 필요. 지금은 좋아요·댓글 모두 로그인 필수(`backend/router/v1/reaction/reaction.py`)
- 구글·토스 로그인 적용 (결정, 앱인토스 등록에 토스 로그인 필요) — 지금은 아이디·비밀번호만(`backend/router/v1/auth/account.py`), `AuthProvider`에 GOOGLE 값만 있음
- 앱인토스 정산 계좌(대표자 명의) 입력 시 유효성 오류 → 토스에 문의
## 검색 노출
- '날씨각' 외에 '오늘 날씨'·'서울 날씨'·'성동구 날씨'·'춘천 날씨' 같은 지역 날씨 검색으로 들어오게 지역별 콘텐츠 추가, 리서치·테스트하며 개선 — 담당 김성경. 지금까지 한 것: 지역·구 페이지 274개(`96cbd19`), 검색어 리서치(`docs/검색어_인기_리서치.md`, '내일 날씨'가 '오늘 날씨'보다 훨씬 많음)
## 홍보·수익화
- 유튜브 채널 개설, 각 설명·오늘 날씨 숏폼 매일 자동 생성·업로드 (결정) — 기존 숏폼 자동화(크리에이토메이트 템플릿) 활용, 노하우 전수(수석, 확인 필요). 담당 미정
- 인스타그램·스레드 계정 운영
- '오늘 날씨 코디' 시도 — 상품 링크·협찬 수익 가능성. TODO의 옷차림 [보류] 행과 이어짐
- 날씨 타로 — 카드를 뽑으면 '오늘은 야장각'처럼 행동 추천
- 광고는 애드센스 수준으로 양옆 여백 등에 깔끔하게만 (검토)
- 의견(황 본부장): 날씨각을 Web4Ai 전 사이트에 챗봇처럼 모듈로 붙이고 외부 제휴로 확산 / 캐시워크처럼 날씨각 템플릿에 사용자 사진을 얹어 인스타에 바로 올리기
## 담당·기한
| 할 일 | 담당 | 기한 | 보고 |
|---|---|---|---|
| 오늘의 각 카드화·공유 | 최미나 | 미정 | 대표 공유 |
| '+' 포스팅·메인 피드 노출 방식 | 최미나 | 미정 | 대표 보고 |
| 피드 순서 재배치, 단풍·스포츠·제철 수산물각 | 최미나 | 미정 | 대표 공유 |
| 나만의 각 자유 등록 프로토타입 | 최미나 | 미정 | 대표 시연 |
| 구글·토스 로그인, 앱인토스 계좌 오류 문의 | 최미나 | 미정 | 대표 공유 |
| 날씨 타로·오늘 날씨 코디 구체화 | 최미나 | 미정 | 대표 보고 |
| 공유 방식 변경(링크·대표 이미지·잘림) | 김성경(확인 필요) | 미정 | 대표 공유 |
| 날씨 점수 하향·산정 설명, 시간대 지정 각 노출 | 김성경(확인 필요) | 미정 | 대표 보고 |
| 지역 날씨 검색 콘텐츠 | 김성경 | 미정 | 대표 보고 |
| 유튜브 채널·숏폼 자동화 | 미정 (노하우: 수석) | 미정 | 대표 보고 |
+845 -117
View File
File diff suppressed because it is too large. Load diff
+39
View File
@@ -0,0 +1,39 @@
# 검색어 인기 리서치
조사일: 2026-10-20
방법: 구글 트렌드(한국, 최근 12개월 평균, '세차'=100 기준 상대값), 구글·네이버 자동완성.
한계: 구글 트렌드는 표본 값이라 같은 검색어도 묶음마다 수치가 2배까지 달라졌다(이번주 날씨 32·69). 자릿수로만 본다. 한국은 네이버 비중이 커서 네이버 실제 검색량(네이버 검색광고 키워드 도구, 광고 계정 필요)으로 다시 확인해야 한다.
## 구글 트렌드 상대 검색량 ('세차'=100)
| 묶음 | 검색어 = 값 |
|---|---|
| 날씨 일반 | 내일 날씨 ≈ 10,000 · 오늘 날씨 384 · 서울 날씨 295 · 이번주 날씨 32~69 · 주말 날씨 15 |
| 지역 | 인천 날씨 80 · 수원 날씨 31 · 성남 날씨 7 · 강남 날씨 4 · 분당 날씨 2 · 마포구 날씨 0 · 판교 날씨 0 |
| 생활 | 우산 181 · 빨래 160 · 미세먼지 156 · 노을 82 · 옷차림 82 · 일몰 시간 50 |
| 활동+날씨 | 캠핑 날씨 1 · 러닝 날씨 1 · 날씨 좋은 날 1 · 세차 날씨 0 · 빨래 날씨 0 |
- '날씨'·'오늘 날씨'를 같은 묶음에 넣으면 나머지가 모두 0으로 반올림됐다. '날씨' 단독 검색이 압도적으로 많다.
## 자동완성 (사람들이 실제로 붙여 치는 말)
- 오늘 날씨: 구글 — 판교·성남·서울 / 네이버 — 서울·부산·인천·대전·대구, **오늘 날씨 옷차림**
- 분당 날씨: 내일 분당 날씨, 오늘 분당 날씨, 이번주 분당 날씨, 현재 분당 날씨, 분당 날씨 비·강수량
- 주말 날씨: 네이버 — **이번주말 날씨**, 서울·대구·대전·제주 주말 날씨, 다음주 주말 날씨
- 날씨 좋은 날: 갈만한 곳, 카페, 산책, 드라이브, 데이트
- 러닝 날씨: 복장, 옷 / 캠핑 날씨: 어플, 10월·11월 캠핑 날씨
- 노을: 네이버 — 노을 지는 시간
- 세차·빨래: 세차장·세차용품, 빨래방·건조대·쉰내 — 날씨와 붙여 치는 말은 자동완성에 없음
## 판단
- 사람이 많이 치는 꼴은 "지역 + 날씨"와 "내일/오늘/이번주(말) 날씨"다. 우리 지역 주소가 받아야 할 검색어가 이쪽이다.
- 지역은 큰 시가 많다(인천·수원 > 성남 > 분당·강남). 구 단위('마포구 날씨', '판교 날씨')는 구글에서 거의 0이라, 구 주소는 "시 주소가 못 받는 동네 검색" 보조로 본다.
- '세차각'·'세차 날씨'·'빨래 날씨'처럼 활동+날씨 검색은 거의 없다. 각 이름으로 검색 유입을 기대하긴 어렵고, 검색은 지역 날씨로 들어오게 하고 각은 들어온 뒤 차별점으로 쓰는 게 맞다.
- 시간 표현은 '내일'이 '오늘'보다 훨씬 많다. 우리 지역 페이지는 제목이 "오늘 날씨"뿐이라 '내일 OO 날씨'를 받을 내용이 없다 → 내일 예보·내일 각을 페이지에 넣을지 기획 결정 필요.
- '옷차림'(오늘 날씨 옷차림)·'우산'·'미세먼지'·'노을 지는 시간'은 날씨각이 이미 다루는 주제와 맞닿고 검색량이 세차보다 많다. 후보로 둔다.
## 다음에 확인할 것
- 네이버 검색광고 키워드 도구로 위 검색어의 네이버 월간 검색 수(PC·모바일) 확인 — https://searchad.naver.com
- 네이버 데이터랩 검색어 트렌드로 계절 변화 확인 — https://datalab.naver.com/keyword/trendSearch.naver
+102
View File
@@ -0,0 +1,102 @@
# 지역별 예보 HTML 설계
목표: `/weather/{지역}` 주소로 접속했을 때 서버가 처음 보내는 HTML 본문에 그 지역의 실제 예보가 들어가게 한다.
상태: 설계만 했다. 코드는 아직 바꾸지 않았다.
## 결론
Next.js로 바꾸거나 Node 서버를 늘 띄워 둘 필요 없다.
이미 돌고 있는 Python 백엔드가 요청을 받을 때 HTML을 만들고, 만든 HTML은 Redis에 캐시한다.
3시간마다 256개 지역의 HTML 파일을 미리 다시 만드는 방식은 쓰지 않는다. 이유는 다음과 같다.
- 아무도 보지 않는 지역까지 매번 만들게 된다. 단기예보만 쳐도 하루 약 1,800회(224칸 × 8회) 기상청을 불러야 한다.
- worker와 frontend 컨테이너가 같은 폴더를 함께 써야 하고, 다시 만들다 실패했을 때 처리할 일이 따로 생긴다.
- 요청할 때 만들면 피드와 같은 캐시 키를 쓰므로, 사용자가 보는 숫자와 HTML 숫자가 같다.
## 지금 구조 (확인한 것)
| 항목 | 위치 | 내용 |
|---|---|---|
| 첫 HTML | `frontend/index.html:105` | `<main>` 안에 정해진 소개 글만 있고, 불러오는 화면(`#boot`)이 그 위를 덮는다 |
| 화면 그리기 | `frontend/src/main.tsx:17` | `createRoot`가 `#root`를 통째로 바꾼다. 이어 붙이는 방식(hydrate)이 아니다 |
| 예보 데이터 | `frontend/src/b/TodayPage.tsx:350` | 브라우저가 `/v1/feed`, `/v1/weather/today`를 따로 불러온다 |
| 지역 | `frontend/src/b/region.tsx:29` | localStorage에 저장된 지역 → 현재 위치 → 마포구 순으로 정한다. 주소에는 지역이 없다 |
| 라우트 | `frontend/src/App.tsx:19` | 없는 주소도 `*`가 받아 200으로 오늘 화면을 보여 준다(가짜 404) |
| 피드 캐시 | `backend/services/feed_service.py:304`, `:155` | 지역별로 요청이 오면 그때 만들고 `feed:{code}:{slot}`에 저장한다. 저장 기간은 다음 예보 갱신까지, 최대 1시간 |
| 지역 수 | `backend/seed/region.csv` | 구 256개, 기상청 격자 224칸 |
## 동작 흐름
1. nginx가 `/weather/{code}`와 `/sitemap-regions.xml` 요청을 백엔드로 넘긴다.
2. 백엔드는 다음 순서로 HTML을 만든다.
- `FeedService.feed()`와 오늘 날씨 데이터를 가져온다. 피드와 같은 서비스, 같은 캐시를 쓴다.
- 프론트 빌드 결과인 `index.html`을 틀로 쓴다. 틀은 frontend 컨테이너에서 받아 메모리에 5분 동안 캐시한다.
- 틀에서 title, description, og, canonical, `<main>` 부분을 바꾼다.
- 페이지 데이터를 `<script type="application/json" id="ssr-data">`에 넣는다.
3. `<main>`에 들어갈 내용
- H1: "서울 마포구 오늘 날씨"
- 날짜, 최저·최고 기온, 강수확률
- 3시간 단위 예보 표
- 오늘의 각 1~10위와 점수
- "10월 13일 14:00 발표 기준" 같은 기준 시각(`issued_at`)
- 같은 시·도에 있는 다른 구 링크, 그리고 `/gak`, `/sky`, `/week` 링크
4. 지역 페이지에는 `#boot` 덮개를 넣지 않는다. 실제 예보라서 사용자에게 그대로 보여도 된다.
5. 브라우저 쪽
- React Query가 `ssr-data`를 첫 데이터로 쓴다. 그래서 처음 그린 화면의 숫자가 HTML과 같다. 그 뒤에는 원래 주기대로 새로 불러온다.
- 지역은 주소에 있는 지역을 쓴다. 위치 권한은 묻지 않고, 저장해 둔 지역도 덮어쓰지 않는다.
- 사용자가 지역을 바꾸면 그 지역의 `/weather/{code}`로 이동한다.
- 화면은 지금처럼 `createRoot`가 통째로 바꾸므로 hydration 불일치가 생기지 않는다.
## 주소, 검색 태그, 404
- 주소는 `/weather/{region.code}` 형식이다(예: `/weather/1144000000`). 지역 이름은 겹치기 때문이다("중구"가 6곳). 읽기 쉬운 영문 주소가 필요하면 나중에 `region.csv`에 `slug` 칸을 추가한다.
- 검색 태그
- title: `서울 마포구 오늘 날씨 · 세차각·빨래각 점수 | 날씨각`
- description: 오늘 기온, 강수확률, 1위 각을 한 문장으로 쓴다.
- canonical: 자기 주소를 가리킨다.
- 없는 코드로 들어오면 404 상태 코드와 함께 안내 HTML을 보낸다.
- `/sitemap-regions.xml`에 256개 주소를 넣고, `robots.txt`에 `Sitemap:` 줄을 하나 더 추가한다.
- 홈 첫 HTML에 시·도별 지역 링크를 넣어 크롤러가 지역 페이지를 찾게 한다.
## 실패와 기준 시각
- HTML을 정상적으로 만들 때마다 `ssr:last:{code}`에 만료 없이 저장한다.
- 예보를 받아 오거나 계산하다 실패하면 이 마지막 정상본을 보낸다. 마지막 정상본에도 발표 기준 시각이 들어 있다.
- 캐시가 비어 있고 첫 요청이 느리면(기상청 응답 대기 1~3초) 마지막 정상본을 먼저 보내고, 새로 만드는 일은 뒤에서 한다.
## 비용
- 기상청 호출은 지금 사용자 요청과 같은 경로라서, 늘어나는 건 크롤러가 연 지역만큼이다.
- 최악의 경우는 256곳의 캐시가 하루 24번 모두 만료되는 경우다. 이때 단기예보 약 1,800회, 초단기예보 약 5,400회를 부른다.
- 저장 공간은 30KB × 256 ≒ 8MB다.
## 수정할 파일
| 파일 | 할 일 |
|---|---|
| `backend/router/ssr.py` (새 파일) | `/weather/{code}`와 `/sitemap-regions.xml` 처리, 404 응답 |
| `backend/router/router.py` | 위 라우터 등록 |
| `backend/services/region_page.py` (새 파일) | 피드와 오늘 날씨로 HTML 만들기, 틀 캐시, 마지막 정상본 저장과 대체 |
| `frontend/nginx.conf` | 위 두 주소를 백엔드로 넘기기 |
| `frontend/public/robots.txt` | 지역 sitemap 줄 추가 |
| `frontend/index.html` | 시·도별 지역 링크 |
| `frontend/src/App.tsx` | `weather/:code` 라우트 추가 |
| `frontend/src/b/region.tsx` | 주소의 지역을 먼저 쓰고, 위치 권한 묻기 생략 |
| `frontend/src/main.tsx` | `ssr-data`를 React Query 첫 데이터로 넣기 |
| `backend/tests/test_region_page.py` (새 파일) | 정상 생성, 404, 실패했을 때 마지막 정상본 테스트 |
## 위험과 검증
| 위험 | 검증 |
|---|---|
| 캐시가 비었을 때 첫 응답이 느림 | `curl -w %{time_total}`로 측정한다. 1초가 넘으면 마지막 정상본을 먼저 보내는지 확인한다 |
| HTML과 화면의 숫자가 다름 | `curl`로 받은 본문과 로컬 화면 스크린샷을 비교한다 |
| 기상청 하루 호출 한도 | data.go.kr 신청 내역에서 한도를 확인한다(아직 확인 안 함) |
| 효과 확인 | 서치 콘솔 "URL 검사 → 크롤링된 페이지 HTML"에 예보 숫자가 있는지 본다. `site:weather.o2o.kr/weather`로 색인된 수를 본다 |
이 작업으로 순위가 오른다는 보장은 없다. 바뀌는 건 두 가지다. 지역마다 고유한 주소와 본문이 생긴다. 크롤러가 JS를 실행하지 않아도 예보 본문을 읽을 수 있다.
## 범위 밖 (남은 이슈)
- `App.tsx`의 `*` 라우트가 없는 주소를 200으로 응답한다(가짜 404).
- 지역 주소를 영문(slug)으로 바꿀지 정해야 한다.
@@ -0,0 +1,155 @@
# 피드 포스트 배경 제작 지시문 (Codex 이미지 생성용)
- 작성: 2026-10-20
- 쓰는 법: 아래 **공통 규격** + **스타일** + 만들 목록(표에서 id와 장면만 골라서)을 합쳐 Codex에 붙여 넣습니다. 한 번에 5~10장씩 나눠 요청합니다.
- 실행 예: 저장소 루트에서 `codex exec --sandbox workspace-write -i frontend/public/icons/bike.png "<지시문>"`
- `-i` 로 3D 아이콘 한두 장을 **스타일 참고**로 붙이면 질감이 맞춰집니다.
- 쓰는 곳: 피드 슬라이드(4:5) 뒤 배경. 위 왼쪽에 작은 머리글+큰 제목, 아래 왼쪽에 큰 주황 점수·이름·주황 버튼, 오른쪽 가운데에 각 3D 아이콘이 올라갑니다.
---
## 1. 공통 규격 (모든 요청에 붙여 넣기)
```
너는 한국 날씨 웹서비스 '날씨각'의 일러스트레이터야. 아래 목록마다 피드 포스트 배경 그림을 한 장씩 만들어 줘.
규격
- 1080 × 1350 PNG (세로 4:5), 불투명 배경
- 글자, 숫자, 로고, 워터마크 넣지 않기
- 그 각의 대표 사물(아이콘에 그려진 것)은 그리지 않기. 아이콘은 나중에 위에 따로 얹는다
- 사람 얼굴 넣지 않기. 사람이 꼭 필요하면 아주 작은 뒷모습 실루엣까지만
- 실존 브랜드·간판 그리지 않기
글자 자리(꼭 지키기)
- 위 왼쪽 약 40%(가로 60% × 세로 40%): 하늘·여백처럼 낮은 대비, 작은 디테일 없음
- 아래 왼쪽 약 35%(가로 60% × 세로 35%): 바닥·언덕처럼 평평하고 차분하게
- 오른쪽 가운데(가로 55~100%, 세로 30~70%): 비워 두기. 큰 오브젝트 놓지 않기
- 장면의 볼거리는 오른쪽 위·오른쪽 아래·가장자리로 보낸다
결과물
- 파일 이름: 아래 목록의 id 그대로 (예: bike.png). 변형이 여럿이면 bike-a.png, bike-b.png …
- 행사·포스트 종류 배경은 event-a.png, sunset.png 처럼 표의 id 그대로
- 모든 결과를 한 장에 모은 미리보기(contact-sheet.png)
- 저장 위치: ./generated-images/post-bg/
- 실제로 쓴 프롬프트를 ./generated-images/post-bg/prompts.txt 에 남기기
```
## 2. 스타일 (공통 규격 바로 아래에 붙여 넣기)
```
스타일: 말랑한 파스텔 3D 디오라마 배경
- 참고: 붙인 아이콘 이미지는 질감·빛 참고용. 주제는 따라 하지 않기
- 재질: 무광 클레이·매끈한 새틴. 둥근 모서리, 단순한 큰 면, 부드러운 그라데이션. 외곽선·사실적 질감 금지
- 빛: 왼쪽 위에서 오는 부드러운 빛, 그림자는 옅게
- 색: 밝은 파스텔 한 가지 바탕(라일락 #D8CFFC, 하늘 #BFE3FF, 민트 #BFECD6, 버터 #FFE7A0, 피치 #FFD2BB 중 장면에 맞는 것) + 포인트 2~3색. 주황(#FF7A45)은 점수 색과 겹치니 넓게 쓰지 않기
- 밤 장면(행사·밤 각): 짙은 남색 #1F2658 → #3D3F86 바탕, 포인트는 노랑·분홍·하늘 빛
- 디테일은 적게. 피드에서 작게 보여도 장면이 한눈에 읽히게
```
## 3. 변형 4종 (대표 각·행사에만)
| 변형 | 낮 각 (예: 자전거각) | 행사 (밤) |
|---|---|---|
| a | 대표 풍경 (라일락 언덕과 굽은 길) | 도시 야경 스카이라인과 불꽃놀이 |
| b | 하늘·물가 (하늘색 강·다리, 해와 구름) | 보라·파랑 빛의 물결 |
| c | 지도 느낌 (옅은 지도 위 경로 핀·나무) | 색종이 꽃가루 |
| d | 추상 (파스텔 원 겹침) | 어두운 바탕 추상 원 |
## 4. 각 목록 (68개)
| id | 각 | 배경 장면 |
|---|---|---|
| yajang | 야장각 | 저녁 골목, 오른쪽 위 전구 줄과 따뜻한 창 불빛, 남보라 하늘 |
| picnic | 피크닉각 | 민트 잔디 언덕과 둥근 나무, 오른쪽 아래 작은 꽃밭, 맑은 하늘 |
| chimaek | 치맥각 | 초저녁 강변 공원, 오른쪽 위 가로등과 별 하나 |
| walk | 산책각 | 해 진 뒤 가로수길, 둥근 가로등이 이어지는 길 |
| vent | 환기각 | 하늘색 바탕에 흩날리는 커튼 자락과 바람 줄기(오른쪽 위) |
| hiking | 등산각 | 아침 빛 겹겹이 이어지는 둥근 산 능선, 오른쪽 위 봉우리 |
| carwash | 세차각 | 맑게 갠 하늘과 물방울 반짝임, 바닥에 옅은 물웅덩이 |
| camping | 캠핑각 | 해 질 녘 숲가 언덕, 오른쪽 아래 소나무 실루엣, 첫 별 |
| running | 러닝각 | 아침 강변 트랙이 오른쪽 아래로 휘어 나가는 풍경 |
| stars | 별보기각 | 짙은 남색 밤하늘 은하수, 아래 어두운 둥근 언덕 |
| jjamppong | 짬뽕각 | 비 오는 창밖 흐린 거리, 유리창 빗방울 |
| makgeolli | 막걸리각 | 비 내리는 한옥 처마 끝 빗줄기, 회청색 하늘 |
| iced_hot | 뜨아각 | 반은 여름 하늘, 반은 가을 단풍으로 나뉜 하늘 |
| laundry | 빨래각 | 쨍한 하늘과 둥실한 흰 구름, 오른쪽 위 작은 해 |
| bike | 자전거각 | 라일락 언덕 사이로 굽이치는 길 (변형 4종은 3절) |
| dog | 멍뭉산책각 | 민트 잔디 공원 산책로와 둥근 덤불 |
| glasses | 김서림각 | 추운 겨울 거리, 따뜻한 가게 창 김 서린 빛 |
| makeup | 화장붕괴각 | 후텁지근한 한여름 아지랑이 하늘, 노란 햇빛 |
| naengmyeon | 냉면각 | 한여름 쨍한 하늘과 반짝이는 얼음 결정 무늬 |
| taxi | 택시대란각 | 비 오는 밤 도시 대로, 번지는 신호등 불빛 |
| delivery | 배달폭주각 | 비 오는 밤 아파트 단지 창 불빛 |
| garden | 가드닝각 | 버터색 햇살 비치는 작은 텃밭 이랑 |
| photo | 사진산책각 | 노을빛 골목길, 피치·라일락 하늘 |
| baseball | 야구각 | 저녁 야구장 조명탑 불빛과 초록 잔디(관중 없이) |
| study | 공부각 | 비 오는 창가 책상 너머 흐린 바깥 |
| netflix | 넷플릭스각 | 어두운 거실 창밖 빗줄기, 은은한 화면 빛 |
| chestnut | 군밤각 | 초겨울 저녁 길거리, 노점 불빛 번짐 |
| golf | 골프각 | 부드러운 초록 페어웨이 언덕과 맑은 하늘 |
| jipkok | 집콕각 | 창밖 잿빛 비, 안쪽은 따뜻한 피치색 방 |
| fishing | 낚시각 | 새벽 안개 낀 잔잔한 호수와 둥근 산 |
| drive | 드라이브각 | 해안 도로가 오른쪽으로 휘어 가는 맑은 날 |
| kite | 연날리기각 | 넓은 하늘색 하늘과 낮은 들판, 바람 줄기 |
| waterplay | 물놀이각 | 맑은 바다 물결과 모래사장 가장자리 |
| kimjang | 김장각 | 늦가을 시골 마당 장독대(오른쪽 아래), 맑은 하늘 |
| flower | 꽃구경각 | 벚꽃 가로수 길, 분홍 꽃잎 흩날림 |
| blanket | 이불빨래각 | 옥상 너머 쨍한 하늘과 바람에 흔들리는 구름 |
| bingsu | 빙수각 | 한여름 버터색 햇빛과 아지랑이 하늘 |
| indoordry | 실내건조각 | 비 오는 날 창 안쪽 흐린 빛, 습한 공기 |
| riverwind | 한강밤바람각 | 밤 강가, 다리 불빛이 물에 비친 남색 장면 |
| foliage | 단풍각 | 붉고 노란 둥근 단풍 산 |
| silvergrass | 억새각 | 해 질 녘 은빛 억새 언덕 |
| sweetpotato | 군고구마각 | 초겨울 해 질 녘 골목, 연기 한 줄기 |
| sunrise | 해돋이각 | 새벽 바다 수평선 위로 떠오르는 해 빛(오른쪽 위) |
| snowman | 눈사람각 | 눈 덮인 둥근 언덕과 흰 하늘 |
| bungeoppang | 붕어빵각 | 초겨울 저녁 거리, 노점 따뜻한 불빛 |
| tangerine | 귤까먹기각 | 겨울밤 창밖 눈, 안쪽은 따뜻한 방 빛 |
| umbrella | 우산각 | 회청색 하늘과 비스듬한 빗줄기 |
| pajeon | 파전각 | 비 오는 처마 밑 빗줄기, 따뜻한 창 불빛 |
| mood_song | 감성노래각 | 빗방울 맺힌 유리창 너머 번지는 불빛 |
| trot | 트로트각 | 봄 나들이 길, 꽃 핀 가로수와 맑은 하늘 |
| singing_rain | 싱잉인더레인각 | 비 오는 거리 바닥 물웅덩이에 비친 가로등 |
| umbrella_lost | 우산분실각 | 비 그친 뒤 갠 하늘, 물웅덩이와 작은 무지개 |
| traffic | 교통체증각 | 비 오는 출근길 도로, 멀리 번지는 차 불빛 |
| hangang | 한강각 | 넓은 강과 아치 다리, 강가 잔디, 오후 빛 |
| themepark | 놀이공원각 | 멀리 관람차·회전목마 실루엣(오른쪽 위), 맑은 하늘 |
| date | 데이트각 | 노을 무렵 강변 산책로와 가로등 |
| frizz | 곱슬머리각 | 습한 안개 낀 아침 거리 |
| boiler | 보일러각 | 겨울밤 아파트 창 불빛과 서리 |
| sunscreen | 선크림각 | 강한 한낮 해와 하얀 모래, 하늘색 바다 |
| mosquito | 모기각 | 여름밤 풀숲과 반딧불 같은 작은 빛 |
| tennis | 테니스각 | 아침 빛 야외 코트 가장자리 철망과 나무 |
| hyodo | 효도각 | 맑은 날 수목원 산책길과 둥근 나무 |
| thanks | 감사각 | 저녁 창가, 따뜻한 노을빛 하늘 |
| gift | 선물각 | 봄 오후 꽃집 골목, 파스텔 차양 |
| party | 파티각 | 저녁 실내 창가, 전구 줄과 남보라 밤하늘 |
| game | 게임각 | 어두운 방 창밖 밤 도시, 은은한 보라 빛 |
| selfie | 셀카각 | 자연광 가득한 창가, 피치색 햇살 |
| sentimental | 센치각 | 저녁 비 그친 골목, 라일락·남색 하늘 |
## 5. 포스트 종류 배경 (각이 아닌 슬라이드)
| id | 포스트 종류 | 배경 장면 |
|---|---|---|
| event-a~d | 가까운 행사 | 3절 행사 변형 4종 (짙은 남색) |
| weather | 오늘 날씨 | 하늘색 하늘과 둥근 구름 몇 개 |
| sunset | 노을 | 라일락→분홍→주황 노을 하늘, 아래 낮은 도시 실루엣 |
| season | 계절 소식 | 계절 나무가 늘어선 둥근 언덕(가을 단풍 기본) |
| tip | 날씨 상식 | 하늘색 추상 구름·바람 줄기 |
| week | 주말 예보 | 민트 바탕, 멀리 이어지는 언덕 길 |
| alert | 생활 알림 | 라일락 바탕 흐린 하늘, 옅은 빗줄기 |
| tomorrow | 내일 미리보기 | 해 진 직후 남보라 하늘과 첫 별 |
| quote | 오늘의 한 문장 | 피치 바탕 추상 파스텔 원 |
| weekend_plan | 주말 플랜 | 버터색 바탕, 나들이 길과 둥근 나무 |
| air | 미세먼지 | 맑은 민트 하늘과 바람 줄기 |
| day_trip | 당일치기 | 기찻길이 오른쪽 아래로 이어지는 들판 |
| moon | 오늘 밤 달 | 짙은 남색 밤하늘, 오른쪽 위 달빛 번짐(달은 작게) |
| uv | 자외선 | 강한 버터색 햇살과 하늘 |
---
## 6. 받은 뒤 할 일
- Claude가 확인: 글자 없음, 글자 자리 비어 있음, 오른쪽 가운데 비어 있음, 세트 통일감, 파일 이름·크기
- 마음에 안 드는 것만 id로 골라 "bike-c, event-b만 같은 규칙으로 다시" 처럼 다시 요청
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen';
import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
import { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, 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, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
export type QueryKey<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -466,7 +466,7 @@ export const unlikePostMutation = (options?: Partial<Options<UnlikePostData>>):
};
/**
* 좋아요
* 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likePostMutation = (options?: Partial<Options<LikePostData>>): UseMutationOptions<LikePostResponse, LikePostError, Options<LikePostData>> => {
const mutationOptions: UseMutationOptions<LikePostResponse, LikePostError, Options<LikePostData>> = {
@@ -693,7 +693,7 @@ export const unlikeCommentMutation = (options?: Partial<Options<UnlikeCommentDat
};
/**
* 댓글 좋아요
* 댓글 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>): UseMutationOptions<LikeCommentResponse, LikeCommentError, Options<LikeCommentData>> => {
const mutationOptions: UseMutationOptions<LikeCommentResponse, LikeCommentError, Options<LikeCommentData>> = {
@@ -709,6 +709,260 @@ export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>)
return mutationOptions;
};
export const listMyGakQueryKey = (options?: Options<ListMyGakData>) => createQueryKey('listMyGak', options);
/**
* 내 각 목록 (로그인하지 않았으면 빈 목록)
*/
export const listMyGakOptions = (options?: Options<ListMyGakData>) => queryOptions<ListMyGakResponse, ListMyGakError, ListMyGakResponse, ReturnType<typeof listMyGakQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listMyGak({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listMyGakQueryKey(options)
});
/**
* 이름과 날씨 조건으로 내 각 만들기
*/
export const addMyGakMutation = (options?: Partial<Options<AddMyGakData>>): UseMutationOptions<AddMyGakResponse, AddMyGakError, Options<AddMyGakData>> => {
const mutationOptions: UseMutationOptions<AddMyGakResponse, AddMyGakError, Options<AddMyGakData>> = {
mutationFn: async (fnOptions) => {
const { data } = await addMyGak({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)
*/
export const scoreMyGakMutation = (options?: Partial<Options<ScoreMyGakData>>): UseMutationOptions<ScoreMyGakResponse, ScoreMyGakError, Options<ScoreMyGakData>> => {
const mutationOptions: UseMutationOptions<ScoreMyGakResponse, ScoreMyGakError, Options<ScoreMyGakData>> = {
mutationFn: async (fnOptions) => {
const { data } = await scoreMyGak({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 내 각 지우기
*/
export const deleteMyGakMutation = (options?: Partial<Options<DeleteMyGakData>>): UseMutationOptions<DeleteMyGakResponse, DeleteMyGakError, Options<DeleteMyGakData>> => {
const mutationOptions: UseMutationOptions<DeleteMyGakResponse, DeleteMyGakError, Options<DeleteMyGakData>> = {
mutationFn: async (fnOptions) => {
const { data } = await deleteMyGak({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const listTalksQueryKey = (options?: Options<ListTalksData>) => createQueryKey('listTalks', options);
/**
* 동네 이야기 (전국, 최신순, 로그인 없이 보기)
*/
export const listTalksOptions = (options?: Options<ListTalksData>) => queryOptions<ListTalksResponse, ListTalksError, ListTalksResponse, ReturnType<typeof listTalksQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listTalks({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listTalksQueryKey(options)
});
export const listTalksInfiniteQueryKey = (options?: Options<ListTalksData>): QueryKey<Options<ListTalksData>> => createQueryKey('listTalks', options, true);
/**
* 동네 이야기 (전국, 최신순, 로그인 없이 보기)
*/
export const listTalksInfiniteOptions = (options?: Options<ListTalksData>) => {
const opts = infiniteQueryOptions<ListTalksResponse, ListTalksError, InfiniteData<ListTalksResponse>, QueryKey<Options<ListTalksData>>, number | null | Pick<QueryKey<Options<ListTalksData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<QueryKey<Options<ListTalksData>>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : {
query: {
cursor: pageParam
}
};
const params = createInfiniteParams(queryKey, page);
const { data } = await listTalks({
...options,
...params,
signal,
throwOnError: true
});
return data;
},
queryKey: listTalksInfiniteQueryKey(options)
});
return opts as Omit<typeof opts, 'initialData'>;
};
/**
* 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)
*/
export const addTalkMutation = (options?: Partial<Options<AddTalkData>>): UseMutationOptions<AddTalkResponse, AddTalkError, Options<AddTalkData>> => {
const mutationOptions: UseMutationOptions<AddTalkResponse, AddTalkError, Options<AddTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await addTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)
*/
export const uploadTalkImageMutation = (options?: Partial<Options<UploadTalkImageData>>): UseMutationOptions<UploadTalkImageResponse, UploadTalkImageError, Options<UploadTalkImageData>> => {
const mutationOptions: UseMutationOptions<UploadTalkImageResponse, UploadTalkImageError, Options<UploadTalkImageData>> = {
mutationFn: async (fnOptions) => {
const { data } = await uploadTalkImage({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const getTalkImageQueryKey = (options: Options<GetTalkImageData>) => createQueryKey('getTalkImage', options);
/**
* 올린 사진
*/
export const getTalkImageOptions = (options: Options<GetTalkImageData>) => queryOptions<unknown, GetTalkImageError, unknown, ReturnType<typeof getTalkImageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTalkImage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTalkImageQueryKey(options)
});
/**
* 내 이야기 지우기
*/
export const deleteTalkMutation = (options?: Partial<Options<DeleteTalkData>>): UseMutationOptions<DeleteTalkResponse, DeleteTalkError, Options<DeleteTalkData>> => {
const mutationOptions: UseMutationOptions<DeleteTalkResponse, DeleteTalkError, Options<DeleteTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await deleteTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이야기 좋아요 취소
*/
export const unlikeTalkMutation = (options?: Partial<Options<UnlikeTalkData>>): UseMutationOptions<UnlikeTalkResponse, UnlikeTalkError, Options<UnlikeTalkData>> => {
const mutationOptions: UseMutationOptions<UnlikeTalkResponse, UnlikeTalkError, Options<UnlikeTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await unlikeTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이야기 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeTalkMutation = (options?: Partial<Options<LikeTalkData>>): UseMutationOptions<LikeTalkResponse, LikeTalkError, Options<LikeTalkData>> => {
const mutationOptions: UseMutationOptions<LikeTalkResponse, LikeTalkError, Options<LikeTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await likeTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이야기 신고 (서로 다른 3명이면 숨김)
*/
export const reportTalkMutation = (options?: Partial<Options<ReportTalkData>>): UseMutationOptions<ReportTalkResponse, ReportTalkError, Options<ReportTalkData>> => {
const mutationOptions: UseMutationOptions<ReportTalkResponse, ReportTalkError, Options<ReportTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await reportTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이 글 쓴 사람의 글 안 보기
*/
export const blockTalkAuthorMutation = (options?: Partial<Options<BlockTalkAuthorData>>): UseMutationOptions<BlockTalkAuthorResponse, BlockTalkAuthorError, Options<BlockTalkAuthorData>> => {
const mutationOptions: UseMutationOptions<BlockTalkAuthorResponse, BlockTalkAuthorError, Options<BlockTalkAuthorData>> = {
mutationFn: async (fnOptions) => {
const { data } = await blockTalkAuthor({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const getWatchSummaryQueryKey = (options: Options<GetWatchSummaryData>) => createQueryKey('getWatchSummary', options);
/**
@@ -745,6 +999,42 @@ export const getImageOptions = (options: Options<GetImageData>) => queryOptions<
queryKey: getImageQueryKey(options)
});
export const getTodayPageQueryKey = (options: Options<GetTodayPageData>) => createQueryKey('getTodayPage', options);
/**
* 지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)
*/
export const getTodayPageOptions = (options: Options<GetTodayPageData>) => queryOptions<GetTodayPageResponse, GetTodayPageError, GetTodayPageResponse, ReturnType<typeof getTodayPageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTodayPage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTodayPageQueryKey(options)
});
export const getTodayGuPageQueryKey = (options: Options<GetTodayGuPageData>) => createQueryKey('getTodayGuPage', options);
/**
* 구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)
*/
export const getTodayGuPageOptions = (options: Options<GetTodayGuPageData>) => queryOptions<GetTodayGuPageResponse, GetTodayGuPageError, GetTodayGuPageResponse, ReturnType<typeof getTodayGuPageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTodayGuPage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTodayGuPageQueryKey(options)
});
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
/**
+1 -1
View File
@@ -13,4 +13,4 @@ import type { ClientOptions as ClientOptions2 } from './types.gen';
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export const client: Client = createClient(createConfig<ClientOptions2>({ baseUrl: 'http://localhost:9810', throwOnError: true }));
export const client: Client = createClient(createConfig<ClientOptions2>({ baseUrl: 'http://localhost:9811', throwOnError: true }));
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, typeLine truncated
export { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, 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, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type ClientOptions, type CommentData, type CommuteData, Confidence, 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 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 GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type MyGakRule, type MyGakScore, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceDatLine truncated
+115 -4
View File
@@ -1,8 +1,8 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Client, ClientMeta, Options as Options2, RequestResult, 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 type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, 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, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, 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> & {
/**
@@ -167,7 +167,7 @@ export const updateMe = <ThrowOnError extends boolean = true>(options: Options<U
export const unlikePost = <ThrowOnError extends boolean = true>(options: Options<UnlikePostData, ThrowOnError>): RequestResult<UnlikePostResponses, UnlikePostErrors, ThrowOnError> => (options.client ?? client).delete<UnlikePostResponses, UnlikePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/like', ...options });
/**
* 좋아요
* 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likePost = <ThrowOnError extends boolean = true>(options: Options<LikePostData, ThrowOnError>): RequestResult<LikePostResponses, LikePostErrors, ThrowOnError> => (options.client ?? client).post<LikePostResponses, LikePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/like', ...options });
@@ -214,10 +214,111 @@ export const deleteComment = <ThrowOnError extends boolean = true>(options: Opti
export const unlikeComment = <ThrowOnError extends boolean = true>(options: Options<UnlikeCommentData, ThrowOnError>): RequestResult<UnlikeCommentResponses, UnlikeCommentErrors, ThrowOnError> => (options.client ?? client).delete<UnlikeCommentResponses, UnlikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
/**
* 댓글 좋아요
* 댓글 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeComment = <ThrowOnError extends boolean = true>(options: Options<LikeCommentData, ThrowOnError>): RequestResult<LikeCommentResponses, LikeCommentErrors, ThrowOnError> => (options.client ?? client).post<LikeCommentResponses, LikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
/**
* 내 각 목록 (로그인하지 않았으면 빈 목록)
*/
export const listMyGak = <ThrowOnError extends boolean = true>(options?: Options<ListMyGakData, ThrowOnError>): RequestResult<ListMyGakResponses, ListMyGakErrors, ThrowOnError> => (options?.client ?? client).get<ListMyGakResponses, ListMyGakErrors, ThrowOnError>({ url: '/v1/my-gak', ...options });
/**
* 이름과 날씨 조건으로 내 각 만들기
*/
export const addMyGak = <ThrowOnError extends boolean = true>(options: Options<AddMyGakData, ThrowOnError>): RequestResult<AddMyGakResponses, AddMyGakErrors, ThrowOnError> => (options.client ?? client).post<AddMyGakResponses, AddMyGakErrors, ThrowOnError>({
url: '/v1/my-gak',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)
*/
export const scoreMyGak = <ThrowOnError extends boolean = true>(options: Options<ScoreMyGakData, ThrowOnError>): RequestResult<ScoreMyGakResponses, ScoreMyGakErrors, ThrowOnError> => (options.client ?? client).post<ScoreMyGakResponses, ScoreMyGakErrors, ThrowOnError>({
url: '/v1/my-gak/score',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 내 각 지우기
*/
export const deleteMyGak = <ThrowOnError extends boolean = true>(options: Options<DeleteMyGakData, ThrowOnError>): RequestResult<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError> => (options.client ?? client).delete<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError>({ url: '/v1/my-gak/{my_gak_id}', ...options });
/**
* 동네 이야기 (전국, 최신순, 로그인 없이 보기)
*/
export const listTalks = <ThrowOnError extends boolean = true>(options?: Options<ListTalksData, ThrowOnError>): RequestResult<ListTalksResponses, ListTalksErrors, ThrowOnError> => (options?.client ?? client).get<ListTalksResponses, ListTalksErrors, ThrowOnError>({ url: '/v1/talk/list', ...options });
/**
* 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)
*/
export const addTalk = <ThrowOnError extends boolean = true>(options: Options<AddTalkData, ThrowOnError>): RequestResult<AddTalkResponses, AddTalkErrors, ThrowOnError> => (options.client ?? client).post<AddTalkResponses, AddTalkErrors, ThrowOnError>({
url: '/v1/talk',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)
*/
export const uploadTalkImage = <ThrowOnError extends boolean = true>(options: Options<UploadTalkImageData, ThrowOnError>): RequestResult<UploadTalkImageResponses, UploadTalkImageErrors, ThrowOnError> => (options.client ?? client).post<UploadTalkImageResponses, UploadTalkImageErrors, ThrowOnError>({
...formDataBodySerializer,
url: '/v1/talk/image',
...options,
headers: {
'Content-Type': null,
...options.headers
}
});
/**
* 올린 사진
*/
export const getTalkImage = <ThrowOnError extends boolean = true>(options: Options<GetTalkImageData, ThrowOnError>): RequestResult<GetTalkImageResponses, GetTalkImageErrors, ThrowOnError> => (options.client ?? client).get<GetTalkImageResponses, GetTalkImageErrors, ThrowOnError>({ url: '/v1/talk/image/{name}', ...options });
/**
* 내 이야기 지우기
*/
export const deleteTalk = <ThrowOnError extends boolean = true>(options: Options<DeleteTalkData, ThrowOnError>): RequestResult<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError> => (options.client ?? client).delete<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}', ...options });
/**
* 이야기 좋아요 취소
*/
export const unlikeTalk = <ThrowOnError extends boolean = true>(options: Options<UnlikeTalkData, ThrowOnError>): RequestResult<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError> => (options.client ?? client).delete<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
/**
* 이야기 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeTalk = <ThrowOnError extends boolean = true>(options: Options<LikeTalkData, ThrowOnError>): RequestResult<LikeTalkResponses, LikeTalkErrors, ThrowOnError> => (options.client ?? client).post<LikeTalkResponses, LikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
/**
* 이야기 신고 (서로 다른 3명이면 숨김)
*/
export const reportTalk = <ThrowOnError extends boolean = true>(options: Options<ReportTalkData, ThrowOnError>): RequestResult<ReportTalkResponses, ReportTalkErrors, ThrowOnError> => (options.client ?? client).post<ReportTalkResponses, ReportTalkErrors, ThrowOnError>({
url: '/v1/talk/{talk_id}/report',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 이 글 쓴 사람의 글 안 보기
*/
export const blockTalkAuthor = <ThrowOnError extends boolean = true>(options: Options<BlockTalkAuthorData, ThrowOnError>): RequestResult<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError> => (options.client ?? client).post<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/block', ...options });
/**
* 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표
*/
@@ -228,6 +329,16 @@ export const getWatchSummary = <ThrowOnError extends boolean = true>(options: Op
*/
export const getImage = <ThrowOnError extends boolean = true>(options: Options<GetImageData, ThrowOnError>): RequestResult<GetImageResponses, GetImageErrors, ThrowOnError> => (options.client ?? client).get<GetImageResponses, GetImageErrors, ThrowOnError>({ url: '/v1/image', ...options });
/**
* 지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)
*/
export const getTodayPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayPageData, ThrowOnError>): RequestResult<GetTodayPageResponses, GetTodayPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayPageResponses, GetTodayPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}', ...options });
/**
* 구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)
*/
export const getTodayGuPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayGuPageData, ThrowOnError>): RequestResult<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}/{gu}', ...options });
/**
* 헬스체크
*/
+873 -1
View File
@@ -1,7 +1,7 @@
// This file is auto-generated by @hey-api/openapi-ts
export type ClientOptions = {
baseUrl: `${string}://${string}` | (string & {});
baseUrl: 'http://localhost:9811' | (string & {});
};
/**
@@ -238,6 +238,16 @@ export type BestTime = {
end?: string | null;
};
/**
* Body_upload_talk_image_v1_talk_image_post
*/
export type BodyUploadTalkImageV1TalkImagePost = {
/**
* File
*/
file: Blob | File;
};
/**
* CommentData
*/
@@ -830,6 +840,101 @@ export type Me = {
provider: AuthProvider;
};
/**
* MyGakData
*/
export type MyGakData = {
/**
* My Gak Id
*/
my_gak_id: number;
/**
* Name
*/
name: string;
rule: MyGakRule;
};
/**
* MyGakRule
*/
export type MyGakRule = {
/**
* Temp
*
* 체감온도 범위 [최저, 최고]° (-20~40)
*/
temp?: [
number,
number
] | null;
/**
* Rain
*
* dry: 비 안 와야 / wet: 비 와야 / 없으면 상관없음
*/
rain?: 'dry' | 'wet' | null;
/**
* Wind Max
*
* 바람 상한 m/s
*/
wind_max?: number | null;
/**
* Air
*
* 미세먼지 허용 단계: good 좋음까지 / normal 보통까지
*/
air?: 'good' | 'normal' | null;
/**
* Humidity
*
* 습도 범위 [최저, 최고]%
*/
humidity?: [
number,
number
] | null;
/**
* Slots
*
* 볼 시간대
*/
slots?: Array<'morning' | 'day' | 'evening' | 'night'>;
};
/**
* MyGakScore
*/
export type MyGakScore = {
/**
* Score
*
* 지금 시간대 점수. 지금이 고른 시간대가 아니면 고른 시간대 중 가장 좋은 점수. 예보가 없으면 null
*/
score?: number | null;
/**
* Slot
*
* score 가 어느 시간대 점수인지
*/
slot?: 'morning' | 'day' | 'evening' | 'night' | null;
/**
* Slots
*
* 고른 시간대별 점수 (아침·낮·저녁·밤 순)
*/
slots?: {
[key: string]: number;
};
/**
* Reasons
*
* score 근거: 조건마다 그 시간대 실제 값
*/
reasons?: Array<string>;
};
/**
* PlaceData
*/
@@ -1219,6 +1324,33 @@ export type ReqLogin = {
password: string;
};
/**
* Req_MyGak
*/
export type ReqMyGak = {
/**
* Name
*
* 내 각 이름 (끝에 '각'이 없으면 붙인다)
*/
name: string;
rule: MyGakRule;
};
/**
* Req_MyGakScore
*/
export type ReqMyGakScore = {
/**
* Region Code
*/
region_code: string;
/**
* Rules
*/
rules: Array<MyGakRule>;
};
/**
* Req_Refresh
*/
@@ -1247,6 +1379,35 @@ export type ReqSignup = {
nickname: string;
};
/**
* Req_Talk
*/
export type ReqTalk = {
/**
* Region Code
*/
region_code: string;
/**
* Body
*
* 공백을 줄인 뒤 100자까지
*/
body: string;
/**
* Image
*
* 먼저 올린 사진 주소 (POST /v1/talk/image 결과)
*/
image?: string | null;
};
/**
* Req_TalkReport
*/
export type ReqTalkReport = {
reason: TalkReport;
};
/**
* Req_UpdateMe
*/
@@ -1535,6 +1696,54 @@ export type ResMe = {
me?: Me | null;
};
/**
* Res_MyGak
*/
export type ResMyGak = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
item?: MyGakData | null;
};
/**
* Res_MyGakList
*/
export type ResMyGakList = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Items
*
* 내 각. 로그인하지 않았으면 비어 있음
*/
items?: Array<MyGakData>;
};
/**
* Res_MyGakScore
*/
export type ResMyGakScore = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Now Slot
*/
now_slot?: 'morning' | 'day' | 'evening' | 'night' | null;
/**
* Scores
*/
scores?: Array<MyGakScore>;
};
/**
* Res_PlaceList
*/
@@ -1760,6 +1969,73 @@ export type ResSkyRanking = {
items?: Array<RankData>;
};
/**
* Res_Talk
*/
export type ResTalk = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
talk?: TalkData | null;
};
/**
* Res_TalkImage
*/
export type ResTalkImage = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Image
*
* 글에 붙일 사진 주소
*/
image?: string | null;
};
/**
* Res_TalkLike
*/
export type ResTalkLike = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Liked
*/
liked?: boolean | null;
/**
* Like Count
*/
like_count?: number | null;
};
/**
* Res_TalkList
*/
export type ResTalkList = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Talks
*/
talks?: Array<TalkData>;
/**
* Next Cursor
*/
next_cursor?: number | null;
};
/**
* Res_WatchSummary
*/
@@ -2365,6 +2641,97 @@ export type SunsetSlide = {
peak_at?: string | null;
};
/**
* TalkData
*/
export type TalkData = {
/**
* Talk Id
*/
talk_id: number;
/**
* Nickname
*/
nickname: string;
/**
* Character
*/
character: string;
/**
* Color
*/
color: string;
/**
* Mood
*/
mood?: string | null;
/**
* Region Name
*
* 쓴 사람이 고른 동네 (성남시 분당구)
*/
region_name?: string | null;
/**
* Weather
*
* 쓸 때 그 동네 날씨 (18° 맑음)
*/
weather?: string | null;
/**
* Body
*/
body: string;
/**
* Image
*
* 올린 사진 주소
*/
image?: string | null;
/**
* Like Count
*/
like_count: number;
/**
* Liked
*/
liked: boolean;
/**
* Mine
*/
mine: boolean;
/**
* Created At
*/
created_at: string;
};
/**
* TalkReport
*/
export const TalkReport = {
/**
* ABUSE
*/
ABUSE: 1,
/**
* SPAM
*/
SPAM: 2,
/**
* PRIVACY
*/
PRIVACY: 3,
/**
* ETC
*/
ETC: 4
} as const;
/**
* TalkReport
*/
export type TalkReport = typeof TalkReport[keyof typeof TalkReport];
/**
* TermData
*/
@@ -2635,6 +3002,10 @@ export type WatchNow = {
* Rain 2H
*/
rain_2h?: boolean | null;
/**
* Thunder
*/
thunder?: boolean | null;
/**
* Text
*/
@@ -3955,6 +4326,435 @@ export type LikeCommentResponses = {
export type LikeCommentResponse = LikeCommentResponses[keyof LikeCommentResponses];
export type ListMyGakData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: never;
url: '/v1/my-gak';
};
export type ListMyGakErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type ListMyGakError = ListMyGakErrors[keyof ListMyGakErrors];
export type ListMyGakResponses = {
/**
* Successful Response
*/
200: ResMyGakList;
};
export type ListMyGakResponse = ListMyGakResponses[keyof ListMyGakResponses];
export type AddMyGakData = {
body: ReqMyGak;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: never;
url: '/v1/my-gak';
};
export type AddMyGakErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type AddMyGakError = AddMyGakErrors[keyof AddMyGakErrors];
export type AddMyGakResponses = {
/**
* Successful Response
*/
200: ResMyGak;
};
export type AddMyGakResponse = AddMyGakResponses[keyof AddMyGakResponses];
export type ScoreMyGakData = {
body: ReqMyGakScore;
path?: never;
query?: never;
url: '/v1/my-gak/score';
};
export type ScoreMyGakErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type ScoreMyGakError = ScoreMyGakErrors[keyof ScoreMyGakErrors];
export type ScoreMyGakResponses = {
/**
* Successful Response
*/
200: ResMyGakScore;
};
export type ScoreMyGakResponse = ScoreMyGakResponses[keyof ScoreMyGakResponses];
export type DeleteMyGakData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path: {
/**
* My Gak Id
*/
my_gak_id: number;
};
query?: never;
url: '/v1/my-gak/{my_gak_id}';
};
export type DeleteMyGakErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type DeleteMyGakError = DeleteMyGakErrors[keyof DeleteMyGakErrors];
export type DeleteMyGakResponses = {
/**
* Successful Response
*/
200: ResWebPacketProtocol;
};
export type DeleteMyGakResponse = DeleteMyGakResponses[keyof DeleteMyGakResponses];
export type ListTalksData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: {
/**
* Cursor
*/
cursor?: number | null;
};
url: '/v1/talk/list';
};
export type ListTalksErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type ListTalksError = ListTalksErrors[keyof ListTalksErrors];
export type ListTalksResponses = {
/**
* Successful Response
*/
200: ResTalkList;
};
export type ListTalksResponse = ListTalksResponses[keyof ListTalksResponses];
export type AddTalkData = {
body: ReqTalk;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: never;
url: '/v1/talk';
};
export type AddTalkErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type AddTalkError = AddTalkErrors[keyof AddTalkErrors];
export type AddTalkResponses = {
/**
* Successful Response
*/
200: ResTalk;
};
export type AddTalkResponse = AddTalkResponses[keyof AddTalkResponses];
export type UploadTalkImageData = {
body: BodyUploadTalkImageV1TalkImagePost;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: never;
url: '/v1/talk/image';
};
export type UploadTalkImageErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type UploadTalkImageError = UploadTalkImageErrors[keyof UploadTalkImageErrors];
export type UploadTalkImageResponses = {
/**
* Successful Response
*/
200: ResTalkImage;
};
export type UploadTalkImageResponse = UploadTalkImageResponses[keyof UploadTalkImageResponses];
export type GetTalkImageData = {
body?: never;
path: {
/**
* Name
*/
name: string;
};
query?: never;
url: '/v1/talk/image/{name}';
};
export type GetTalkImageErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetTalkImageError = GetTalkImageErrors[keyof GetTalkImageErrors];
export type GetTalkImageResponses = {
/**
* Successful Response
*/
200: unknown;
};
export type DeleteTalkData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path: {
/**
* Talk Id
*/
talk_id: number;
};
query?: never;
url: '/v1/talk/{talk_id}';
};
export type DeleteTalkErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type DeleteTalkError = DeleteTalkErrors[keyof DeleteTalkErrors];
export type DeleteTalkResponses = {
/**
* Successful Response
*/
200: ResWebPacketProtocol;
};
export type DeleteTalkResponse = DeleteTalkResponses[keyof DeleteTalkResponses];
export type UnlikeTalkData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path: {
/**
* Talk Id
*/
talk_id: number;
};
query?: never;
url: '/v1/talk/{talk_id}/like';
};
export type UnlikeTalkErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type UnlikeTalkError = UnlikeTalkErrors[keyof UnlikeTalkErrors];
export type UnlikeTalkResponses = {
/**
* Successful Response
*/
200: ResTalkLike;
};
export type UnlikeTalkResponse = UnlikeTalkResponses[keyof UnlikeTalkResponses];
export type LikeTalkData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path: {
/**
* Talk Id
*/
talk_id: number;
};
query?: never;
url: '/v1/talk/{talk_id}/like';
};
export type LikeTalkErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type LikeTalkError = LikeTalkErrors[keyof LikeTalkErrors];
export type LikeTalkResponses = {
/**
* Successful Response
*/
200: ResTalkLike;
};
export type LikeTalkResponse = LikeTalkResponses[keyof LikeTalkResponses];
export type ReportTalkData = {
body: ReqTalkReport;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path: {
/**
* Talk Id
*/
talk_id: number;
};
query?: never;
url: '/v1/talk/{talk_id}/report';
};
export type ReportTalkErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type ReportTalkError = ReportTalkErrors[keyof ReportTalkErrors];
export type ReportTalkResponses = {
/**
* Successful Response
*/
200: ResWebPacketProtocol;
};
export type ReportTalkResponse = ReportTalkResponses[keyof ReportTalkResponses];
export type BlockTalkAuthorData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path: {
/**
* Talk Id
*/
talk_id: number;
};
query?: never;
url: '/v1/talk/{talk_id}/block';
};
export type BlockTalkAuthorErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type BlockTalkAuthorError = BlockTalkAuthorErrors[keyof BlockTalkAuthorErrors];
export type BlockTalkAuthorResponses = {
/**
* Successful Response
*/
200: ResWebPacketProtocol;
};
export type BlockTalkAuthorResponse = BlockTalkAuthorResponses[keyof BlockTalkAuthorResponses];
export type GetWatchSummaryData = {
body?: never;
path?: never;
@@ -4031,6 +4831,78 @@ export type GetImageResponses = {
200: unknown;
};
export type GetTodayPageData = {
body?: never;
path: {
/**
* Sido
*/
sido: string;
/**
* Place
*/
place: string;
};
query?: never;
url: '/v1/seo/today/{sido}/{place}';
};
export type GetTodayPageErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetTodayPageError = GetTodayPageErrors[keyof GetTodayPageErrors];
export type GetTodayPageResponses = {
/**
* Successful Response
*/
200: string;
};
export type GetTodayPageResponse = GetTodayPageResponses[keyof GetTodayPageResponses];
export type GetTodayGuPageData = {
body?: never;
path: {
/**
* Sido
*/
sido: string;
/**
* Place
*/
place: string;
/**
* Gu
*/
gu: string;
};
query?: never;
url: '/v1/seo/today/{sido}/{place}/{gu}';
};
export type GetTodayGuPageErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type GetTodayGuPageError = GetTodayGuPageErrors[keyof GetTodayGuPageErrors];
export type GetTodayGuPageResponses = {
/**
* Successful Response
*/
200: string;
};
export type GetTodayGuPageResponse = GetTodayGuPageResponses[keyof GetTodayGuPageResponses];
export type HealthzHealthzGetData = {
body?: never;
path?: never;
+1 -1
View File
@@ -228,7 +228,7 @@ function Shell() {
<main className="relative z-[1]">
<Outlet />
</main>
<nav aria-label="주요 메뉴" className="b-tabbar fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t px-[max(4px,calc((100%-432px)/2))] pt-[7px] pb-[calc(8px+env(safe-area-inset-bottom,0px))] backdrop-blur-[10px]">
<nav aria-label="주요 메뉴" className="b-tabbar fixed inset-x-0 bottom-0 z-30 grid grid-cols-6 border-t px-[max(4px,calc((100%-432px)/2))] pt-[7px] pb-[calc(8px+env(safe-area-inset-bottom,0px))] backdrop-blur-[10px]">
{TABS.map((t) =>
t.key === 'today' ? (
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
+62 -9
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
import { createPortal } from 'react-dom'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
import { cx } from '../lib/utils'
@@ -7,7 +7,6 @@ import type { SlideBg } from './types'
import { deg } from './weatherText'
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import { useAuth } from './authContext'
import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
@@ -52,6 +51,22 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
const DARK = new Set<SlideBg>(['dusk', 'night'])
// 그림 배경이 있는 각(code)과 장 수. 여러 장이면 글마다 돌려 쓴다
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, camping: 1, stars: 1, walk: 1, hangang: 1 }
const EVENT_BG_N = 4
function bgImage(name: string, n: number, seed: number): CSSProperties {
const file = n > 1 ? `${name}-${'abcd'[seed % n]}` : name
return { backgroundImage: `url(/post-bg/${file}.webp)`, backgroundSize: 'cover', backgroundPosition: 'center' }
}
/** 그림 배경: 각은 각마다, 사진 없는 행사는 행사용. 없으면 색 배경만 */
function slideImage(post: PostData, slide: Slide): CSSProperties | undefined {
if (slide.kind === 'gak') return BG_IMAGES[slide.code] ? bgImage(slide.code, BG_IMAGES[slide.code], post.post_id) : undefined
if (post.post_type === PostType.EVENT && slide.kind === 'rows' && !slide.image) return bgImage('event', EVENT_BG_N, post.post_id)
return undefined
}
function Lines({ text }: { text: string }) {
return text.split('\n').map((t, i) => (
<span key={i}>
@@ -79,7 +94,7 @@ function Pic({ name, className }: { name: string; className?: string }) {
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
const { open } = useSheet()
if (slide.kind === 'hours') {
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
@@ -114,7 +129,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
}
if (slide.kind === 'gak')
return (
<div className={cx(slideBase, `b-bg-${bg}`)}>
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big>
<Pic name={slide.code} />
@@ -223,7 +238,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
</div>
)
return (
<div className={cx(slideBase, `b-bg-${bg}`)}>
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
<Big className="relative z-[1]">
<Lines text={slide.line} />
@@ -312,7 +327,6 @@ export function PostCardSkel() {
function FullCard({ post }: PostProps) {
const { open } = useSheet()
const { loggedIn } = useAuth()
const liked = !!post.liked
const likeCount = post.like_count
const queryClient = useQueryClient()
@@ -338,7 +352,6 @@ function FullCard({ post }: PostProps) {
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
const setLike = (on: boolean) => {
if (!loggedIn) return open({ type: 'login' })
if (on === liked || like.isPending || unlike.isPending) return
if (on) setPop((p) => p + 1)
setLikeFailed(0)
@@ -363,7 +376,7 @@ function FullCard({ post }: PostProps) {
if ((e.target as HTMLElement).closest('button')) return
const now = Date.now()
if (now - lastTap.current < 320) {
if (liked && loggedIn) setPop((p) => p + 1)
if (liked) setPop((p) => p + 1)
else setLike(true)
}
lastTap.current = now
@@ -401,7 +414,7 @@ function FullCard({ post }: PostProps) {
>
<div ref={trackRef} className="flex h-full">
{post.slides.map((s, i) => (
<SlideView key={i} slide={s} bg={bgs[i]} />
<SlideView key={i} slide={s} bg={bgs[i]} img={slideImage(post, s)} />
))}
</div>
</div>
@@ -457,3 +470,43 @@ function FullCard({ post }: PostProps) {
</article>
)
}
type FrameProps = { title: string; account: string; avatar: string; caption?: ReactNode; more?: ReactNode; shot?: RefObject<HTMLDivElement | null>; children: ReactNode }
/** 피드 글과 같은 틀(계정 줄·본문·보내기 줄)에 날씨·각 같은 화면 조각을 담는다. 보내기는 shot(공유용 틀)이 있으면 그것을, 없으면 본문을 이미지로 */
export function PostFrame({ title, account, avatar, caption, more, shot, children }: FrameProps) {
const { open } = useSheet()
const bodyRef = useRef<HTMLDivElement>(null)
const share = () => {
const el = shot?.current ?? bodyRef.current
if (el) open({ type: 'share', share: { title, slides: [el] } })
}
return (
<article className="mt-3.5 border-y border-(--line) bg-white first:mt-1" aria-label={title}>
<div className="flex items-center gap-2.5 px-3 py-2.5">
<span className="b-ring size-[34px] shrink-0 rounded-full p-0.5">
<i className="grid size-full place-items-center rounded-full bg-white">
<Ic name={avatar} className="w-[22px]" />
</i>
</span>
<span>
<b className="block text-sm leading-tight font-extrabold">날씨각</b>
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div ref={bodyRef}>{children}</div>
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
<button type="button" onClick={share} aria-label="보내기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
{more && <span className="ml-auto text-[13px] font-bold text-(--ink2)">{more}</span>}
</div>
{caption && (
<p className="px-3 pt-0.5 pb-3 text-sm">
<b className="mr-[5px] font-extrabold">날씨각</b>
{caption}
</p>
)}
</article>
)
}
+3 -4
View File
@@ -25,6 +25,7 @@ import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext'
import { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
@@ -102,7 +103,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
}, [isOpen])
const then = state?.type === 'login' ? state.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
return (
<dialog
@@ -132,6 +133,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
</div>
)}
{!state && <RegionLinks />}
@@ -614,8 +616,6 @@ const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const { region } = useRegion()
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const [liked, setLiked] = useState(c.liked)
const [count, setCount] = useState(c.like_count)
@@ -626,7 +626,6 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const [likeFailed, setLikeFailed] = useState(false)
const toggle = () => {
if (!loggedIn) return open({ type: 'login' })
if (like.isPending || unlike.isPending) return
const next = !liked
setLikeFailed(false)
+93 -70
View File
@@ -1,15 +1,21 @@
import { Fragment, useEffect, useState, type ReactNode } from 'react'
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TalkData, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { PostCard, PostCardSkel } from './Post'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { FeedComposer, TalkCard } from './talk'
import { useFeedTalks } from './talkState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
import { GakShareCard, HeroShareCard, type HeroShare } from './shareCards'
import { SendIcon } from './svg'
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
import { deg, slotAt } from './weatherText'
type Mode = 'now' | TimeKind
@@ -102,6 +108,9 @@ const CLOUD_N: Record<Weather, number> = { clear: 0, partly: 2, cloudy: 3, rain:
function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
const { open } = useSheet()
const { region } = useRegion()
const tplRef = useRef<HTMLDivElement>(null)
const share = () => tplRef.current && open({ type: 'share', share: { title: `${region.name} 오늘 날씨`, slides: [tplRef.current] } })
const { preview, setServerKind, setPreview } = useSky()
const mode: Mode = preview ?? 'now'
const clock = useNow()
@@ -137,9 +146,26 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
const rain = weather === 'rain' || weather === 'sleet'
const snow = weather === 'snow' || weather === 'sleet'
const shareData: HeroShare = {
kind,
sky: weather,
date: `${t.mo}월 ${t.d}일 ${WEEKDAYS[t.wd]}요일`,
place: region.name,
label: `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`,
score,
bubble,
summary: top1?.summary,
status: status.map((x) => ({ label: x.label, value: x.value, warn: x.tone === 'warn' })),
slots: KINDS.map((k) => {
const s = slotOf(k === nowKind ? 'now' : k)
return { label: k === nowKind ? '지금' : PREVIEW[k].label, icon: k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)], temp: s?.temp_c != null ? deg(s.temp_c) : '–', on: k === kind }
}),
}
// 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로)
return (
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind} data-sky={weather}>
<HeroShareCard d={shareData} ref={tplRef} />
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
{STARS.map((s, i) => (
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
@@ -154,9 +180,14 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
{snow && FLAKES.map((s, i) => <i key={i} className="b-flake" style={s} />)}
</div>
)}
<p className="relative z-[3] m-0 text-[14px] font-bold opacity-80">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</p>
<div className="relative z-[3] flex items-center justify-between">
<p className="m-0 text-[14px] font-bold opacity-80">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</p>
<button type="button" onClick={share} aria-label="오늘 날씨 보내기" className={cx('relative grid size-7 cursor-pointer place-items-center opacity-80 [&_svg]:size-[22px] [&_svg]:stroke-[2]', TAP44)}>
<SendIcon className="fill-none stroke-current [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
</div>
<div className="relative h-[146px]">
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
<span key={c.cls} className={cx('b-cloud b-fall z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true" />
@@ -227,27 +258,34 @@ function moonPath(pct: number, r: number, lit: boolean) {
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function Stories({ items }: { items: TopIndex[] }) {
function GakCard({ items, place, at }: { items: TopIndex[]; place: string; at: string }) {
const { open } = useSheet()
const tplRef = useRef<HTMLDivElement>(null)
const top = items.filter((g) => g.active).slice(0, 5)
return (
<Rail label="오늘의 각 순위">
{items.map((g, i) => (
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('flex w-[72px] cursor-pointer flex-col items-center gap-1', !g.active && 'opacity-55')}>
<span className={cx('relative size-[68px] rounded-full p-[3px]', !g.active || g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
<Ic name={g.icon} className="w-[42px]" />
</i>
{i < 3 && g.active && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
</span>
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
{g.active ? (
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
) : (
<small className="text-[11px] leading-none font-extrabold text-(--ink3)">지금 아님</small>
)}
</button>
))}
</Rail>
<PostFrame title={`오늘의 각 · ${place}`} account="오늘의 각" avatar="rabbit" more={<Link to="/gak">전체 보기</Link>} caption="누르면 계산 근거를 보여 줘요" shot={tplRef}>
<GakShareCard items={top} title={`오늘의 각 · ${place} ${at}`} ref={tplRef} />
<div className="b-band-2 px-4 pt-3.5 pb-3">
<p className="m-0 font-jua text-[19px]">
오늘의 각 · {place} {at}
</p>
<ol className="m-0 mt-2 grid list-none gap-1.5 p-0">
{top.map((g, i) => (
<li key={g.index_id}>
<button type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="flex w-full cursor-pointer items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 text-left shadow-[inset_0_-4px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
<Ic name={g.icon} className="w-[34px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{g.name}</b>
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</span>
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
</button>
</li>
))}
</ol>
</div>
</PostFrame>
)
}
@@ -260,27 +298,6 @@ function PostsSkel() {
)
}
const STORY_SKELS = Array.from({ length: 6 }, (_, i) => i)
/** Stories 와 같은 칸(68px 동그라미 + 이름 + 점수)을 6개 */
function StoriesSkel() {
return (
<SkelRail>
{STORY_SKELS.map((i) => (
<span key={i} className="flex w-[72px] flex-col items-center gap-1">
<Skel shape className="size-[68px] rounded-full" />
<b className="font-jua text-[13px] font-normal">
<Skel className="w-12" />
</b>
<em className="font-bagel text-[12.5px] leading-none not-italic">
<Skel className="w-6" />
</em>
</span>
))}
</SkelRail>
)
}
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
return (
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
@@ -309,25 +326,6 @@ function EventsBand({ events }: { events: BandEvent[] }) {
)
}
function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
const { open } = useSheet()
return (
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
<Rail>
{items.slice(0, 5).map((g, i) => (
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="relative flex w-[138px] cursor-pointer flex-col items-start gap-1 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="absolute top-2 left-2 w-[26px]" /> : <span className="absolute top-2.5 left-3 font-jua text-(--ink3)">{i + 1}위</span>}
<Ic name={g.icon} className="w-[58px] self-center" />
<b className="font-jua text-base font-normal">{g.name}</b>
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
{g.summary && <small className="text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</button>
))}
</Rail>
</Band>
)
}
function SeasonBand({ news }: { news: BandArticle[] }) {
const { open } = useSheet()
return (
@@ -352,6 +350,7 @@ export function TodayPage() {
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
const { preview } = useSky()
const { open } = useSheet()
const f = feed.data
const posts = f?.posts ?? []
const stories = atSlot(f?.stories ?? [], preview)
@@ -359,15 +358,28 @@ export function TodayPage() {
const bands = f?.bands
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
const [mine, setMine] = useState<TalkData[]>([])
// 사람들이 쓴 글은 운영 포스트 3개마다 하나씩. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
const talks = useFeedTalks().filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
useEffect(() => {
window.scrollTo({ top: 0 })
}, [region.code])
// 친구가 보낸 내 각 링크(/?my=...)로 들어오면 내 동네 기준으로 보여 준다
useEffect(() => {
const url = new URL(window.location.href)
const code = url.searchParams.get('my')
if (!code) return
url.searchParams.delete('my')
window.history.replaceState(window.history.state, '', url)
const g = fromShare(code)
if (g) open({ type: 'mix', shared: g })
}, [open])
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
[6, bands?.top5?.length ? <TopBand key="top5" items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
]
@@ -375,9 +387,19 @@ export function TodayPage() {
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
<FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} />
{mine.map((t) => (
<TalkCard key={t.talk_id} t={t} />
))}
<MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
)}
<div>
{load === 'loading' && <PostsSkel />}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
@@ -387,6 +409,7 @@ export function TodayPage() {
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{(i + 1) % 3 === 0 && talks[(i + 1) / 3 - 1] && <TalkCard t={talks[(i + 1) / 3 - 1]} />}
{bandAt.find(([at]) => at === i + 1)?.[1]}
</Fragment>
))}
+1 -1
View File
@@ -1,6 +1,6 @@
import type { CSSProperties } from 'react'
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
+198
View File
@@ -0,0 +1,198 @@
import { useState, type ReactNode } from 'react'
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores } from './myGakState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Sec } from './ui'
const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
const v = s?.score
return (
<em className={cx('ml-auto font-bagel leading-none not-italic', big ? 'text-[36px]' : 'text-[28px]', v == null || v < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>
{v ?? '–'}
</em>
)
}
function Reasons({ s }: { s?: MyGakScore }) {
if (!s?.slot) return <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">예보를 불러오는 중이에요</p>
return (
<p className="m-0 text-[12.5px] leading-snug font-semibold text-(--ink2)">
<b className="mr-1 text-(--ink)">{SLOT_WORD[s.slot as Slot]}</b>
{s.reasons?.join(' · ')}
</p>
)
}
/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */
export function MyGakRow() {
const { open } = useSheet()
const { items, remove } = useMyGak()
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []
const [copied, setCopied] = useState<number | null>(null)
const send = (g: MyGak, i: number) => {
const url = shareUrl(g)
if (navigator.share) {
navigator.share({ title: `${g.name} · 날씨각`, url }).catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
})
return
}
navigator.clipboard.writeText(url).then(
() => setCopied(i),
(e: unknown) => console.error('[myGak] copy', e),
)
}
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<div className="flex snap-x gap-2 overflow-x-auto px-3 pb-1 [scrollbar-width:none]">
{items.map((g, i) => (
<div key={g.id ?? 'local'} className="flex w-[220px] shrink-0 snap-start flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="flex items-center gap-1">
<b className="font-jua text-[17px] leading-tight font-normal">{g.name}</b>
<Score s={scores[i]} />
</div>
<Reasons s={scores[i]} />
<div className="mt-auto flex gap-1.5 pt-0.5">
<button type="button" onClick={() => send(g, i)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied === i ? '링크 복사함' : '친구에게 보내기'}
</button>
<button type="button" onClick={() => remove(g)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)">
지우기
</button>
</div>
</div>
))}
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] shrink-0 cursor-pointer snap-start flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
<span className="text-[26px] leading-none">+</span>
내 각 만들기
</button>
</div>
</>
)
}
function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) {
return (
<div className={cx('flex min-h-[44px] flex-wrap items-center gap-2 border-b border-(--line) py-2', !on && 'opacity-60')}>
<label className="flex w-[84px] cursor-pointer items-center gap-1.5 text-[14px] font-extrabold">
<input type="checkbox" checked={on} onChange={onToggle} className="size-4 accent-(--orange)" />
{label}
</label>
{on ? <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 text-[13.5px] font-bold">{children}</div> : <span className="text-[13px] font-semibold text-(--ink3)">상관없음</span>}
</div>
)
}
function Num({ value, onChange, min, max, label }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string }) {
return (
<input
type="number"
inputMode="numeric"
aria-label={label}
value={value}
min={min}
max={max}
onChange={(e) => {
const v = Number(e.target.value)
if (e.target.value !== '' && Number.isFinite(v)) onChange(Math.min(max, Math.max(min, v)))
}}
className="w-[58px] rounded-xl bg-[#f3f6fb] px-2 py-1.5 text-center tabular-nums"
/>
)
}
function Choice<T extends string>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<span className="flex gap-1" role="radiogroup" aria-label={label}>
{options.map(([k, word]) => (
<button key={k} type="button" role="radio" aria-checked={value === k} onClick={() => onChange(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', value === k ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</span>
)
}
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> }
const DEFAULT_RULE: Filled<MyGakRule> = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] }
type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity'
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
const { region } = useRegion()
const { create, pending, failed } = useMyGak()
const [name, setName] = useState(shared?.name ?? '')
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE)
const [on, setOn] = useState<Record<Cond, boolean>>(
shared ? { temp: !!shared.rule.temp, rain: !!shared.rule.rain, wind_max: shared.rule.wind_max != null, air: !!shared.rule.air, humidity: !!shared.rule.humidity } : { temp: true, rain: true, wind_max: false, air: false, humidity: false },
)
const set = <K extends keyof typeof vals>(k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }))
const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }))
const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial<MyGakRule>) }
const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1])
const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0]
const title = gakName(name) || '이름 없는 각'
const toggleSlot = (s: Slot) => set('slots', vals.slots.includes(s) ? vals.slots.filter((x) => x !== s) : SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)))
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{shared ? (
<p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>
) : (
<label className="block">
<span className="font-jua text-[19px]">이름</span>
<input value={name} onChange={(e) => setName(e.target.value)} maxLength={11} placeholder="소맥, 야독, 새우깡" className="mt-1.5 w-full rounded-2xl bg-[#f3f6fb] px-3.5 py-2.5 text-[15px]" />
</label>
)}
<fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0">
<legend className="font-jua text-[19px]">조건</legend>
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')}>
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} onChange={(v) => set('temp', [v, vals.temp[1]])} />~
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} onChange={(v) => set('temp', [vals.temp[0], v])} />° 체감
</Row>
<Row label="비" on={on.rain} onToggle={() => toggle('rain')}>
<Choice label="비" value={vals.rain} onChange={(v) => set('rain', v)} options={[['dry', '안 와야'], ['wet', '와야']]} />
</Row>
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')}>
초속 <Num label="바람 상한" value={vals.wind_max} min={1} max={20} onChange={(v) => set('wind_max', v)} />m 이하
</Row>
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')}>
<Choice label="미세먼지" value={vals.air} onChange={(v) => set('air', v)} options={[['good', '좋음만'], ['normal', '보통까지']]} />
</Row>
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')}>
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />~
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} onChange={(v) => set('humidity', [vals.humidity[0], v])} />%
</Row>
<div className="flex flex-wrap items-center gap-1.5 py-2.5 text-[13.5px] font-bold">
<span className="w-[84px] text-[14px] font-extrabold">시간대</span>
{SLOTS.map(([k, word]) => (
<button key={k} type="button" aria-pressed={vals.slots.includes(k)} onClick={() => toggleSlot(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', vals.slots.includes(k) ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</div>
</fieldset>
<div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5">
<div className="flex items-center">
<b className="font-jua text-[20px] font-normal">{title}</b>
<Score s={valid ? score : undefined} big />
</div>
{valid ? <Reasons s={score} /> : <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">조건과 시간대를 하나 이상 골라요</p>}
</div>
{failed && <p className="mt-2 mb-0 text-xs font-bold text-(--heart)">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</p>}
<button
type="button"
disabled={!valid || !gakName(name) || pending}
onClick={() => create({ name, rule }, onDone)}
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
>
{shared ? '내 각으로 가져오기' : '내 각으로 저장'}
</button>
</div>
)
}
+132
View File
@@ -0,0 +1,132 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useSyncExternalStore } from 'react'
import { SITE_URL } from '../api/setup'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey } from '../api/client/@tanstack/react-query.gen'
import { scoreMyGak } from '../api/client/sdk.gen'
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
const KEY = 'nalssigak.b.myRule'
export type Slot = 'morning' | 'day' | 'evening' | 'night'
export const SLOTS: [Slot, string][] = [
['morning', '아침'],
['day', '낮'],
['evening', '저녁'],
['night', '밤'],
]
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
export type MyGak = { id?: number; name: string; rule: MyGakRule }
function readLocal(): MyGak | null {
try {
const raw = localStorage.getItem(KEY)
return raw ? (JSON.parse(raw) as MyGak) : null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return null
}
}
// 시트와 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
let local = readLocal()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
function setLocal(g: MyGak | null) {
local = g
listeners.forEach((cb) => cb())
try {
if (g) localStorage.setItem(KEY, JSON.stringify(g))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[myGak] 기기에 저장하지 못함', e)
}
}
/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
export const gakName = (name: string) => {
const n = name.trim().replace(/\s+/g, ' ')
return n && !n.endsWith('각') ? `${n}각` : n
}
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
export function shareUrl(g: MyGak) {
const json = JSON.stringify({ n: g.name, r: g.rule })
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
}
export function fromShare(code: string): MyGak | null {
try {
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'))
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; r?: unknown }
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, rule: v.r as MyGakRule } : null
} catch (e) {
console.warn('[myGak] 받은 링크를 읽지 못함', e)
return null
}
}
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
export function useMyGakScores(rules: MyGakRule[]) {
const { region } = useRegion()
return useQuery({
queryKey: ['myGakScore', region.code, rules],
enabled: rules.length > 0,
staleTime: 5 * 60_000,
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } })
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score')
return { nowSlot: data.now_slot, scores: data.scores ?? [] }
},
})
}
export function useMyGak() {
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn })
const saved = useSyncExternalStore(subscribe, () => local)
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() })
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh })
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh })
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
const { mutate } = add
useEffect(() => {
if (!loggedIn || !saved) return
mutate({ body: { name: saved.name, rule: saved.rule } }, { onSuccess: () => setLocal(null) })
}, [loggedIn, saved, mutate])
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, rule: g.rule })) : saved ? [saved] : []
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
const create = (g: MyGak, onDone?: () => void) => {
const item = { name: gakName(g.name), rule: g.rule }
if (loggedIn) {
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
return
}
if (saved) {
open({ type: 'login' })
return
}
setLocal(item)
onDone?.()
}
const remove = (g: MyGak) => {
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } })
setLocal(null)
}
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false }
}
+88
View File
@@ -0,0 +1,88 @@
import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import type { TopIndex } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { MEDALS } from './lib'
import { Ic } from './ui'
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
function Offscreen({ children }: { children: React.ReactNode }) {
return createPortal(
<div aria-hidden="true" className="pointer-events-none fixed top-0 -left-[10000px] w-[380px]">
{children}
</div>,
document.body,
)
}
export type HeroShare = {
kind: string
sky: string
date: string
place: string
label: string
score?: number | null
bubble?: string | null
summary?: string | null
status: { label: string; value: string; warn: boolean }[]
slots: { label: string; icon: string; temp: string; on: boolean }[]
}
export function HeroShareCard({ d, ref }: { d: HeroShare; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="b-hero relative flex aspect-[4/5] flex-col overflow-hidden px-5 pt-5 pb-4 text-center" data-t={d.kind} data-sky={d.sky}>
<p className="m-0 text-left text-[14px] font-bold opacity-80">
{d.date} · {d.place}
</p>
<div className="b-sun mx-auto mt-5 grid aspect-square w-36 place-items-center rounded-full">
<span>
<small className="block font-jua text-[13px]">{d.label}</small>
<b className="block font-bagel text-[58px] leading-[0.95] font-normal">{d.score ?? '–'}</b>
</span>
</div>
<p className="m-0 mt-4 font-jua text-[26px] leading-tight">{d.bubble}</p>
{d.summary && <p className="m-0 mt-1 text-[15px] font-bold opacity-80">{d.summary}</p>}
<p className="m-0 mt-2 flex flex-wrap justify-center gap-x-2 font-jua text-[14px]">
{d.status.map((x) => (
<span key={x.label} className={cx('whitespace-nowrap', x.warn && 'b-warn')}>
<span className="opacity-75">{x.label}</span> {x.value}
</span>
))}
</p>
<div className="b-strip mt-auto grid grid-cols-4 gap-1 rounded-[18px] p-[3px]">
{d.slots.map((s) => (
<span key={s.label} className={cx('flex flex-col items-center rounded-[14px] py-1.5', s.on && 'b-strip-on')}>
<span className="text-[13px] font-bold opacity-80">{s.label}</span>
<Ic name={s.icon} className="my-0.5 h-[22px] w-[22px] object-contain" />
<b className="font-jua text-[15px] font-normal">{s.temp}</b>
</span>
))}
</div>
</div>
</Offscreen>
)
}
export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title: string; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="b-band-2 flex aspect-[4/5] flex-col bg-white px-5 pt-5 pb-4">
<p className="m-0 font-jua text-[22px]">{title}</p>
<ol className="m-0 mt-3 grid list-none gap-2 p-0">
{items.map((g, i) => (
<li key={g.index_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2.5 shadow-[inset_0_-4px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
<Ic name={g.icon} className="w-[36px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[17px] leading-tight font-normal">{g.name}</b>
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</span>
<em className="font-bagel text-[24px] leading-none text-(--orange) not-italic">{g.score}</em>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
+2
View File
@@ -1,3 +1,4 @@
import type { MyGak } from './myGakState'
import { createContext, use } from 'react'
export type SharePayload = { title: string; slides: HTMLElement[] }
@@ -12,6 +13,7 @@ export type SheetState =
| { type: 'login'; then?: CommentsState }
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
| null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
+2 -1
View File
@@ -35,7 +35,7 @@ export function PinIcon({ className }: P) {
)
}
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' }) {
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' | 'talk' }) {
return (
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
{name === 'today' && <path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
@@ -55,6 +55,7 @@ export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky'
<circle cx="12" cy="15" r="1.6" />
</>
)}
{name === 'talk' && <path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.5 4v-4h0A1.5 1.5 0 0 1 4 14.5zM8 8.5h8M8 12h5" />}
{name === 'season' && <path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
</svg>
)
+279
View File
@@ -0,0 +1,279 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
import {
addTalkMutation,
blockTalkAuthorMutation,
deleteTalkMutation,
likeTalkMutation,
reportTalkMutation,
unlikeTalkMutation,
} from '../api/client/@tanstack/react-query.gen'
import { uploadTalkImage } from '../api/client/sdk.gen'
import { TalkReport, type TalkData } from '../api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, kst } from './lib'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { HeartIcon } from './svg'
import { Avatar, TAP44 } from './ui'
const BODY_MAX = 100
const PHOTO_MAX = 10 * 1024 * 1024
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record<string, string> = {
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
INVALID_INPUT: '100자 안으로 써 주세요.',
}
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
[TalkReport.PRIVACY, '개인정보 노출'],
[TalkReport.ETC, '기타'],
] as const
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
function slotWord(iso: string) {
const h = kst(iso).h
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤'
}
function useRefreshTalks() {
const queryClient = useQueryClient()
return () => queryClient.invalidateQueries({ queryKey: [{ _id: 'listTalks' }] })
}
function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
const { region } = useRegion()
const { loggedIn, me } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const add = useMutation(addTalkMutation())
const [text, setText] = useState('')
const [error, setError] = useState<string | null>(null)
const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null)
const [uploading, setUploading] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
const busy = add.isPending || uploading
useEffect(() => {
if (!photo) return
return () => URL.revokeObjectURL(photo.src)
}, [photo])
const pick = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
if (file.size > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.')
setError(null)
setPhoto({ file, src: URL.createObjectURL(file) })
}
// 사진이 있으면 먼저 올려 주소를 받고, 그 주소를 글에 붙인다
const upload = async (): Promise<string | undefined> => {
if (!photo) return undefined
setUploading(true)
try {
const { data } = await uploadTalkImage({ body: { file: photo.file } })
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload')
return data.image
} finally {
setUploading(false)
}
}
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login' })
const body = text.trim()
if (!body || busy) return
setError(null)
upload().then(
(image) =>
add.mutate(
{ body: { region_code: region.code, body, image } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
setText('')
setPhoto(null)
refresh()
if (res.talk) onDone?.(res.talk)
},
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
},
),
(e: unknown) => {
console.error('[talk] photo upload', e)
setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.')
},
)
}
return (
<form onSubmit={submit} className="mx-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
onFocus={() => !loggedIn && open({ type: 'login' })}
readOnly={busy}
maxLength={BODY_MAX}
rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
aria-label="동네 이야기 쓰기"
className="w-full resize-none rounded-2xl bg-[#f3f6fb] px-3 py-2.5 text-[14.5px]"
/>
{photo && (
<div className="relative mt-2 w-[96px]">
<img src={photo.src} alt="올릴 사진" className="aspect-[4/5] w-full rounded-xl object-cover" />
<button type="button" onClick={() => setPhoto(null)} aria-label="사진 빼기" className="absolute -top-1.5 -right-1.5 grid size-6 cursor-pointer place-items-center rounded-full bg-(--ink) text-[13px] font-extrabold text-white">
×
</button>
</div>
)}
<input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden />
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
<button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} className="shrink-0 cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2) disabled:opacity-40">
사진
</button>
<span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
<span className="ml-auto tabular-nums">
{text.length}/{BODY_MAX}
</span>
<button type="submit" disabled={busy || (loggedIn && !text.trim())} className="shrink-0 cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white disabled:opacity-40">
{busy ? '올리는 중…' : '올리기'}
</button>
</div>
{error && (
<p className="mt-1 mb-0 text-xs font-bold text-(--heart)" role="alert">
{error}
</p>
)}
</form>
)
}
function TalkRow({ t }: { t: TalkData }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const [liked, setLiked] = useState(t.liked)
const [count, setCount] = useState(t.like_count)
const [menu, setMenu] = useState<'closed' | 'open' | 'report' | 'done'>('closed')
const like = useMutation(likeTalkMutation())
const unlike = useMutation(unlikeTalkMutation())
const remove = useMutation(deleteTalkMutation())
const report = useMutation(reportTalkMutation())
const block = useMutation(blockTalkAuthorMutation())
const [failed, setFailed] = useState(false)
const toggle = () => {
if (like.isPending || unlike.isPending) return
const next = !liked
setLiked(next)
setCount((n) => n + (next ? 1 : -1))
;(next ? like : unlike).mutate(
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (res.result?.success && res.like_count != null) return setCount(res.like_count)
setLiked(!next)
setCount(t.like_count)
},
onError: () => {
setLiked(!next)
setCount(t.like_count)
},
},
)
}
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = {
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
setMenu('done')
refresh()
},
onError: () => setFailed(true),
}
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
return (
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 border-b border-(--line) py-2.5 last:border-b-0">
<Avatar character={t.character} color={t.color} mood={t.mood} />
<div className="min-w-0">
<small className="block text-xs font-bold text-(--ink3)">
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
{[t.region_name, slotWord(t.created_at), t.weather].filter(Boolean).join(' · ')}
</small>
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
{t.image && <img src={t.image.startsWith('/v1/') ? API_BASE_URL + t.image : t.image} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
{t.mine ? '내 글' : '더보기'}
</button>
</small>
{menu !== 'closed' && (
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
{menu === 'done' ? (
<span className="text-[#1f9d62]">처리했어요</span>
) : t.mine ? (
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, after)} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
지우기
</button>
) : menu === 'report' ? (
REASONS.map(([reason, label]) => (
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after)} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
{label}
</button>
))
) : (
<>
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
이 사람 글 안 보기
</button>
<button type="button" onClick={() => guard(() => setMenu('report'))} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
신고하기
</button>
</>
)}
{failed && (
<span className="text-(--heart)" role="alert">
못 했어요. 다시 해 주세요
</span>
)}
</div>
)}
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
</button>
</div>
)
}
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
return (
<div className="mt-3.5">
<Composer onDone={onPosted} />
</div>
)
}
/** 피드에 끼우는 글 한 장 */
export function TalkCard({ t }: { t: TalkData }) {
return (
<article className="mt-3.5 border-y border-(--line) bg-white px-3" aria-label={`${t.nickname}의 글`}>
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
</article>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { useInfiniteQuery } from '@tanstack/react-query'
import { listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen'
/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞는다 */
export function useFeedTalks() {
const list = useInfiniteQuery({
...listTalksInfiniteOptions(),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
return list.data?.pages.flatMap((p) => p.talks ?? []) ?? []
}