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

+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)