feat: 작업 중이던 변경 반영 — 글 주제(동네 이야기·하늘·비·단풍·옷차림)와 주제별 묶음을 피드 사이사이에, 이야기 페이지(/talk), 애드센스 코드·ads.txt·개인정보처리방침, 사진 검증을 Blob 주소까지

This commit is contained in:
minaChoi committed 2026-10-23 15:06:21 +09:00
1 parent 1393fc465c
commit 3cb58b9f0f
22 files changed
+718 -60

No files matched your search

+1
View File
@@ -401,6 +401,7 @@ class Talk(Base):
body: Mapped[str] = mapped_column(String(100))
weather: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
image: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
topic: Mapped[int] = mapped_column(SmallInteger, default=1)
like_count: Mapped[int] = mapped_column(Integer, default=0)
report_count: Mapped[int] = mapped_column(Integer, default=0)
hidden: Mapped[bool] = mapped_column(Boolean, default=False)
+10
View File
@@ -115,6 +115,16 @@ class IndexCategory(CodeEnum):
LIFE = 4
class TalkTopic(CodeEnum):
"""사람 글 주제. 안 고르면 동네 이야기. 피드에서 같은 주제 포스트 옆에 묶어 보여 준다"""
LOCAL = 1 # 동네 이야기
SKY = 2 # 하늘·노을
RAIN = 3 # 비·눈
FOLIAGE = 4 # 단풍·꽃
OUTFIT = 5 # 오늘 옷차림
class TalkReport(CodeEnum):
ABUSE = 1 # 욕설·비하
SPAM = 2 # 광고·도배
+20 -3
View File
@@ -13,7 +13,8 @@ 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
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)."""
@@ -28,10 +29,24 @@ class TalkCRUD:
)
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))
@@ -48,8 +63,10 @@ class TalkCRUD:
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) -> Talk:
t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather, image=image)
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)
+3
View File
@@ -294,6 +294,9 @@ CREATE TABLE IF NOT EXISTS public.talk (
);
CREATE INDEX IF NOT EXISTS idx_talk_list ON public.talk (talk_id DESC) WHERE deleted = FALSE AND hidden = FALSE;
CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at);
-- 글 주제 (TalkTopic: 1 동네 이야기, 2 하늘·노을, 3 비·눈, 4 단풍·꽃, 5 오늘 옷차림)
ALTER TABLE public.talk ADD COLUMN IF NOT EXISTS topic SMALLINT NOT NULL DEFAULT 1;
CREATE INDEX IF NOT EXISTS idx_talk_recent ON public.talk (created_at DESC) WHERE deleted = FALSE AND hidden = FALSE;
CREATE TABLE IF NOT EXISTS public.talk_like (
talk_id BIGINT NOT NULL,
+12 -1
View File
@@ -3,7 +3,7 @@ from typing import Optional
from pydantic import Field
from common.enums import TalkReport
from common.enums import TalkReport, TalkTopic
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
@@ -17,6 +17,7 @@ class TalkData(WebPacketProtocol):
weather: Optional[str] = Field(None, description="쓸 때 그 동네 날씨 (18° 맑음)")
body: str
image: Optional[str] = Field(None, description="올린 사진 주소")
topic: TalkTopic = TalkTopic.LOCAL
like_count: int
liked: bool
mine: bool
@@ -27,6 +28,7 @@ class Req_Talk(Req_WebPacketProtocol):
region_code: str = Field(min_length=10, max_length=10)
body: str = Field(min_length=1, max_length=200, description="공백을 줄인 뒤 100자까지")
image: Optional[str] = Field(None, max_length=200, description="먼저 올린 사진 주소 (POST /v1/talk/image 결과)")
topic: TalkTopic = Field(TalkTopic.LOCAL, description="글 주제. 안 고르면 동네 이야기")
class Req_TalkReport(Req_WebPacketProtocol):
@@ -38,6 +40,15 @@ class Res_TalkList(Res_WebPacketProtocol):
next_cursor: Optional[str] = Field(None, description="다음 페이지를 받을 때 그대로 cursor 로 보낸다")
class TalkGroup(WebPacketProtocol):
topic: int = Field(description="0 이면 '동네 사람들'(모든 주제), 아니면 TalkTopic")
talks: list[TalkData] = []
class Res_TalkGroups(Res_WebPacketProtocol):
groups: list[TalkGroup] = Field([], description="동네 사람들 묶음은 늘 있고(비어 있을 수 있음), 주제 묶음은 3장 이상일 때만")
class Res_Talk(Res_WebPacketProtocol):
talk: Optional[TalkData] = None
+19 -5
View File
@@ -7,12 +7,12 @@ from fastapi.responses import FileResponse
from common.auth import current_user, optional_user
from common.database.model.models import User
from common.enums import ErrorType
from common.enums import ErrorType, TalkTopic
from common.liker import Liker, liker
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkGroups, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData, TalkGroup
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
from services.talk_service import TalkService, TalkView
@@ -23,19 +23,33 @@ def _data(v: TalkView) -> TalkData:
t, u = v.talk, v.author
return TalkData(
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
body=t.body, image=t.image, like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
)
@router.get("/groups", response_model=Res_TalkGroups, response_model_exclude_none=True, summary="오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)")
async def talk_groups(
region: Optional[str] = Query(None, min_length=10, max_length=10, description="보는 사람의 구 행정코드"),
user: Optional[User] = Depends(optional_user),
who: Liker = Depends(liker),
service: TalkService = Depends(),
) -> Res_TalkGroups:
err, groups = await service.groups(user, who.ip_hash, region)
if err is not ErrorType.SUCCESS:
return Res_TalkGroups(result=error_info(err))
return Res_TalkGroups(groups=[TalkGroup(topic=k, talks=[_data(v) for v in vs]) for k, vs in groups.items()])
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)")
async def list_talks(
region: Optional[str] = Query(None, min_length=10, max_length=10, description="보는 사람의 구 행정코드"),
topic: Optional[TalkTopic] = Query(None, description="이 주제 글만. 없으면 전체"),
cursor: Optional[str] = Query(None, max_length=40),
user: Optional[User] = Depends(optional_user),
who: Liker = Depends(liker),
service: TalkService = Depends(),
) -> Res_TalkList:
err, views, nxt = await service.page(user, who.ip_hash, region, cursor)
err, views, nxt = await service.page(user, who.ip_hash, region, cursor, topic.value if topic else None)
if err is not ErrorType.SUCCESS:
return Res_TalkList(result=error_info(err))
return Res_TalkList(talks=[_data(v) for v in views], next_cursor=nxt)
@@ -53,7 +67,7 @@ async def list_my_talks(cursor: Optional[str] = Query(None, max_length=20), user
@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)")
async def add_talk(req: Req_Talk, user: User = Depends(current_user), service: TalkService = Depends()) -> Res_Talk:
err, v = await service.add(user, req.region_code, req.body, req.image)
err, v = await service.add(user, req.region_code, req.body, req.image, req.topic)
return Res_Talk(result=error_info(err)) if err is not ErrorType.SUCCESS or v is None else Res_Talk(talk=_data(v))
+64 -8
View File
@@ -1,19 +1,20 @@
import math
import re
from dataclasses import dataclass
from datetime import timedelta
from datetime import datetime, timedelta
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Talk, User, WeatherHourly
from common.enums import ErrorType, RainType, Sky, TalkReport
from common.enums import ErrorType, RainType, Sky, TalkReport, TalkTopic
from common.liker import Liker
from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.talk_crud import TalkCRUD
from crud.weather_crud import WeatherCRUD
from services.talk_image import file_of
from services.talk_image import is_ours
BODY_MAX = 100
DAILY_MAX = 5
@@ -22,6 +23,13 @@ HIDE_AT = 3
PAGE = 20
# 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다
LOCAL_BOOST = timedelta(hours=12)
# 피드 묶음: 최근 이 기간 글 중에서 고른다. 한 묶음 최대 장수, 이보다 적으면 주제 묶음은 숨긴다
GROUP_WINDOW = timedelta(days=7)
GROUP_POOL = 300
GROUP_MAX = 10
GROUP_MIN = 3
# 묶음 순서는 '덜 지난 것처럼 쳐 주는 시간'으로 매긴다: 같은 구 6시간, 같은 시도 3시간, 좋아요는 2시간 × log2(1+좋아요)
NEAR_GU_H, NEAR_SIDO_H, LIKE_H = 6, 3, 2
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
@@ -51,6 +59,30 @@ def spread_authors(views: list["TalkView"]) -> list["TalkView"]:
return out
def group_age(t: Talk, region_code: Optional[str], now: datetime) -> float:
"""묶음 안 정렬 값(작을수록 앞): 지난 시간에서 가까운 동네·좋아요만큼 뺀다. 오래된 글은 좋아요가 많아도 결국 뒤로 간다"""
age = (now - t.created_at).total_seconds() / 3600
near = NEAR_GU_H if region_code and t.region_code == region_code else NEAR_SIDO_H if region_code and t.region_code[:2] == region_code[:2] else 0
return age - near - LIKE_H * math.log2(1 + t.like_count)
def pick_group(views: list["TalkView"], region_code: Optional[str], now: datetime) -> list["TalkView"]:
"""한 사람 한 장, 최대 GROUP_MAX 장. 첫 장은 신고 받은 적 없는 글"""
out: list[TalkView] = []
seen: set = set()
for v in sorted(views, key=lambda v: group_age(v.talk, region_code, now)):
if v.author.user_id in seen:
continue
seen.add(v.author.user_id)
out.append(v)
if len(out) == GROUP_MAX:
break
clean = next((i for i, v in enumerate(out) if v.talk.report_count == 0), None)
if clean:
out.insert(0, out.pop(clean))
return out
def parse_cursor(cursor: str) -> Optional[tuple[int, int]]:
key, _, talk_id = cursor.partition("_")
return (int(key), int(talk_id)) if key.lstrip("-").isdigit() and talk_id.isdigit() else None
@@ -69,14 +101,36 @@ class TalkService:
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
self.crud, self.regions, self.weather = crud, regions, weather
async def page(self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str]) -> tuple[ErrorType, list[TalkView], Optional[str]]:
async def groups(self, user: Optional[User], ip_hash: str, region_code: Optional[str]) -> tuple[ErrorType, dict[int, list[TalkView]]]:
"""피드 묶음. 0은 '동네 사람들'(모든 주제), 나머지는 주제별(GROUP_MIN 장 이상일 때만)"""
now = now_kst()
viewer = user.user_id if user else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.recent(s, viewer, now - GROUP_WINDOW, GROUP_POOL))
if err is not ErrorType.SUCCESS:
return err, {}
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
if err is not ErrorType.SUCCESS:
return err, {}
views = [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows]
out = {0: pick_group(views, region_code, now)}
for topic in TalkTopic:
if topic is TalkTopic.LOCAL:
continue
group = pick_group([v for v in views if v.talk.topic == topic.value], region_code, now)
if len(group) >= GROUP_MIN:
out[topic.value] = group
return ErrorType.SUCCESS, out
async def page(
self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str], topic: Optional[int] = None
) -> tuple[ErrorType, list[TalkView], Optional[str]]:
"""한 페이지와 다음 페이지 cursor. 같은 사람 글은 페이지 안에서 떨어뜨린다."""
after = parse_cursor(cursor) if cursor else None
if cursor and after is None:
return ErrorType.INVALID_INPUT, [], None
viewer = user.user_id if user else None
sido = region_code[:2] if region_code else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, sido, int(LOCAL_BOOST.total_seconds()), after, PAGE))
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, sido, int(LOCAL_BOOST.total_seconds()), after, PAGE, topic))
if err is not ErrorType.SUCCESS:
return err, [], None
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
@@ -111,11 +165,13 @@ class TalkService:
return None
return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now)))
async def add(self, user: User, region_code: str, body: str, image: Optional[str] = None) -> tuple[ErrorType, Optional[TalkView]]:
async def add(
self, user: User, region_code: str, body: str, image: Optional[str] = None, topic: TalkTopic = TalkTopic.LOCAL
) -> tuple[ErrorType, Optional[TalkView]]:
body = " ".join(body.split())
if not body or len(body) > BODY_MAX:
return ErrorType.INVALID_INPUT, None
if image is not None and file_of(image) is None:
if image is not None and not is_ours(image):
return ErrorType.INVALID_INPUT, None
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
@@ -131,7 +187,7 @@ class TalkService:
if n >= DAILY_MAX:
return ErrorType.DAILY_LIMIT, None
weather = await self._weather_now(region_code)
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image))
err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather, image, topic.value))
if err is not ErrorType.SUCCESS or t is None:
return err, None
return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True)
+49 -1
View File
@@ -4,7 +4,9 @@ import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
from services.talk_service import DAILY_MAX, HIDE_AT, parse_cursor, spread_authors, weather_line
from datetime import datetime, timedelta, timezone
from services.talk_service import DAILY_MAX, GROUP_MAX, HIDE_AT, parse_cursor, pick_group, spread_authors, weather_line
REGION = "1144000000"
BUSAN = "2611000000"
@@ -143,3 +145,49 @@ def test_spread_authors_and_cursor():
assert [x.author.user_id for x in spread_authors([v("a"), v("a"), v("a"), v("b"), v("c")])] == ["a", "b", "a", "c", "a"]
assert parse_cursor("1760000000_42") == (1760000000, 42)
assert parse_cursor("12") is None and parse_cursor("x_1") is None
@pytest.mark.anyio
async def test_topic_is_saved_and_filters_list():
async with client() as c:
h = await _login(c, "talk_tp1")
sky = (await c.post("/v1/talk", json={"region_code": REGION, "body": "노을 분홍빛", "topic": 2}, headers=h)).json()["talk"]
plain = (await _write(c, h, "그냥 동네 이야기"))["talk"]
assert sky["topic"] == 2 and plain["topic"] == 1
only_sky = _ids((await c.get("/v1/talk/list", params={"topic": 2})).json())
only_foliage = _ids((await c.get("/v1/talk/list", params={"topic": 4})).json())
assert sky["talk_id"] in only_sky and plain["talk_id"] not in only_sky
assert sky["talk_id"] not in only_foliage
@pytest.mark.anyio
async def test_groups_have_near_group_and_topic_group_from_three_people():
async with client() as c:
for i in range(3):
h = await _login(c, f"talk_gr{i}")
for j in range(2):
await c.post("/v1/talk", json={"region_code": REGION, "body": f"단풍 물들었어요 {i}-{j}", "topic": 4}, headers=h)
groups = {g["topic"]: g["talks"] for g in (await c.get("/v1/talk/groups", params={"region": REGION})).json()["groups"]}
assert 0 in groups and 4 in groups
assert all(t["topic"] == 4 for t in groups[4])
for talks in groups.values():
names = [t["nickname"] for t in talks]
assert len(names) == len(set(names)) and len(talks) <= GROUP_MAX
def _view(talk_id, user, region, hours_ago, likes=0, reports=0):
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
talk = SimpleNamespace(talk_id=talk_id, region_code=region, created_at=now - timedelta(hours=hours_ago), like_count=likes, report_count=reports)
return SimpleNamespace(talk=talk, author=SimpleNamespace(user_id=user))
def test_pick_group_orders_near_fresh_first_one_per_person_clean_first():
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
far = _view(1, "a", BUSAN, 1)
same_sido = _view(2, "b", "1111000000", 1)
same_gu = _view(3, "c", REGION, 1)
old_popular = _view(4, "d", REGION, 30, likes=50)
again = _view(5, "c", REGION, 0)
assert [v.talk.talk_id for v in pick_group([far, same_sido, same_gu, old_popular, again], REGION, now)] == [5, 2, 1, 4]
reported = _view(6, "e", REGION, 0, reports=1)
assert pick_group([reported, far], REGION, now)[0].talk.talk_id == 1