feat: 10/20 회의 반영 — 이야기 탭을 오늘 피드로 합침(글쓰기 칸·사진 올리기·위치 정보 삭제), 오늘의 각 카드와 히어로·각 공유 템플릿, 나만의 각을 이름+날씨 조건 저장으로, 로그인 없이 좋아요(IP 해시), 피드 순서·불쾌지수 상시·포스트 그림 배경, 새 각 아이콘
This commit is contained in:
1 parent
017022a0b0
commit
d0213f41a6
81 files changed
+3503
-593
No files matched your search
@@ -0,0 +1,52 @@
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
from typing import Literal, Optional
|
||||
|
||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS
|
||||
|
||||
Rain = Literal["dry", "wet"]
|
||||
Air = Literal["good", "normal"]
|
||||
|
||||
# 미세먼지 허용 단계 → 초미세먼지(㎍/㎥) 점수 규칙. 단계 경계(좋음 15·보통 35)까지 100, 넘으면 깎는다
|
||||
_AIR = {"good": {"zero": 35, "full": 15}, "normal": {"zero": 75, "full": 35}}
|
||||
_WIND_LIMIT_OVER = 6 # 바람 상한에서 이만큼 더 세지면 0점
|
||||
|
||||
|
||||
def _n(v: float) -> float:
|
||||
"""근거 문구에 15.0° 대신 15° 로 나오게."""
|
||||
return int(v) if float(v).is_integer() else v
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MyRule:
|
||||
"""사용자가 정한 내 각 조건. None 인 항목은 보지 않는다."""
|
||||
|
||||
temp: Optional[tuple[float, float]] = None # 체감온도 범위(°)
|
||||
rain: Optional[Rain] = None # dry: 안 와야, wet: 와야
|
||||
wind_max: Optional[float] = None # 바람 상한(m/s)
|
||||
air: Optional[Air] = None # 미세먼지 허용 단계
|
||||
humidity: Optional[tuple[int, int]] = None # 습도 범위(%)
|
||||
slots: tuple[str, ...] = SLOTS # 볼 시간대
|
||||
|
||||
|
||||
def axes(rule: MyRule) -> list[str]:
|
||||
return [a for a, on in (("temp", rule.temp), ("rain", rule.rain), ("wind", rule.wind_max is not None), ("air", rule.air), ("humidity", rule.humidity)) if on]
|
||||
|
||||
|
||||
def definition(rule: MyRule) -> SimpleNamespace:
|
||||
"""공식 각과 같은 계산(evaluate)에 넣을 정의. 고른 조건끼리 가중치를 똑같이 나눈다."""
|
||||
used = axes(rule)
|
||||
share = {a: 100 // len(used) + (1 if i < 100 % len(used) else 0) for i, a in enumerate(used)} if used else {}
|
||||
return SimpleNamespace(
|
||||
**{f"weight_{a}": share.get(a, 0) for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")},
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": _n(rule.temp[0]), "hi": _n(rule.temp[1])} if rule.temp else {"type": "range", "lo": -50, "hi": 60},
|
||||
"rain": {"dir": rule.rain or "dry"},
|
||||
"wind": {"type": "calm", "ok": _n(rule.wind_max), "limit": rule.wind_max + _WIND_LIMIT_OVER} if rule.wind_max is not None else {"type": "ignore"},
|
||||
"humidity": {"type": "range", "lo": rule.humidity[0], "hi": rule.humidity[1]} if rule.humidity else {"type": "ignore"},
|
||||
"air": _AIR[rule.air] if rule.air else None,
|
||||
"time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [],
|
||||
windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
|
||||
)
|
||||
@@ -76,12 +76,13 @@ def sido_of(region_code: str) -> str:
|
||||
def post_scope(post_type: PostType, region_code: str) -> str:
|
||||
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
|
||||
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
|
||||
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 앞쪽 절반 사이사이 무작위.
|
||||
# 알림은 비·특보가 있을 때만 켜지니 맨 앞, 주말·노을처럼 공유할 만한 카드를 그다음, 공기·자외선·상식 같은 평이한 정보는 뒤로.
|
||||
ORDER = {
|
||||
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
|
||||
"day": [PostType.GAK, PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.MOON, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.GAK, PostType.MOON, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.AIR, PostType.TOMORROW, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SEASON, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.MOON, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.GAK, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.AIR, PostType.SEASON, PostType.TIP, PostType.QUOTE],
|
||||
"morning": [PostType.ALERT, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.SUNSET, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
|
||||
"day": [PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.MOON, PostType.AIR, PostType.UV, PostType.TIP, PostType.QUOTE],
|
||||
"evening": [PostType.SUNSET, PostType.ALERT, PostType.WEEK, PostType.MOON, PostType.WEEKEND_PLAN, PostType.GAK, PostType.TOMORROW, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
|
||||
"night": [PostType.TOMORROW, PostType.ALERT, PostType.MOON, PostType.WEEK, PostType.SUNSET, PostType.WEEKEND_PLAN, PostType.GAK, PostType.DAY_TRIP, PostType.WEEKEND_PLAN, PostType.GAK, PostType.SEASON, PostType.GAK, PostType.AIR, PostType.TIP, PostType.QUOTE],
|
||||
}
|
||||
_SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"}
|
||||
_CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"}
|
||||
@@ -220,7 +221,8 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
|
||||
if slot == "night":
|
||||
rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE]
|
||||
events = pool.get(PostType.EVENT, [])
|
||||
gaps = sorted(random.Random(seed).sample(range(1, len(rest)), min(len(events), max(0, len(rest) - 1))), reverse=True)
|
||||
front = range(1, max(1, len(rest) // 2 + 1))
|
||||
gaps = sorted(random.Random(seed).sample(front, min(len(events), len(front))), reverse=True)
|
||||
for gap, e in zip(gaps, reversed(events[:len(gaps)])):
|
||||
rest.insert(gap, e)
|
||||
return head + rest
|
||||
|
||||
@@ -11,7 +11,6 @@ Tone = Literal["normal", "warn", "rain"]
|
||||
|
||||
UV_HIGH = 6.0
|
||||
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
|
||||
DISCOMFORT_MONTHS = range(6, 10) # 기상청처럼 6~9월에만. 더위 지표라 선선한 철엔 비 와도 '쾌적'으로 나온다
|
||||
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
|
||||
TEMP_SWING_C = 10.0
|
||||
WIND_CHILL_C = 3.0
|
||||
@@ -67,11 +66,11 @@ def humidity_label(h: int) -> str:
|
||||
|
||||
|
||||
def hero_status(x: HeroInput) -> list[HeroStatItem]:
|
||||
"""히어로 상태 한 줄: 습도·불쾌지수(6~9월)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
|
||||
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
|
||||
out: list[HeroStatItem] = []
|
||||
if x.humidity is not None:
|
||||
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
|
||||
if x.discomfort is not None and x.now.month in DISCOMFORT_MONTHS:
|
||||
if x.discomfort is not None:
|
||||
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
|
||||
if not x.after_dark and x.uv is not None:
|
||||
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
|
||||
|
||||
@@ -365,6 +365,36 @@ class IndexService:
|
||||
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
|
||||
)
|
||||
|
||||
async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]:
|
||||
"""공식 각이 아닌 정의(내 각)들을 그 동네 오늘 아침·낮·저녁·밤으로 계산한다. (지금 구간, 정의마다 구간별 결과)"""
|
||||
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.NOT_FOUND, None
|
||||
now = now_kst()
|
||||
_, _, ultra = await asyncio.gather(self.weather_service.ensure_vilage(region, now), self.air_service.ensure(now), ultra_hours(region, now))
|
||||
today = now.date()
|
||||
start = kst_midnight(today)
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region.code, start - timedelta(days=1), start + timedelta(days=2)))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if not rows:
|
||||
return ErrorType.EXTERNAL_API_ERROR, None
|
||||
air = await self.air_service.nearest(region)
|
||||
by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
|
||||
ctx = Context(
|
||||
day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), wind_warning=False,
|
||||
pm25=air.pm25 if air else None, air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
|
||||
)
|
||||
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
|
||||
cur = current_slot(now, sunset_at)
|
||||
out = []
|
||||
for d in defns:
|
||||
parts = slot_results(d, today, region, by_at, {}, ctx, sunset_at, now)
|
||||
out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)})
|
||||
return ErrorType.SUCCESS, (shown_slot(cur), out)
|
||||
|
||||
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
|
||||
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
|
||||
_, _, _, warnings, ultra = await asyncio.gather(
|
||||
|
||||
@@ -1,48 +1,77 @@
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import MyGak, User
|
||||
from common.enums import ErrorType, IndexCategory
|
||||
from crud.index_crud import IndexCRUD
|
||||
from common.enums import ErrorType
|
||||
from crud.my_gak_crud import MyGakCRUD
|
||||
from services.calc.day_slot import SLOTS
|
||||
from services.calc.my_gak_calc import MyRule, axes, definition
|
||||
from services.index_service import IndexService
|
||||
|
||||
# 한 사람이 만들 수 있는 조합 수
|
||||
# 한 사람이 만들 수 있는 내 각 수
|
||||
MAX_PER_USER = 20
|
||||
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b|\d{3,}", re.I)
|
||||
|
||||
|
||||
def gak_name(name: str) -> Optional[str]:
|
||||
"""앞뒤 공백을 빼고 끝에 '각'을 붙인다. 링크·긴 숫자(전화번호 등)는 받지 않는다."""
|
||||
name = " ".join(name.split())
|
||||
if not name or _LINK.search(name):
|
||||
return None
|
||||
name = name if name.endswith("각") else f"{name}각"
|
||||
return name if len(name) <= 12 else None
|
||||
|
||||
|
||||
def my_rule(rule: dict) -> MyRule:
|
||||
return MyRule(
|
||||
temp=tuple(rule["temp"]) if rule.get("temp") else None, rain=rule.get("rain"), wind_max=rule.get("wind_max"), air=rule.get("air"),
|
||||
humidity=tuple(rule["humidity"]) if rule.get("humidity") else None, slots=tuple(s for s in SLOTS if s in (rule.get("slots") or SLOTS)),
|
||||
)
|
||||
|
||||
|
||||
class MyGakService:
|
||||
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexCRUD = Depends(IndexCRUD)) -> None:
|
||||
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexService = Depends(IndexService)) -> None:
|
||||
self.crud, self.index = crud, index
|
||||
|
||||
async def mixable(self) -> tuple[ErrorType, list[int]]:
|
||||
"""섞을 수 있는 공식 각. 생활 고민(우산·교통체증처럼 불편한 날을 알리는 각)은 좋은 날 각과 섞으면 뜻이 뒤집혀 뺀다."""
|
||||
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.definitions(s))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
return ErrorType.SUCCESS, [d.index_id for d in defs if d.category != IndexCategory.LIFE.value]
|
||||
|
||||
async def mine(self, user: User) -> tuple[ErrorType, list[MyGak]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
|
||||
return err, rows or []
|
||||
|
||||
async def add(self, user: User, index_ids: list[int]) -> tuple[ErrorType, Optional[MyGak]]:
|
||||
a, b = sorted(index_ids)
|
||||
err, ok = await self.mixable()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if a == b or a not in ok or b not in ok:
|
||||
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]:
|
||||
name = gak_name(name)
|
||||
if name is None:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count(s, user.user_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if n >= MAX_PER_USER:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, a, b))
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule))
|
||||
|
||||
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
|
||||
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
|
||||
|
||||
async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]:
|
||||
"""조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수."""
|
||||
mine = [my_rule(r) for r in rules]
|
||||
err, got = await self.index.custom(region_code, [definition(r) for r in mine])
|
||||
if err is not ErrorType.SUCCESS or got is None:
|
||||
return err, None
|
||||
now_slot, parts = got
|
||||
out = []
|
||||
for r, p in zip(mine, parts):
|
||||
picked = {k: v for k, v in p.items() if k in r.slots}
|
||||
key = now_slot if now_slot in picked else max(picked, key=lambda k: picked[k].score, default=None)
|
||||
res = picked.get(key) if key else None
|
||||
out.append({
|
||||
"score": res.score if res else None, "slot": key if res else None,
|
||||
"slots": {k: v.score for k, v in picked.items()},
|
||||
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
|
||||
})
|
||||
return ErrorType.SUCCESS, (now_slot, out)
|
||||
@@ -7,6 +7,7 @@ from fastapi import Depends
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Comment, Post, User
|
||||
from common.enums import ErrorType
|
||||
from common.liker import Liker
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.reaction_crud import ReactionCRUD
|
||||
|
||||
@@ -41,11 +42,11 @@ class ReactionService:
|
||||
return err
|
||||
return ErrorType.SUCCESS if post is not None else ErrorType.NOT_FOUND
|
||||
|
||||
async def like_post(self, post_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
async def like_post(self, post_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err = await self._post_exists(post_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, user.user_id, on))
|
||||
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_post_like(s, post_id, who, on))
|
||||
|
||||
async def save_post(self, post_id: int, user: User, on: bool) -> ErrorType:
|
||||
err = await self._post_exists(post_id)
|
||||
@@ -60,6 +61,12 @@ class ReactionService:
|
||||
err, marks = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.my_marks(s, user.user_id, post_ids))
|
||||
return marks if err is ErrorType.SUCCESS else (set(), set())
|
||||
|
||||
async def anon_liked(self, ip_hash: str, post_ids: list[int]) -> set[int]:
|
||||
if not post_ids:
|
||||
return set()
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_posts(s, ip_hash, post_ids))
|
||||
return liked if err is ErrorType.SUCCESS else set()
|
||||
|
||||
async def counts(self, post_ids: list[int]) -> dict[int, tuple[int, int]]:
|
||||
"""피드는 캐시돼 있어서 좋아요·댓글 수는 매번 DB 에서 덮어쓴다."""
|
||||
if not post_ids:
|
||||
@@ -71,13 +78,16 @@ class ReactionService:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.saved_posts(s, user.user_id, cursor, PAGE))
|
||||
return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []]
|
||||
|
||||
async def comments(self, post_id: int, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
ids = [c.comment_id for c, *_ in rows]
|
||||
if user is not None and rows:
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, [c.comment_id for c, *_ in rows]))
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, ids))
|
||||
elif rows:
|
||||
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids))
|
||||
return ErrorType.SUCCESS, [
|
||||
CommentView(comment=c, nickname=n, character=ch, color=co, mood=mo, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id)
|
||||
for c, n, ch, co, mo in rows
|
||||
@@ -99,8 +109,8 @@ class ReactionService:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def like_comment(self, comment_id: int, user: User, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, user.user_id, on))
|
||||
async def like_comment(self, comment_id: int, who: Liker, on: bool) -> tuple[ErrorType, Optional[int]]:
|
||||
err, count = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_comment_like(s, comment_id, who, on))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
||||
@@ -0,0 +1,45 @@
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from config.settings import settings
|
||||
from common.enums import ErrorType
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024 # 올릴 수 있는 원본 크기
|
||||
MAX_SIDE = 1080 # 긴 변을 이만큼으로 줄인다
|
||||
URL_PREFIX = "/v1/talk/image/"
|
||||
_NAME = re.compile(r"^[0-9a-f]{32}\.webp$")
|
||||
|
||||
|
||||
def folder() -> str:
|
||||
path = os.path.join(settings.upload_dir, "talk")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def file_of(url: str) -> Optional[str]:
|
||||
"""올린 사진 주소 → 저장된 파일 경로. 우리가 만든 이름이 아니거나 파일이 없으면 None."""
|
||||
name = url.removeprefix(URL_PREFIX)
|
||||
if not url.startswith(URL_PREFIX) or not _NAME.match(name):
|
||||
return None
|
||||
path = os.path.join(folder(), name)
|
||||
return path if os.path.isfile(path) else None
|
||||
|
||||
|
||||
def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
|
||||
"""사진을 다시 그려 저장한다. 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
|
||||
if len(data) > MAX_BYTES:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as src:
|
||||
img = ImageOps.exif_transpose(src).convert("RGB")
|
||||
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
img.thumbnail((MAX_SIDE, MAX_SIDE))
|
||||
name = f"{uuid.uuid4().hex}.webp"
|
||||
img.save(os.path.join(folder(), name), "WEBP", quality=82)
|
||||
return ErrorType.SUCCESS, URL_PREFIX + name
|
||||
@@ -8,10 +8,12 @@ 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
|
||||
@@ -49,14 +51,18 @@ 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]]:
|
||||
async def page(self, user: Optional[User], ip_hash: str, 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 rows:
|
||||
ids = [t.talk_id for t, *_ in rows]
|
||||
if user is not None:
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
|
||||
else:
|
||||
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
|
||||
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]
|
||||
@@ -69,10 +75,12 @@ 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) -> tuple[ErrorType, Optional[TalkView]]:
|
||||
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))
|
||||
@@ -87,7 +95,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))
|
||||
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)
|
||||
@@ -104,11 +112,11 @@ class TalkService:
|
||||
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]]:
|
||||
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, user.user_id, on))
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user