173 lines
6.9 KiB
Python
173 lines
6.9 KiB
Python
import hashlib
|
|
import hmac
|
|
import time
|
|
import uuid
|
|
from dataclasses import dataclass
|
|
from datetime import date, 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 User
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from common.utils.kma_time import now_kst
|
|
from config.settings import settings
|
|
from crud.level_crud import LevelCRUD
|
|
|
|
# 계정 레벨: 모은 각 총량으로 정한다 (쓰는 기능이 생겨도 레벨은 안 내려간다). 사용자 결정 10/28
|
|
LEVELS: list[tuple[int, str]] = [(0, "이슬"), (30, "햇살"), (100, "산들바람"), (200, "무지개"), (400, "노을"), (700, "은하수"), (1000, "별똥별")]
|
|
|
|
# 각을 주는 일: (한 번에 주는 각, 하루 한도, 이름). 로그인한 사람만 쌓인다
|
|
ACTIONS: dict[str, tuple[int, int, str]] = {
|
|
"attend": (10, 10, "출석"),
|
|
"tarot": (10, 10, "오늘 타로 뽑기"),
|
|
"saju": (10, 10, "날씨 사주 보기"),
|
|
"react": (5, 10, "좋아요·댓글"),
|
|
"talk": (20, 20, "동네 이야기 글쓰기"),
|
|
"checkin": (10, 10, "저녁 체크인"),
|
|
"share": (10, 10, "공유하기"),
|
|
"game": (2, 20, "날씨게임 라운드 깨기"),
|
|
"streak": (50, 50, "7일 연속 출석"),
|
|
}
|
|
STREAK_DAYS = 7
|
|
# 날씨게임 점수는 폰에서 계산해 조작될 수 있다. 하루 한도로 막고, 판 시작부터 라운드당 이만큼은 지나야 받는다
|
|
GAME_ROUND_MIN_SEC = 15
|
|
GAME_MAX_SEC = 3 * 60 * 60
|
|
GAME_MAX_ROUND = 100
|
|
STREAK_LOOKBACK = 60
|
|
|
|
# 레벨로 열리는 것: 새로 생기는 것만 잠근다 (지금 있는 기능·캐릭터·색·기분은 그대로)
|
|
UNLOCKS: dict[int, list[tuple[str, str]]] = {
|
|
2: [("saju_week", "날씨 사주 7일 흐름")],
|
|
3: [("saju_money", "금전운 · 일운")],
|
|
4: [("saju_love", "연애운")],
|
|
5: [("saju_match", "궁합")],
|
|
6: [("saju_month", "이달 운")],
|
|
7: [("saju_year", "올해 운")],
|
|
}
|
|
|
|
|
|
def level_of(points: int) -> int:
|
|
return max(i + 1 for i, (need, _) in enumerate(LEVELS) if points >= need)
|
|
|
|
|
|
def unlock_level(key: str) -> int:
|
|
return next((lv for lv, items in UNLOCKS.items() if any(k == key for k, _ in items)), 1)
|
|
|
|
|
|
def is_unlocked(points: int, key: str) -> bool:
|
|
return level_of(points) >= unlock_level(key)
|
|
|
|
|
|
def game_token(user_id: uuid.UUID, ts: int) -> str:
|
|
"""판 시작 표: 시작 시각과 서명. 그 사람만 쓸 수 있다"""
|
|
sig = hmac.new(settings.jwt_access_secret.encode(), f"game:{user_id}:{ts}".encode(), hashlib.sha256).hexdigest()[:16]
|
|
return f"{ts}.{sig}"
|
|
|
|
|
|
def game_round_ok(user_id: uuid.UUID, play: str, round_no: int, now: int) -> bool:
|
|
ts, _, _ = play.partition(".")
|
|
if not ts.isdigit() or not hmac.compare_digest(game_token(user_id, int(ts)), play):
|
|
return False
|
|
elapsed = now - int(ts)
|
|
return 1 <= round_no <= GAME_MAX_ROUND and round_no * GAME_ROUND_MIN_SEC <= elapsed <= GAME_MAX_SEC
|
|
|
|
|
|
def streak(days: set[date], today: date) -> int:
|
|
"""오늘부터 거꾸로 이어 출석한 날 수"""
|
|
n = 0
|
|
while today - timedelta(days=n) in days:
|
|
n += 1
|
|
return n
|
|
|
|
|
|
async def award(user_id: uuid.UUID, action: str, ref: str = "") -> int:
|
|
"""각을 준다. 하루 한도·같은 대상 중복이면 주지 않는다. 본래 동작을 막지 않게 실패는 로그만 남긴다. 새 총량(안 줬으면 0)"""
|
|
per, cap, _ = ACTIONS[action]
|
|
day = now_kst().date()
|
|
crud = LevelCRUD()
|
|
err, earned = await DB_SESSION_MNG.execute_lambda(lambda s: crud.earned(s, user_id, day, action))
|
|
if err is not ErrorType.SUCCESS:
|
|
LOG.error(f"[level] 각 조회 실패 {action}")
|
|
return 0
|
|
if earned >= cap:
|
|
return 0
|
|
points = min(per, cap - earned)
|
|
err, total = await DB_SESSION_MNG.execute_lambda_write(lambda s: crud.add(s, user_id, day, action, ref, points))
|
|
if err is not ErrorType.SUCCESS:
|
|
LOG.error(f"[level] 각 적립 실패 {action}")
|
|
return 0
|
|
if action == "attend" and total:
|
|
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: crud.attend_days(s, user_id, day - timedelta(days=STREAK_LOOKBACK)))
|
|
n = streak(set(days or []), day) if err is ErrorType.SUCCESS else 0
|
|
if n and n % STREAK_DAYS == 0:
|
|
more = await award(user_id, "streak", str(n))
|
|
total = more or total
|
|
return total or 0
|
|
|
|
|
|
@dataclass
|
|
class TodayAction:
|
|
action: str
|
|
name: str
|
|
points: int # 한 번에 주는 각
|
|
cap: int
|
|
earned: int
|
|
|
|
|
|
@dataclass
|
|
class Status:
|
|
points: int
|
|
level: int
|
|
name: str
|
|
floor: int # 지금 레벨이 시작하는 각
|
|
next_points: Optional[int] # 다음 레벨까지 필요한 총량 (마지막 레벨이면 없음)
|
|
next_name: Optional[str]
|
|
streak: int
|
|
today: list[TodayAction]
|
|
unlocks: list[tuple[int, str, str]] # (레벨, 키, 이름)
|
|
|
|
|
|
class LevelService:
|
|
def __init__(self, crud: LevelCRUD = Depends(LevelCRUD)) -> None:
|
|
self.crud = crud
|
|
|
|
async def status(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
|
day = now_kst().date()
|
|
err, points = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.points(s, user.user_id))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
err, today = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.today(s, user.user_id, day))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
err, days = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.attend_days(s, user.user_id, day - timedelta(days=STREAK_LOOKBACK)))
|
|
if err is not ErrorType.SUCCESS:
|
|
return err, None
|
|
lv = level_of(points)
|
|
floor, name = LEVELS[lv - 1]
|
|
nxt = LEVELS[lv] if lv < len(LEVELS) else None
|
|
return ErrorType.SUCCESS, Status(
|
|
points=points, level=lv, name=name, floor=floor, next_points=nxt[0] if nxt else None, next_name=nxt[1] if nxt else None,
|
|
streak=streak(set(days), day),
|
|
today=[TodayAction(action=a, name=n, points=p, cap=c, earned=(today or {}).get(a, 0)) for a, (p, c, n) in ACTIONS.items() if a != "streak"],
|
|
unlocks=[(lv_, k, n) for lv_, items in UNLOCKS.items() for k, n in items],
|
|
)
|
|
|
|
async def attend(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
|
await award(user.user_id, "attend")
|
|
return await self.status(user)
|
|
|
|
async def share(self, user: User) -> tuple[ErrorType, Optional[Status]]:
|
|
await award(user.user_id, "share")
|
|
return await self.status(user)
|
|
|
|
def game_start(self, user: User) -> str:
|
|
return game_token(user.user_id, int(time.time()))
|
|
|
|
async def game_round(self, user: User, play: str, round_no: int) -> tuple[ErrorType, Optional[Status]]:
|
|
if game_round_ok(user.user_id, play, round_no, int(time.time())):
|
|
await award(user.user_id, "game", f"{play}:{round_no}")
|
|
return await self.status(user)
|