chore: main 병합 — 로그인 없이 댓글·좋아요, 구글 로그인만, 동네 이야기·카드뉴스 등 (차단 표 user_block 하나로 합침, 익명 댓글도 신고 가능)

This commit is contained in:
minaChoi committed 2026-10-26 10:00:40 +09:00
commit dba34675c8
408 files changed
+36377 -725

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
from datetime import date, datetime
from typing import Optional
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import CardImage, CardSet, Post
from common.enums import CardStatus, PostType, RefType
# 카드뉴스 포스트 번호. 03:00 에 만드는 카드(LINEUP 1~20)와 겹치지 않게 101부터
CARD_POSITION_START = 101
NATIONAL_SCOPE = "00"
class CardCRUD:
async def create(self, s: AsyncSession, card: CardSet, images: list[bytes]) -> CardSet:
s.add(card)
await s.flush()
s.add_all(CardImage(card_id=card.card_id, seq=i + 1, data=data) for i, data in enumerate(images))
return card
async def get(self, s: AsyncSession, card_id: int) -> Optional[CardSet]:
return await s.get(CardSet, card_id)
async def recent(self, s: AsyncSession, limit: int) -> list[CardSet]:
"""만든 순서 역순. 올린 것·승인 대기·반려 모두."""
return list((await s.scalars(select(CardSet).order_by(CardSet.card_id.desc()).limit(limit))).all())
async def many(self, s: AsyncSession, card_ids: list[int]) -> list[CardSet]:
if not card_ids:
return []
return list((await s.scalars(select(CardSet).where(CardSet.card_id.in_(card_ids)))).all())
async def image_counts(self, s: AsyncSession, card_ids: list[int]) -> dict[int, int]:
if not card_ids:
return {}
rows = await s.execute(select(CardImage.card_id, func.count()).where(CardImage.card_id.in_(card_ids)).group_by(CardImage.card_id))
return {card_id: n for card_id, n in rows.all()}
async def image(self, s: AsyncSession, card_id: int, seq: int) -> Optional[bytes]:
row = await s.get(CardImage, (card_id, seq))
return row.data if row is not None else None
async def publish(self, s: AsyncSession, card: CardSet, day: date, now: datetime, end: datetime) -> Post:
"""그날 전국 피드에 포스트 하나로 올린다. 같은 날 여러 개면 번호를 하나씩 늘린다."""
last = await s.scalar(select(func.max(Post.position)).where(Post.feed_date == day, Post.scope == NATIONAL_SCOPE, Post.position >= CARD_POSITION_START))
post = Post(feed_date=day, position=(last or CARD_POSITION_START - 1) + 1, scope=NATIONAL_SCOPE, post_type=PostType.CARD.value,
ref_type=RefType.CARD.value, ref_id=card.card_id, published_at=now, end_at=end)
s.add(post)
await s.flush()
card.status, card.post_id, card.published_at = CardStatus.PUBLISHED.value, post.post_id, now
return post
+3 -2
View File
@@ -35,9 +35,10 @@ class IndexCRUD:
return await s.scalar(stmt)
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
"""현재 방식으로 모든 구간을 계산하지 않은 행이 있는지."""
stmt = select(IndexScore.index_id).where(
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
IndexScore.region_code == region_code, IndexScore.score_date == day,
text("NOT (index_score.slots ?& ARRAY['morning', 'day', 'evening', 'night', 'early'])")
).limit(1)
return (await s.scalar(stmt)) is not None
+24
View File
@@ -0,0 +1,24 @@
import uuid
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import MyGak
class MyGakCRUD:
async def of_user(self, s: AsyncSession, user_id: uuid.UUID) -> list[MyGak]:
return list((await s.scalars(select(MyGak).where(MyGak.user_id == user_id).order_by(MyGak.my_gak_id))).all())
async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int:
return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id))
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict) -> MyGak:
row = MyGak(user_id=user_id, name=name, rule=rule)
s.add(row)
await s.flush()
return row
async def delete(self, s: AsyncSession, user_id: uuid.UUID, my_gak_id: int) -> bool:
res = await s.execute(delete(MyGak).where(MyGak.my_gak_id == my_gak_id, MyGak.user_id == user_id).returning(MyGak.my_gak_id))
return res.first() is not None
+41 -24
View File
@@ -1,23 +1,32 @@
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import delete, 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, CommentReport, Post, PostLike, PostSave, User, UserBlock
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."""
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, user_id: uuid.UUID, on: bool) -> int:
async def toggle_post_like(self, s: AsyncSession, post_id: int, who: Liker, 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:
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))
@@ -36,21 +45,24 @@ class ReactionCRUD:
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, 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(
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)),
Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.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)
@@ -60,16 +72,24 @@ class ReactionCRUD:
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)
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 delete_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID) -> bool:
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, Comment.user_id == user_id, Comment.deleted.is_(False))
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
)
row = res.first()
@@ -80,20 +100,17 @@ class ReactionCRUD:
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]:
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), 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:
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) -> 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 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 건이 되면 숨기고 댓글 수에서 뺀다."""
+27
View File
@@ -0,0 +1,27 @@
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import defer
from common.database.model.models import Reel
class ReelCRUD:
async def create(self, s: AsyncSession, reel: Reel) -> Reel:
s.add(reel)
await s.flush()
return reel
async def get(self, s: AsyncSession, reel_id: int) -> Optional[Reel]:
return await s.get(Reel, reel_id)
async def recent(self, s: AsyncSession, limit: int) -> list[Reel]:
"""만든 순서 역순. 영상·표지 바이트는 안 읽는다."""
return list((await s.scalars(select(Reel).options(defer(Reel.video), defer(Reel.cover)).order_by(Reel.reel_id.desc()).limit(limit))).all())
async def video(self, s: AsyncSession, reel_id: int) -> Optional[bytes]:
return await s.scalar(select(Reel.video).where(Reel.reel_id == reel_id))
async def cover(self, s: AsyncSession, reel_id: int) -> Optional[bytes]:
return await s.scalar(select(Reel.cover).where(Reel.reel_id == reel_id))
+96
View File
@@ -0,0 +1,96 @@
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import BigInteger, case, cast, delete, func, select, tuple_, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Region, Talk, TalkLike, TalkLikeAnon, TalkReport, User, UserBlock
from common.liker import Liker
from crud.reaction_crud import toggle_like_row
class TalkCRUD:
async def page(
self, s: AsyncSession, viewer: Optional[uuid.UUID], sido: Optional[str], boost_sec: int, cursor: Optional[tuple[int, int]], limit: int,
topic: Optional[int] = None,
) -> list[tuple[Talk, User, Optional[str], int]]:
"""최신 글부터. 보는 사람과 같은 시도 글은 boost_sec 만큼 늦게 쓴 것처럼 앞에 둔다. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다.
cursor 는 앞 페이지 마지막 글의 (정렬 키, talk_id)."""
key = cast(func.floor(func.extract("epoch", Talk.created_at)), BigInteger)
if sido:
key = key + case((func.left(Talk.region_code, 2) == sido, boost_sec), else_=0)
stmt = (
select(Talk, User, Region.short_name, key)
.join(User, User.user_id == Talk.user_id)
.outerjoin(Region, Region.code == Talk.region_code)
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False))
)
if viewer is not None:
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
if topic is not None:
stmt = stmt.where(Talk.topic == topic)
if cursor is not None:
stmt = stmt.where(tuple_(key, Talk.talk_id) < tuple_(*cursor))
return list((await s.execute(stmt.order_by(key.desc(), Talk.talk_id.desc()).limit(limit))).all())
async def recent(self, s: AsyncSession, viewer: Optional[uuid.UUID], since: datetime, limit: int) -> list[tuple[Talk, User, Optional[str]]]:
"""since 뒤에 쓴 글 최신순 (숨김·지운 글, 내가 안 보기로 한 사람 글 빼고). 피드 묶음을 고를 재료"""
stmt = (
select(Talk, User, Region.short_name)
.join(User, User.user_id == Talk.user_id)
.outerjoin(Region, Region.code == Talk.region_code)
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False), Talk.created_at >= since)
)
if viewer is not None:
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
return list((await s.execute(stmt.order_by(Talk.created_at.desc()).limit(limit))).all())
async def mine(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Talk, Optional[str]]]:
"""내가 쓴 글, 최신부터. 신고로 숨겨진 글도 쓴 사람에겐 보인다."""
stmt = select(Talk, Region.short_name).outerjoin(Region, Region.code == Talk.region_code).where(Talk.user_id == user_id, Talk.deleted.is_(False))
if cursor is not None:
stmt = stmt.where(Talk.talk_id < cursor)
return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all())
async def liked(self, s: AsyncSession, user_id: uuid.UUID, talk_ids: list[int]) -> set[int]:
return set((await s.scalars(select(TalkLike.talk_id).where(TalkLike.user_id == user_id, TalkLike.talk_id.in_(talk_ids)))).all())
async def anon_liked(self, s: AsyncSession, ip_hash: str, talk_ids: list[int]) -> set[int]:
return set((await s.scalars(select(TalkLikeAnon.talk_id).where(TalkLikeAnon.ip_hash == ip_hash, TalkLikeAnon.talk_id.in_(talk_ids)))).all())
async def count_since(self, s: AsyncSession, user_id: uuid.UUID, since: datetime) -> int:
return await s.scalar(select(func.count()).select_from(Talk).where(Talk.user_id == user_id, Talk.created_at >= since))
async def add(
self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str], image: Optional[str] = None, topic: int = 1
) -> Talk:
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image, topic=topic)
s.add(t)
await s.flush()
await s.refresh(t)
return t
async def get(self, s: AsyncSession, talk_id: int) -> Optional[Talk]:
return await s.scalar(select(Talk).where(Talk.talk_id == talk_id, Talk.deleted.is_(False)))
async def delete(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID) -> bool:
res = await s.execute(update(Talk).where(Talk.talk_id == talk_id, Talk.user_id == user_id, Talk.deleted.is_(False)).values(deleted=True).returning(Talk.talk_id))
return res.first() is not None
async def toggle_like(self, s: AsyncSession, talk_id: int, who: Liker, on: bool) -> int:
"""좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다."""
if await toggle_like_row(s, who, TalkLike, TalkLikeAnon, "talk_id", talk_id, on):
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(like_count=Talk.like_count + (1 if on else -1)))
return await s.scalar(select(Talk.like_count).where(Talk.talk_id == talk_id))
async def report(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, reason: int, hide_at: int) -> None:
"""한 사람은 한 번만 센다. hide_at 건이 되면 숨긴다."""
res = await s.execute(insert(TalkReport).values(talk_id=talk_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(TalkReport.talk_id))
if res.first() is None:
return
await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(report_count=Talk.report_count + 1, hidden=Talk.report_count + 1 >= hide_at))
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())