Merge branch 'react-native' into release/1026-merge
# Conflicts: # backend/common/enums.py # backend/router/v1/auth/account.py # frontend/.dockerignore # frontend/package-lock.json # frontend/package.json # frontend/public/terms.html # frontend/src/api/client/index.ts # frontend/src/b/BLayout.tsx # frontend/src/b/Sheets.tsx # shared/api/client/@tanstack/react-query.gen.ts # shared/api/client/sdk.gen.ts # shared/api/client/types.gen.ts
This commit is contained in:
commit
5d18fa51fa
148 files changed
+21940
-4532
No files matched your search
@@ -360,6 +360,7 @@ class User(Base):
|
||||
color: Mapped[str] = mapped_column(String(20), default="orange")
|
||||
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -400,10 +401,29 @@ class Comment(Base):
|
||||
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
body: Mapped[str] = mapped_column(String(60))
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
is_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 CommentReport(Base):
|
||||
__tablename__ = "comment_report"
|
||||
|
||||
comment_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())
|
||||
|
||||
|
||||
class CommentLike(Base):
|
||||
__tablename__ = "comment_like"
|
||||
|
||||
@@ -472,9 +492,3 @@ class TalkReport(Base):
|
||||
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())
|
||||
@@ -25,6 +25,7 @@ class ErrorType(Enum):
|
||||
AUTH_FAILED = 4002
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
AUTH_TOKEN_INVALID = 4004
|
||||
TERMS_REQUIRED = 4005
|
||||
|
||||
|
||||
class Sky(CodeEnum):
|
||||
@@ -192,3 +193,10 @@ class AuthProvider(CodeEnum):
|
||||
LOCAL = 1
|
||||
GOOGLE = 2
|
||||
TOSS = 3
|
||||
|
||||
|
||||
class ReportReason(CodeEnum):
|
||||
ABUSE = 1
|
||||
AD = 2
|
||||
PRIVACY = 3
|
||||
OTHER = 4
|
||||
@@ -2,13 +2,15 @@ import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy import delete, func, or_, 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.database.model.models import Comment, CommentLike, CommentLikeAnon, CommentReport, Post, PostLike, PostLikeAnon, PostSave, User, UserBlock
|
||||
from common.liker import Liker
|
||||
|
||||
HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다
|
||||
|
||||
|
||||
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."""
|
||||
@@ -52,9 +54,16 @@ class ReactionCRUD:
|
||||
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))
|
||||
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], 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), 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)),
|
||||
or_(Comment.user_id.is_(None), 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())
|
||||
@@ -81,18 +90,61 @@ class ReactionCRUD:
|
||||
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)
|
||||
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
|
||||
)
|
||||
post_id = res.scalar()
|
||||
if post_id is None:
|
||||
row = res.first()
|
||||
if row is None:
|
||||
return False
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
||||
# 숨긴 댓글은 이미 댓글 수에서 빠져 있다
|
||||
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, who: Liker, on: bool) -> Optional[int]:
|
||||
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
|
||||
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 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))
|
||||
|
||||
async def comment_author(self, s: AsyncSession, comment_id: int):
|
||||
"""지금 보이는 댓글이면 (comment_id, user_id) 행, 없으면 None. 로그인 없이 쓴 댓글은 user_id 가 None."""
|
||||
return (await s.execute(select(Comment.comment_id, Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))).first()
|
||||
|
||||
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())
|
||||
@@ -1,11 +1,12 @@
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import User
|
||||
from common.database.model.models import Comment, CommentLike, CommentReport, Post, PostLike, PostSave, User, UserBlock
|
||||
|
||||
|
||||
class UserCRUD:
|
||||
@@ -46,3 +47,29 @@ class UserCRUD:
|
||||
user.updated_at = datetime.now(timezone.utc)
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def agree_terms(self, s: AsyncSession, user_id: uuid.UUID) -> None:
|
||||
await s.execute(update(User).where(User.user_id == user_id, User.terms_agreed_at.is_(None)).values(terms_agreed_at=datetime.now(timezone.utc)))
|
||||
|
||||
async def withdraw(self, s: AsyncSession, user_id: uuid.UUID) -> None:
|
||||
"""계정과 그 사람이 남긴 좋아요·저장·댓글·신고·차단을 모두 지우고, 게시물·댓글에 쌓인 수를 그만큼 줄인다."""
|
||||
liked_posts = (await s.scalars(delete(PostLike).where(PostLike.user_id == user_id).returning(PostLike.post_id))).all()
|
||||
if liked_posts:
|
||||
await s.execute(update(Post).where(Post.post_id.in_(liked_posts)).values(like_count=Post.like_count - 1))
|
||||
liked_comments = (await s.scalars(delete(CommentLike).where(CommentLike.user_id == user_id).returning(CommentLike.comment_id))).all()
|
||||
if liked_comments:
|
||||
await s.execute(update(Comment).where(Comment.comment_id.in_(liked_comments)).values(like_count=Comment.like_count - 1))
|
||||
await s.execute(delete(PostSave).where(PostSave.user_id == user_id))
|
||||
reported = (await s.scalars(delete(CommentReport).where(CommentReport.user_id == user_id).returning(CommentReport.comment_id))).all()
|
||||
if reported:
|
||||
await s.execute(update(Comment).where(Comment.comment_id.in_(reported)).values(report_count=Comment.report_count - 1))
|
||||
await s.execute(delete(UserBlock).where((UserBlock.user_id == user_id) | (UserBlock.blocked_id == user_id)))
|
||||
mine = (await s.execute(delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.deleted, Comment.is_hidden))).all()
|
||||
if mine:
|
||||
ids = [c for c, _, _, _ in mine]
|
||||
await s.execute(delete(CommentLike).where(CommentLike.comment_id.in_(ids)))
|
||||
await s.execute(delete(CommentReport).where(CommentReport.comment_id.in_(ids)))
|
||||
# 이미 지웠거나 숨긴 댓글은 댓글 수에서 빠져 있다
|
||||
for post_id, n in Counter(p for _, p, deleted, hidden in mine if not deleted and not hidden).items():
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - n))
|
||||
await s.execute(delete(User).where(User.user_id == user_id))
|
||||
@@ -218,6 +218,7 @@ CREATE TABLE IF NOT EXISTS public.users (
|
||||
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
||||
mood VARCHAR(20) NULL, -- 오늘 기분: clear·partly·cloudy·rain·thunder·snow·fog·rainbow. NULL = 안 고름
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
||||
terms_agreed_at TIMESTAMPTZ NULL, -- 이용약관 동의 시각. NULL 이면 댓글을 못 쓴다
|
||||
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -266,16 +267,28 @@ ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
|
||||
|
||||
-- 댓글 신고 (보류)
|
||||
-- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
|
||||
-- ALTER TABLE public.comment ADD COLUMN is_hidden BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
-- CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
-- comment_id BIGINT NOT NULL,
|
||||
-- user_id UUID NOT NULL,
|
||||
-- reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
-- PRIMARY KEY (comment_id, user_id)
|
||||
-- );
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS is_hidden BOOLEAN NOT NULL DEFAULT FALSE; -- 신고 3건이면 숨김. 숨긴 댓글은 댓글 수에서 빠진다
|
||||
|
||||
-- 댓글 신고. 신고한 사람에게는 그 댓글이 바로 안 보인다
|
||||
CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
comment_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (comment_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_report_user ON public.comment_report (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)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_block_blocked ON public.user_block (blocked_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||
comment_id BIGINT NOT NULL,
|
||||
@@ -343,14 +356,6 @@ CREATE TABLE IF NOT EXISTS public.talk_report (
|
||||
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)
|
||||
);
|
||||
|
||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||
|
||||
-- 구 목록.
|
||||
|
||||
@@ -11,14 +11,14 @@ from common.enums import AuthProvider, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.models.errors import error_info
|
||||
from config.settings import settings
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_TossUnlink
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_TossUnlink, Res_Withdraw
|
||||
from services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _me(u: User) -> Me:
|
||||
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider))
|
||||
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider), terms_agreed=u.terms_agreed_at is not None)
|
||||
|
||||
|
||||
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
|
||||
@@ -100,3 +100,17 @@ async def update_me(req: Req_UpdateMe, user: User = Depends(current_user), servi
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Me(result=error_info(err))
|
||||
return Res_Me(me=_me(updated))
|
||||
|
||||
|
||||
@router.post("/terms", response_model=Res_Me, response_model_exclude_none=True, summary="이용약관 동의 (댓글 쓰기 전에 한 번)")
|
||||
async def agree_terms(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Me:
|
||||
err, updated = await service.agree_terms(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Me(result=error_info(err))
|
||||
return Res_Me(me=_me(updated))
|
||||
|
||||
|
||||
@router.delete("/me", response_model=Res_Withdraw, response_model_exclude_none=True, summary="탈퇴 (계정과 남긴 댓글·좋아요를 모두 지운다)")
|
||||
async def withdraw(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Withdraw:
|
||||
err = await service.withdraw(user)
|
||||
return Res_Withdraw() if err is ErrorType.SUCCESS else Res_Withdraw(result=error_info(err))
|
||||
@@ -48,6 +48,7 @@ class Me(WebPacketProtocol):
|
||||
color: str
|
||||
mood: Optional[str] = None
|
||||
provider: AuthProvider
|
||||
terms_agreed: bool = False
|
||||
|
||||
|
||||
class Res_Auth(Res_WebPacketProtocol):
|
||||
@@ -64,6 +65,10 @@ class Res_Logout(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_Withdraw(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Res_Me(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import PostType
|
||||
from common.enums import PostType, ReportReason
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -58,3 +59,18 @@ class Res_Comment(Res_WebPacketProtocol):
|
||||
class Res_CommentLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
|
||||
|
||||
class Req_Report(Req_WebPacketProtocol):
|
||||
reason: ReportReason
|
||||
|
||||
|
||||
class BlockedUser(WebPacketProtocol):
|
||||
user_id: uuid.UUID
|
||||
nickname: str
|
||||
character: str
|
||||
color: str
|
||||
|
||||
|
||||
class Res_BlockedList(Res_WebPacketProtocol):
|
||||
users: list[BlockedUser] = []
|
||||
@@ -1,3 +1,4 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
@@ -10,7 +11,8 @@ from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from common.utils.kma_time import KST
|
||||
from router.v1.reaction.protocol import (
|
||||
CommentData, Req_Comment, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave, Res_SavedList, SavedPost,
|
||||
BlockedUser, CommentData, Req_Comment, Req_Report, Res_BlockedList, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave,
|
||||
Res_SavedList, SavedPost,
|
||||
)
|
||||
from services.reaction_service import PAGE, CommentView, ReactionService
|
||||
|
||||
@@ -69,7 +71,7 @@ async def list_comments(
|
||||
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)")
|
||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)")
|
||||
async def add_comment(
|
||||
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
|
||||
) -> Res_Comment:
|
||||
@@ -95,3 +97,26 @@ async def like_comment(comment_id: int = Path(...), who: Liker = Depends(liker),
|
||||
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
|
||||
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)
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)")
|
||||
async def report_comment(comment_id: int = Path(...), req: Req_Report = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.report_comment(comment_id, user, req.reason)))
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임)")
|
||||
async def block_author(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.block_author(comment_id, user)))
|
||||
|
||||
|
||||
@router.get("/block/list", response_model=Res_BlockedList, response_model_exclude_none=True, summary="내가 차단한 사람")
|
||||
async def list_blocked(user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_BlockedList:
|
||||
err, users = await service.blocked(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_BlockedList(result=error_info(err))
|
||||
return Res_BlockedList(users=[BlockedUser(user_id=u.user_id, nickname=u.nickname, character=u.character, color=u.color) for u in users])
|
||||
|
||||
|
||||
@router.delete("/block/{user_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="차단 풀기")
|
||||
async def unblock(user_id: uuid.UUID = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.unblock(user, user_id)))
|
||||
@@ -0,0 +1,64 @@
|
||||
"""운영자용 댓글·사용자 조치.
|
||||
|
||||
python scripts/moderate.py reports 신고 받은 댓글 (많은 순 30개)
|
||||
python scripts/moderate.py hide <comment_id> 댓글 숨김
|
||||
python scripts/moderate.py show <comment_id> 숨긴 댓글 되살림
|
||||
python scripts/moderate.py suspend <login_id> 이용 정지 (로그인·토큰 막힘)
|
||||
python scripts/moderate.py resume <login_id> 정지 풀기
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from sqlalchemy import select, update # noqa: E402
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||
from common.database.model.models import Comment, User # noqa: E402
|
||||
from common.enums import ErrorType # noqa: E402
|
||||
from crud.reaction_crud import ReactionCRUD # noqa: E402
|
||||
|
||||
|
||||
async def _reports(s):
|
||||
stmt = (
|
||||
select(Comment.comment_id, Comment.report_count, Comment.is_hidden, User.login_id, Comment.body)
|
||||
.join(User, User.user_id == Comment.user_id)
|
||||
.where(Comment.report_count > 0, Comment.deleted.is_(False))
|
||||
.order_by(Comment.report_count.desc(), Comment.comment_id.desc())
|
||||
.limit(30)
|
||||
)
|
||||
return (await s.execute(stmt)).all()
|
||||
|
||||
|
||||
async def _set_status(s, login_id: str, status: int) -> bool:
|
||||
res = await s.execute(
|
||||
update(User).where(User.login_id == login_id, User.deleted.is_(False)).values(status=status, token_version=User.token_version + 1).returning(User.user_id)
|
||||
)
|
||||
return res.first() is not None
|
||||
|
||||
|
||||
async def main(argv: list[str]) -> int:
|
||||
if len(argv) < 1 or argv[0] not in {"reports", "hide", "show", "suspend", "resume"} or (argv[0] != "reports" and len(argv) != 2):
|
||||
print(__doc__)
|
||||
return 2
|
||||
cmd = argv[0]
|
||||
if cmd == "reports":
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(_reports)
|
||||
for comment_id, count, hidden, login_id, body in rows or []:
|
||||
print(f"{comment_id}\t신고 {count}\t{'숨김' if hidden else '보임'}\t{login_id}\t{body}")
|
||||
elif cmd in {"hide", "show"}:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: ReactionCRUD().set_hidden(s, int(argv[1]), cmd == "hide"))
|
||||
print("바뀜" if ok else "그대로 (없는 댓글이거나 이미 그 상태)")
|
||||
else:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: _set_status(s, argv[1], 2 if cmd == "suspend" else 1))
|
||||
print("바뀜" if ok else "없는 아이디")
|
||||
await DB_SESSION_MNG.stop()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
print(err.name)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main(sys.argv[1:])))
|
||||
@@ -127,6 +127,16 @@ class AuthService:
|
||||
"""이 사용자의 모든 기기 토큰을 무효로 만든다."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.update(s, user.user_id, {"token_version": user.token_version + 1})])
|
||||
|
||||
async def agree_terms(self, user: User) -> tuple[ErrorType, Optional[User]]:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.agree_terms(s, user.user_id)])
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, user.user_id))
|
||||
|
||||
async def withdraw(self, user: User) -> ErrorType:
|
||||
"""탈퇴: 계정과 남긴 댓글·좋아요를 한 번에 지운다. 계정이 없어지니 가진 토큰도 바로 못 쓴다."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.withdraw(s, user.user_id)])
|
||||
|
||||
async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]:
|
||||
"""닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다."""
|
||||
values: dict = {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
@@ -6,7 +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.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
|
||||
@@ -92,7 +93,7 @@ class ReactionService:
|
||||
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, cursor, PAGE))
|
||||
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()
|
||||
@@ -109,6 +110,8 @@ class ReactionService:
|
||||
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
|
||||
@@ -145,3 +148,37 @@ class ReactionService:
|
||||
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 []
|
||||
@@ -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_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ def client():
|
||||
|
||||
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']}"}
|
||||
h = {"Authorization": f"Bearer {body['access_token']}"}
|
||||
await c.post("/v1/auth/terms", headers=h) # 로그인한 사람은 약관에 동의해야 댓글을 쓴다
|
||||
return h
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -147,3 +149,26 @@ async def test_hero_tomorrow_and_tomorrow_slots(offline):
|
||||
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
||||
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
||||
assert res["day"] == hero["tomorrow"]["day"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_can_be_reported_not_blocked(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}/comment"
|
||||
listing = f"{url}/list"
|
||||
anon_id = (await c.post(url, headers=IP_A, json={"body": "익명 댓글"})).json()["comment"]["comment_id"]
|
||||
writer = await _login(c, "anon_mod_01")
|
||||
writer_id = (await c.post(url, headers=writer, json={"body": "회원 댓글"})).json()["comment"]["comment_id"]
|
||||
viewer = await _login(c, "anon_mod_02")
|
||||
|
||||
blocked = (await c.post(f"/v1/reaction/comment/{writer_id}/block", headers=viewer)).json()
|
||||
assert blocked["result"]["success"] is True
|
||||
ids = [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||
assert anon_id in ids and writer_id not in ids
|
||||
|
||||
assert (await c.post(f"/v1/reaction/comment/{anon_id}/block", headers=viewer)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(f"/v1/reaction/comment/{anon_id}/report", headers=viewer, json={"reason": 1})).json()["result"]["success"] is True
|
||||
assert anon_id not in [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||
assert anon_id in [x["comment_id"] for x in (await c.get(listing, headers=IP_B)).json()["comments"]]
|
||||
@@ -10,8 +10,12 @@ def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _signup(c, login_id="mina_01", nickname="망원동주민"):
|
||||
return (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||
async def _signup(c, login_id="mina_01", nickname="망원동주민", agree=True):
|
||||
"""가입하고, 댓글을 쓸 수 있게 이용약관에도 동의한다 (agree=False 면 안 함)."""
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||
if agree and body.get("access_token"):
|
||||
await c.post("/v1/auth/terms", headers={"Authorization": f"Bearer {body['access_token']}"})
|
||||
return body
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -122,3 +126,118 @@ async def test_logout_invalidates_access_and_refresh_tokens():
|
||||
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
|
||||
again = (await c.post("/v1/auth/login", json={"login_id": "mina_out", "password": "password1"})).json()
|
||||
assert (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {again['access_token']}"})).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_withdraw_deletes_account_and_reactions(offline):
|
||||
async with client() as c:
|
||||
body = await _signup(c, login_id="mina_bye")
|
||||
h = {"Authorization": f"Bearer {body['access_token']}"}
|
||||
other = {"Authorization": f"Bearer {(await _signup(c, 'other_bye', '남는사람'))['access_token']}"}
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)
|
||||
await c.post(f"/v1/reaction/post/{post_id}/save", headers=h)
|
||||
mine = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "곧 떠나요"})).json()["comment"]
|
||||
kept = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=other, json={"body": "남아요"})).json()["comment"]
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/like", headers=h)
|
||||
await c.post(f"/v1/reaction/comment/{mine['comment_id']}/like", headers=other)
|
||||
|
||||
assert (await c.delete("/v1/auth/me")).status_code == 401
|
||||
assert (await c.delete("/v1/auth/me", headers=h)).json()["result"]["success"] is True
|
||||
|
||||
assert (await c.get("/v1/auth/me", headers=h)).status_code == 401
|
||||
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
|
||||
assert (await c.post("/v1/auth/login", json={"login_id": "mina_bye", "password": "password1"})).json()["result"]["desc"] == "AUTH_FAILED"
|
||||
comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"]
|
||||
assert [x["body"] for x in comments] == ["남아요"] and comments[0]["like_count"] == 0
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["like_count"] == 0 and p["comment_count"] == 1
|
||||
# 같은 아이디로 다시 가입할 수 있다
|
||||
assert (await _signup(c, login_id="mina_bye"))["result"]["success"] is True
|
||||
|
||||
|
||||
def _h(body):
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
async def _comment(c, post_id, h, text):
|
||||
return (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": text})).json()
|
||||
|
||||
|
||||
async def _bodies(c, post_id, h=None):
|
||||
return [x["body"] for x in (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=h or {})).json()["comments"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_comment_needs_terms_agreement(offline):
|
||||
async with client() as c:
|
||||
h = _h(await _signup(c, agree=False))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
assert (await c.get("/v1/auth/me", headers=h)).json()["me"]["terms_agreed"] is False
|
||||
assert (await _comment(c, post_id, h, "안녕"))["result"]["desc"] == "TERMS_REQUIRED"
|
||||
assert (await c.post("/v1/auth/terms", headers=h)).json()["me"]["terms_agreed"] is True
|
||||
assert (await _comment(c, post_id, h, "안녕"))["comment"]["body"] == "안녕"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_report_hides_for_reporter_then_for_all_at_three(offline):
|
||||
async with client() as c:
|
||||
writer = _h(await _signup(c, "writer_1", "쓴사람"))
|
||||
r = [_h(await _signup(c, f"reporter_{i}", f"신고자{i}")) for i in range(3)]
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
bad = (await _comment(c, post_id, writer, "광고입니다"))["comment"]
|
||||
url = f"/v1/reaction/comment/{bad['comment_id']}/report"
|
||||
|
||||
assert (await c.post(url, headers=writer, json={"reason": 2})).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 9})).status_code == 422
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True # 두 번 신고해도 한 번
|
||||
assert await _bodies(c, post_id, r[0]) == [] and await _bodies(c, post_id, r[1]) == ["광고입니다"]
|
||||
|
||||
await c.post(url, headers=r[1], json={"reason": 1})
|
||||
assert await _bodies(c, post_id) == ["광고입니다"]
|
||||
await c.post(url, headers=r[2], json={"reason": 1})
|
||||
assert await _bodies(c, post_id) == [] and await _bodies(c, post_id, writer) == []
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["comment_count"] == 0
|
||||
# 숨긴 댓글을 지워도 댓글 수가 한 번 더 줄지 않는다
|
||||
assert (await c.delete(f"/v1/reaction/comment/{bad['comment_id']}", headers=writer)).json()["result"]["success"] is True
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["comment_count"] == 0
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_block_hides_author_comments_and_can_be_undone(offline):
|
||||
async with client() as c:
|
||||
me = _h(await _signup(c))
|
||||
other = _h(await _signup(c, "rude_1", "무례한"))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
rude = (await _comment(c, post_id, other, "흥"))["comment"]
|
||||
mine = (await _comment(c, post_id, me, "좋아요"))["comment"]
|
||||
|
||||
assert (await c.post(f"/v1/reaction/comment/{mine['comment_id']}/block", headers=me)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block")).status_code == 401
|
||||
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block", headers=me)).json()["result"]["success"] is True
|
||||
assert await _bodies(c, post_id, me) == ["좋아요"] and await _bodies(c, post_id) == ["흥", "좋아요"]
|
||||
|
||||
blocked = (await c.get("/v1/reaction/block/list", headers=me)).json()["users"]
|
||||
assert [u["nickname"] for u in blocked] == ["무례한"]
|
||||
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["success"] is True
|
||||
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert await _bodies(c, post_id, me) == ["흥", "좋아요"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_withdraw_removes_reports_and_blocks(offline):
|
||||
async with client() as c:
|
||||
leaver = _h(await _signup(c, "leaver_1", "떠날사람"))
|
||||
stay = _h(await _signup(c, "stay_1", "남는사람"))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
kept = (await _comment(c, post_id, stay, "남아요"))["comment"]
|
||||
gone = (await _comment(c, post_id, leaver, "떠나요"))["comment"]
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/report", headers=leaver, json={"reason": 4})
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/block", headers=leaver)
|
||||
await c.post(f"/v1/reaction/comment/{gone['comment_id']}/block", headers=stay)
|
||||
assert (await c.delete("/v1/auth/me", headers=leaver)).json()["result"]["success"] is True
|
||||
assert (await c.get("/v1/reaction/block/list", headers=stay)).json()["users"] == []
|
||||
assert await _bodies(c, post_id, stay) == ["남아요"]
|
||||
@@ -84,6 +84,7 @@ async def test_like_in_one_sido_not_seen_in_another(offline):
|
||||
async with client() as c:
|
||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
await c.post("/v1/auth/terms", headers=h)
|
||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||
|
||||
Reference in new issue
Block a user