Files

230 lines
11 KiB
Python

import math
import re
from dataclasses import dataclass
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, 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 is_ours
BODY_MAX = 100
DAILY_MAX = 5
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
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)
_PHONE = re.compile(r"0\d{1,2}[-.\s]?\d{3,4}[-.\s]?\d{4}")
_SKY = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
_RAIN = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
def weather_line(row: Optional[WeatherHourly]) -> Optional[str]:
"""글에 붙일 그때 날씨: 18° 맑음 / 12° 비."""
if row is None:
return None
rain = RainType(row.rain_type)
word = _RAIN.get(rain) or _SKY.get(Sky(row.sky), "")
return f"{round(float(row.temp_c))}° {word}".strip()
def spread_authors(views: list["TalkView"]) -> list["TalkView"]:
"""같은 사람 글이 붙으면 뒤에서 다른 사람 글을 당겨 끼운다."""
out = list(views)
for i in range(1, len(out)):
if out[i].author.user_id == out[i - 1].author.user_id:
j = next((k for k in range(i + 1, len(out)) if out[k].author.user_id != out[i - 1].author.user_id), None)
if j is not None:
out.insert(i, out.pop(j))
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
@dataclass
class TalkView:
talk: Talk
author: User
region_name: Optional[str]
liked: bool
mine: bool
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 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, 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])
if err is not ErrorType.SUCCESS:
return err, [], None
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]
last = rows[-1] if len(rows) == PAGE else None
return ErrorType.SUCCESS, spread_authors(views), f"{last[3]}_{last[0].talk_id}" if last else None
async def mine(self, user: User, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView], Optional[int]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.mine(s, user.user_id, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, [], None
err, liked = await self._liked(user, "", [t.talk_id for t, _ in rows])
if err is not ErrorType.SUCCESS:
return err, [], None
views = [TalkView(talk=t, author=user, region_name=name, liked=t.talk_id in liked, mine=True) for t, name in rows]
return ErrorType.SUCCESS, views, rows[-1][0].talk_id if len(rows) == PAGE else None
async def _liked(self, user: Optional[User], ip_hash: str, ids: list[int]) -> tuple[ErrorType, set[int]]:
if not ids:
return ErrorType.SUCCESS, set()
if user is not None:
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
async def _weather_now(self, region_code: str) -> Optional[str]:
"""지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다."""
now = now_kst()
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region_code, now - timedelta(hours=1), now + timedelta(hours=2)))
if err is not ErrorType.SUCCESS or not rows:
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, 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 not is_ours(image):
return ErrorType.INVALID_INPUT, None
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
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
if region is None:
return ErrorType.INVALID_INPUT, None
today = kst_midnight(now_kst().date())
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count_since(s, user.user_id, today))
if err is not ErrorType.SUCCESS:
return err, None
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, 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)
async def delete(self, user: User, talk_id: int) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, talk_id, user.user_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
async def _talk(self, talk_id: int) -> tuple[ErrorType, Optional[Talk]]:
err, t = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, talk_id))
if err is not ErrorType.SUCCESS:
return err, None
return (ErrorType.SUCCESS, t) if t is not None else (ErrorType.NOT_FOUND, None)
async def like(self, who: Liker, talk_id: int, on: bool) -> tuple[ErrorType, Optional[int]]:
err, _ = await self._talk(talk_id)
if err is not ErrorType.SUCCESS:
return err, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_like(s, talk_id, who, on))
async def report(self, user: User, talk_id: int, reason: TalkReport) -> ErrorType:
err, t = await self._talk(talk_id)
if err is not ErrorType.SUCCESS or t is None:
return err
if t.user_id == user.user_id:
return ErrorType.INVALID_INPUT
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.report(s, talk_id, user.user_id, reason.value, HIDE_AT))
return err
async def block_author(self, user: User, talk_id: int) -> ErrorType:
err, t = await self._talk(talk_id)
if err is not ErrorType.SUCCESS or t is None:
return err
if t.user_id == user.user_id:
return ErrorType.INVALID_INPUT
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.block(s, user.user_id, t.user_id))
return err