Files
o2o-weather/backend/services/talk_service.py
T

130 lines
6.0 KiB
Python

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.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
BODY_MAX = 100
DAILY_MAX = 5
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
HIDE_AT = 3
PAGE = 20
# 링크(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()
@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], cursor: Optional[int]) -> tuple[ErrorType, list[TalkView]]:
viewer = user.user_id if user else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
if user is not None and rows:
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, [t.talk_id for t, *_ in rows]))
if err is not ErrorType.SUCCESS:
return err, []
return ErrorType.SUCCESS, [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]
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) -> tuple[ErrorType, Optional[TalkView]]:
body = " ".join(body.split())
if not body or len(body) > BODY_MAX:
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))
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, user: User, 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, user.user_id, 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