import uuid from typing import Optional 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, CommentReport, Post, PostLike, PostSave, User, UserBlock HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다 class ReactionCRUD: async def toggle_post_like(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, 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: 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 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, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, str, str, str, Optional[str]]]: """숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다.""" stmt = select(Comment, User.nickname, User.character, User.color, User.mood).join(User, User.user_id == Comment.user_id).where( Comment.post_id == post_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False) ) if viewer is not None: stmt = stmt.where( Comment.comment_id.not_in(select(CommentReport.comment_id).where(CommentReport.user_id == viewer)), Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)), ) 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 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) 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 delete_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID) -> bool: res = await s.execute( update(Comment).where(Comment.comment_id == comment_id, Comment.user_id == user_id, Comment.deleted.is_(False)) .values(deleted=True).returning(Comment.post_id, Comment.is_hidden) ) row = res.first() if row is None: return False # 숨긴 댓글은 이미 댓글 수에서 빠져 있다 if not row.is_hidden: await s.execute(update(Post).where(Post.post_id == row.post_id).values(comment_count=Post.comment_count - 1)) return True async def toggle_comment_like(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, on: bool) -> Optional[int]: exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False))) 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: await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1))) return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id)) async def comment_author(self, s: AsyncSession, comment_id: int) -> Optional[uuid.UUID]: return await s.scalar(select(Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False))) async def report_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, reason: int) -> None: """같은 사람이 두 번 신고해도 한 번만 센다. HIDE_AT 건이 되면 숨기고 댓글 수에서 뺀다.""" res = await s.execute(insert(CommentReport).values(comment_id=comment_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(CommentReport.comment_id)) if res.first() is None: return await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(report_count=Comment.report_count + 1)) res = await s.execute( update(Comment).where(Comment.comment_id == comment_id, Comment.report_count >= HIDE_AT, Comment.is_hidden.is_(False), Comment.deleted.is_(False)) .values(is_hidden=True).returning(Comment.post_id) ) post_id = res.scalar() if post_id is not None: await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1)) async def set_hidden(self, s: AsyncSession, comment_id: int, hidden: bool) -> bool: """운영자가 댓글을 숨기거나 되살린다. 실제로 바뀌었을 때만 댓글 수를 고친다.""" res = await s.execute( update(Comment).where(Comment.comment_id == comment_id, Comment.is_hidden.is_(not hidden), Comment.deleted.is_(False)) .values(is_hidden=hidden).returning(Comment.post_id) ) post_id = res.scalar() if post_id is None: return False await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + (-1 if hidden else 1))) return True async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None: await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing()) async def unblock(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> bool: res = await s.execute(delete(UserBlock).where(UserBlock.user_id == user_id, UserBlock.blocked_id == blocked_id).returning(UserBlock.blocked_id)) return res.first() is not None async def blocked(self, s: AsyncSession, user_id: uuid.UUID) -> list[User]: stmt = select(User).join(UserBlock, UserBlock.blocked_id == User.user_id).where(UserBlock.user_id == user_id).order_by(UserBlock.created_at.desc()) return list((await s.scalars(stmt)).all())