Files
o2o-weather/backend/crud/reaction_crud.py
T
minaChoi 93e041bb91 feat: 10/21 회의 반영 — 공유 링크·로그인 없이 댓글·구글 로그인만, 히어로·오늘의 각 좋아요·댓글, 히어로 오늘/내일 스위치, 단풍 지도 65곳·3단계
- 공유: 이미지와 함께 고정 URL을 넘기고 링크도 클립보드에 복사
- 로그인 창은 구글만, 댓글은 로그인 없이 '동네 익명'(링크·전화번호 막기, IP당 하루 20개, 같은 IP만 지우기)
- 히어로·오늘의 각 카드에 좋아요·댓글 (PostType HERO·TODAY_GAK)
- 히어로 오늘/내일 스위치: 내일 구간별 날씨 점수·기온·최저최고·습도·1위 각, /v1/weather/today?day=tomorrow
- 단풍 지도: 단풍 그림 지도, 단풍 전·첫 단풍·절정, 단풍잎·은행잎, 명소 65곳(산림청 예측 + 가까운 지점 날짜)
- 하단 탭 바 불투명 (홈 바 자리로 글이 비치지 않게)
- 사람 글 동네 우선 정렬·내 글 목록, 내 각 '있는 각에서 불러오기'
- 댓글 표 user_id NULL 허용·ip_hash·region_name (운영 DB ALTER 필요)
2026-10-21 17:10:29 +09:00

99 lines
6.6 KiB
Python

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 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, who: Liker, on: bool) -> int:
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
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))
async def toggle_post_save(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, on: bool) -> None:
if on:
await s.execute(insert(PostSave).values(post_id=post_id, user_id=user_id).on_conflict_do_nothing())
else:
await s.execute(delete(PostSave).where(PostSave.post_id == post_id, PostSave.user_id == user_id))
async def counts(self, s: AsyncSession, post_ids: list[int]) -> dict[int, tuple[int, int]]:
rows = await s.execute(select(Post.post_id, Post.like_count, Post.comment_count).where(Post.post_id.in_(post_ids)))
return {pid: (likes, comments) for pid, likes, comments in rows.all()}
async def my_marks(self, s: AsyncSession, user_id: uuid.UUID, post_ids: list[int]) -> tuple[set[int], set[int]]:
liked = set((await s.scalars(select(PostLike.post_id).where(PostLike.user_id == user_id, PostLike.post_id.in_(post_ids)))).all())
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:
stmt = stmt.where(Post.post_id < cursor)
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다."""
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
if cursor is not None:
stmt = stmt.where(Comment.comment_id > cursor)
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
async def liked_comments(self, s: AsyncSession, user_id: uuid.UUID, comment_ids: list[int]) -> set[int]:
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, who: Liker, body: str, region_name: Optional[str]) -> Comment:
c = Comment(post_id=post_id, user_id=who.user_id, body=body) if who.user_id is not None else Comment(post_id=post_id, ip_hash=who.ip_hash, region_name=region_name, body=body)
s.add(c)
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + 1))
await s.flush()
return c
async def anon_comments_since(self, s: AsyncSession, ip_hash: str, since: datetime) -> int:
return await s.scalar(select(func.count()).select_from(Comment).where(Comment.user_id.is_(None), Comment.ip_hash == ip_hash, Comment.created_at >= since))
async def delete_comment(self, s: AsyncSession, comment_id: int, who: Liker) -> bool:
owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash))
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
.values(deleted=True).returning(Comment.post_id)
)
post_id = res.scalar()
if post_id is None:
return False
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
return True
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
if exists is None:
return None
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))