Files
o2o-weather/backend/services/reaction_service.py
T

141 lines
6.8 KiB
Python

import uuid
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Comment, Post, User
from common.enums import ErrorType, ReportReason
from crud.feed_crud import FeedCRUD
from crud.reaction_crud import ReactionCRUD
COMMENT_MAX = 60
PAGE = 20
@dataclass
class CommentView:
comment: Comment
nickname: str
character: str
color: str
mood: Optional[str]
liked: bool
mine: bool
@dataclass
class SavedView:
post: Post
saved_at: datetime
class ReactionService:
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD)) -> None:
self.crud, self.feed = crud, feed
async def _post_exists(self, post_id: int) -> ErrorType:
err, post = await DB_SESSION_MNG.execute_lambda(lambda s: self.feed.get(s, post_id))
if err is not ErrorType.SUCCESS:
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]]:
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))
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_save(s, post_id, user.user_id, on))
return err
async def marks(self, user: Optional[User], post_ids: list[int]) -> tuple[set[int], set[int]]:
if user is None or not post_ids:
return set(), set()
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 counts(self, post_ids: list[int]) -> dict[int, tuple[int, int]]:
"""피드는 캐시돼 있어서 좋아요·댓글 수는 매번 DB 에서 덮어쓴다."""
if not post_ids:
return {}
err, counts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.counts(s, post_ids))
return counts if err is ErrorType.SUCCESS else {}
async def saved(self, user: User, cursor: Optional[int]) -> tuple[ErrorType, list[SavedView]]:
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]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, user.user_id if user else None, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
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]))
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
]
async def add_comment(self, post_id: int, user: User, body: str) -> tuple[ErrorType, Optional[CommentView]]:
body = body.strip()
if not body or len(body) > COMMENT_MAX:
return ErrorType.INVALID_INPUT, None
if user.terms_agreed_at is None:
return ErrorType.TERMS_REQUIRED, None
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err, None
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, user.user_id, body))
return err, (CommentView(comment=c, nickname=user.nickname, character=user.character, color=user.color, mood=user.mood, liked=False, mine=True) if c else None)
async def delete_comment(self, comment_id: int, user: User) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, user.user_id))
if err is not ErrorType.SUCCESS:
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))
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
async def _others_comment(self, comment_id: int, user: User) -> tuple[ErrorType, Optional[uuid.UUID]]:
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT."""
err, author = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comment_author(s, comment_id))
if err is not ErrorType.SUCCESS:
return err, None
if author is None:
return ErrorType.NOT_FOUND, None
return (ErrorType.INVALID_INPUT, None) if author == user.user_id else (ErrorType.SUCCESS, author)
async def report_comment(self, comment_id: int, user: User, reason: ReportReason) -> ErrorType:
err, _ = await self._others_comment(comment_id, user)
if err is not ErrorType.SUCCESS:
return err
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.report_comment(s, comment_id, user.user_id, reason.value)])
async def block_author(self, comment_id: int, user: User) -> ErrorType:
err, author = await self._others_comment(comment_id, user)
if err is not ErrorType.SUCCESS:
return err
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.block(s, user.user_id, author)])
async def unblock(self, user: User, blocked_id: uuid.UUID) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.unblock(s, user.user_id, blocked_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
async def blocked(self, user: User) -> tuple[ErrorType, list[User]]:
err, users = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.blocked(s, user.user_id))
return err, users or []