upload to gitea
This commit is contained in:
commit
e50b59d88a
59 files changed
+4308
No files matched your search
@@ -0,0 +1,92 @@
|
||||
import secrets
|
||||
import sqlite3
|
||||
from datetime import date, timedelta
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from . import clock, config
|
||||
from .db import get_db
|
||||
from .deps import current_user
|
||||
from .i18n import t
|
||||
from .titles import fmt_uid
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
MEME_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
|
||||
|
||||
|
||||
def list_memes() -> list[str]:
|
||||
if not config.MEME_DIR.is_dir():
|
||||
return []
|
||||
return sorted(
|
||||
p.name for p in config.MEME_DIR.iterdir()
|
||||
if p.is_file() and p.suffix.lower() in MEME_EXTS and not p.name.startswith(".")
|
||||
)
|
||||
|
||||
|
||||
def pick_meme() -> str | None:
|
||||
memes = list_memes()
|
||||
return secrets.choice(memes) if memes else None
|
||||
|
||||
|
||||
def stats(conn: sqlite3.Connection, uid: int, upto: str | None = None, *, live: bool = False) -> tuple[int, int]:
|
||||
"""回傳 (累計天數, 連續天數),只算 upto(含)以前的簽到。
|
||||
|
||||
live=True 用在個人資料:今天還沒簽到時,昨天以前的連續紀錄仍然算數。
|
||||
"""
|
||||
upto = upto or clock.today()
|
||||
days = [r[0] for r in conn.execute(
|
||||
"SELECT day FROM checkins WHERE uid = ? AND day <= ? ORDER BY day DESC", (uid, upto))]
|
||||
expected = date.fromisoformat(upto)
|
||||
if live and days and days[0] != upto:
|
||||
expected -= timedelta(days=1)
|
||||
streak = 0
|
||||
for d in days:
|
||||
if d != expected.isoformat():
|
||||
break
|
||||
streak += 1
|
||||
expected -= timedelta(days=1)
|
||||
return len(days), streak
|
||||
|
||||
|
||||
def card_urls(uid: int, day: str) -> dict:
|
||||
return {
|
||||
"card_url": f"/card/{fmt_uid(uid)}/{day}.png",
|
||||
"share_url": f"{config.PUBLIC_URL}/c/{fmt_uid(uid)}/{day}",
|
||||
}
|
||||
|
||||
|
||||
def today_payload(conn: sqlite3.Connection, user: sqlite3.Row, day: str, already: bool | None = None) -> dict:
|
||||
checked = conn.execute(
|
||||
"SELECT 1 FROM checkins WHERE uid = ? AND day = ?", (user["uid"], day)).fetchone() is not None
|
||||
total, streak = stats(conn, user["uid"], day, live=True)
|
||||
out = {
|
||||
"day": day,
|
||||
"checked_in": checked,
|
||||
"total_days": total,
|
||||
"streak": streak,
|
||||
"next_reset": clock.next_reset().isoformat(),
|
||||
}
|
||||
if already is not None:
|
||||
out["already"] = already
|
||||
if checked:
|
||||
out.update(card_urls(user["uid"], day))
|
||||
out["share_text"] = t(user["lang"], "share.text", n=total)
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/api/checkin")
|
||||
def do_checkin(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
|
||||
day = clock.today() # 只取一次,避免剛好跨過 00:00 時前後不一致
|
||||
# PRIMARY KEY(uid, day) 擋重複簽到:同時送出兩次也只會寫入一筆
|
||||
cur = conn.execute(
|
||||
"INSERT INTO checkins(uid, day, meme, created_at) VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(uid, day) DO NOTHING",
|
||||
(user["uid"], day, pick_meme(), clock.ts()),
|
||||
)
|
||||
return today_payload(conn, user, day, already=cur.rowcount == 0)
|
||||
|
||||
|
||||
@router.get("/api/checkin/today")
|
||||
def get_today(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
|
||||
return today_payload(conn, user, clock.today())
|
||||
Reference in new issue
Block a user