185 lines
9.5 KiB
Python
185 lines
9.5 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 common.liker import Liker
|
|
from common.utils.kma_time import kst_midnight, now_kst
|
|
from crud.feed_crud import FeedCRUD
|
|
from crud.reaction_crud import ReactionCRUD
|
|
from crud.region_crud import RegionCRUD
|
|
from services.talk_service import _LINK, _PHONE
|
|
|
|
COMMENT_MAX = 60
|
|
# 로그인 없이 IP 하나가 하루에 쓸 수 있는 댓글 수
|
|
ANON_DAILY_MAX = 20
|
|
ANON_CHARACTER, ANON_COLOR = "rabbit", "orange"
|
|
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), regions: RegionCRUD = Depends(RegionCRUD)) -> None:
|
|
self.crud, self.feed, self.regions = crud, feed, regions
|
|
|
|
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, 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, who, 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 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:
|
|
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 []]
|
|
|
|
@staticmethod
|
|
def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView:
|
|
if c.user_id is None:
|
|
mine = who.user_id is None and c.ip_hash == who.ip_hash
|
|
return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine)
|
|
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
|
|
|
|
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, user.user_id if user else None, 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, ids))
|
|
elif rows:
|
|
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids))
|
|
who = Liker(user_id=user.user_id if user else None, ip_hash=ip_hash)
|
|
return ErrorType.SUCCESS, [self._view(c, n, ch, co, mo, c.comment_id in (liked or set()), who) for c, n, ch, co, mo in rows]
|
|
|
|
async def add_comment(self, post_id: int, user: Optional[User], who: Liker, body: str, region_code: Optional[str] = None) -> tuple[ErrorType, Optional[CommentView]]:
|
|
"""로그인 없이도 쓴다. 그때는 링크·전화번호를 막고 IP 하나에 하루 ANON_DAILY_MAX 개까지, 이름은 쓸 때 동네로 '마포구 익명'."""
|
|
body = body.strip()
|
|
if not body or len(body) > COMMENT_MAX:
|
|
return ErrorType.INVALID_INPUT, None
|
|
if user is not None and 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
|
|
region_name = None
|
|
if user is None:
|
|
if _LINK.search(body) or _PHONE.search(body):
|
|
return ErrorType.LINK_NOT_ALLOWED, None
|
|
today = kst_midnight(now_kst().date())
|
|
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_comments_since(s, who.ip_hash, today))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
if n >= ANON_DAILY_MAX:
|
|
return ErrorType.DAILY_LIMIT, None
|
|
if region_code:
|
|
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
|
|
region_name = region.short_name if region else None
|
|
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, who, body, region_name))
|
|
if c is None:
|
|
return err, None
|
|
if user is None:
|
|
return err, self._view(c, None, None, None, None, False, who)
|
|
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
|
|
|
|
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
|
|
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, who))
|
|
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, 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)
|
|
|
|
async def _others_comment(self, comment_id: int, user: User) -> tuple[ErrorType, Optional[uuid.UUID]]:
|
|
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT, 로그인 없이 쓴 댓글이면 작성자는 None."""
|
|
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_id == user.user_id else (ErrorType.SUCCESS, author.user_id)
|
|
|
|
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
|
|
# 로그인 없이 쓴 댓글은 차단할 사람이 없어 신고만 받는다
|
|
if author is None:
|
|
return ErrorType.INVALID_INPUT
|
|
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 []
|