import re from dataclasses import dataclass from datetime import 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.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 BODY_MAX = 100 DAILY_MAX = 5 # 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다 HIDE_AT = 3 PAGE = 20 # 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다 LOCAL_BOOST = timedelta(hours=12) # 링크(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 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 page(self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str]) -> 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)) 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) -> 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: 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)) 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