upload to gitea

This commit is contained in:
Sahik committed 2026-11-22 01:04:28 +08:00
commit e50b59d88a
59 files changed
+4308

No files matched your search

View File
Whitespace-only changes.
+131
View File
@@ -0,0 +1,131 @@
"""管理指令(在容器裡執行):
docker compose exec app python -m app.admin info <email>
docker compose exec app python -m app.admin grant-uid <email> 114514
docker compose exec app python -m app.admin test-mail <email>
docker compose exec app python -m app.admin unlock # 解除管理員登入鎖定
docker compose exec app python -m app.admin totp-uri # 印出 Aegis 用的 otpauth:// 連結
docker compose exec app python -m app.admin reset-progress --yes # 正式上線前清空簽到進度
"""
import argparse
import os
import shutil
import sqlite3
import sys
from datetime import datetime
from . import card, config, db, totp
from .titles import fmt_uid
def cmd_info(args):
conn = db.connect()
row = conn.execute("SELECT * FROM users WHERE email = ?", (args.email.strip().lower(),)).fetchone()
if row is None:
sys.exit("找不到這個信箱")
days = conn.execute("SELECT COUNT(*) FROM checkins WHERE uid = ?", (row["uid"],)).fetchone()[0]
print(f"uid={fmt_uid(row['uid'])} name={row['display_name']} lang={row['lang']} checkins={days}")
next_uid = conn.execute("SELECT value FROM meta WHERE key = 'next_uid'").fetchone()[0]
print(f"next_uid={next_uid}")
def cmd_grant_uid(args):
"""把某個帳號的 UID 換成指定號碼(1–99999999,例如 114514)。不會影響之後的依序給號。"""
conn = db.connect()
email = args.email.strip().lower()
new_uid = args.uid
if not 1 <= new_uid <= config.UID_MAX:
sys.exit(f"UID 要在 1–{config.UID_MAX} 之間(0 是管理員)")
with db.transaction(conn):
row = conn.execute("SELECT uid FROM users WHERE email = ?", (email,)).fetchone()
if row is None:
sys.exit("找不到這個信箱")
if conn.execute("SELECT 1 FROM users WHERE uid = ?", (new_uid,)).fetchone():
sys.exit(f"UID {new_uid} 已經有人使用")
old_uid = row["uid"]
if old_uid == config.ADMIN_UID:
sys.exit("不能改管理員的 UID")
# sessions、checkins 是 ON UPDATE CASCADE,會一起改
conn.execute("UPDATE users SET uid = ? WHERE uid = ?", (new_uid, old_uid))
old_av = config.DATA_DIR / "avatars" / f"{old_uid}.webp"
if old_av.exists():
os.replace(old_av, config.DATA_DIR / "avatars" / f"{new_uid}.webp")
card.invalidate(old_uid)
print(f"{email}: UID {fmt_uid(old_uid)} -> {fmt_uid(new_uid)}")
def cmd_test_mail(args):
"""實際寄一封測試信,失敗時印出 SMTP 的錯誤訊息。"""
from . import mailer
print(f"SMTP {config.SMTP_HOST}:{config.SMTP_PORT} user={config.SMTP_USER or '(empty)'} "
f"password={'(set)' if config.SMTP_PASSWORD else '(empty)'} from={config.MAIL_FROM}")
if not config.SMTP_USER or not config.SMTP_PASSWORD:
sys.exit("SMTP_USER / SMTP_PASSWORD 沒有設定,不會寄信。改好 .env 後執行 docker compose up -d")
try:
mailer.send_code(args.email, "123456", args.lang)
except Exception as e:
sys.exit(f"寄送失敗:{type(e).__name__}: {e}")
print(f"SMTP 伺服器已收下,寄到 {args.email}(驗證碼 123456 只是測試用)")
def cmd_unlock(args):
conn = db.connect()
for key in ("admin_fails", "admin_lock_level", "admin_lock_until"):
db.set_meta(conn, key, 0)
print("管理員登入已解除鎖定")
def cmd_totp_uri(args):
if not config.ADMIN_LOGIN or not config.ADMIN_TOTP:
sys.exit("ADMIN_LOGIN / ADMIN_TOTP 沒有設定")
print(totp.uri(config.ADMIN_TOTP, config.ADMIN_LOGIN))
def cmd_reset_progress(args):
"""清空所有簽到紀錄與小卡(Beta 結束、正式上線時用)。帳號、UID、名稱、大頭貼、自介都保留。"""
conn = db.connect()
checkins = conn.execute("SELECT COUNT(*) FROM checkins").fetchone()[0]
users = conn.execute("SELECT COUNT(DISTINCT uid) FROM checkins").fetchone()[0]
print(f"會刪除 {checkins} 筆簽到紀錄({users} 個帳號)與所有小卡;帳號、UID、名稱、大頭貼、自介保留")
if not args.yes:
print("沒有做任何變更。確定要執行請加上 --yes")
return
backup = config.DATA_DIR / f"inmu.db.bak-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
dst = sqlite3.connect(backup)
conn.backup(dst)
dst.close()
conn.execute("DELETE FROM checkins")
shutil.rmtree(config.DATA_DIR / "cards", ignore_errors=True)
(config.DATA_DIR / "cards").mkdir(exist_ok=True)
print(f"完成。備份在 {backup}")
def main(argv=None):
p = argparse.ArgumentParser(prog="python -m app.admin")
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("info", help="查看帳號")
s.add_argument("email")
s.set_defaults(func=cmd_info)
s = sub.add_parser("grant-uid", help="指定 UID")
s.add_argument("email")
s.add_argument("uid", type=int)
s.set_defaults(func=cmd_grant_uid)
s = sub.add_parser("test-mail", help="寄一封測試信")
s.add_argument("email")
s.add_argument("--lang", default=config.DEFAULT_LANG)
s.set_defaults(func=cmd_test_mail)
s = sub.add_parser("unlock", help="解除管理員登入鎖定")
s.set_defaults(func=cmd_unlock)
s = sub.add_parser("totp-uri", help="印出 Aegis 用的 otpauth:// 連結")
s.set_defaults(func=cmd_totp_uri)
s = sub.add_parser("reset-progress", help="清空所有簽到進度(保留帳號)")
s.add_argument("--yes", action="store_true", help="確定執行")
s.set_defaults(func=cmd_reset_progress)
args = p.parse_args(argv)
db.init()
args.func(args)
if __name__ == "__main__":
main()
+192
View File
@@ -0,0 +1,192 @@
"""信箱驗證碼登入(沒有密碼):第一次驗證成功就自動建立帳號。
管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 Aegis 算的 TOTP(不寄信)。錯 3 次就全域鎖定,時間逐次加倍。
"""
import re
import secrets
import sqlite3
import threading
import time
from collections import defaultdict, deque
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel
from . import clock, config, db, mailer, totp
from .db import get_db, get_meta, set_meta, transaction
from .deps import client_ip, current_user, fail, session_token, sha256
from .i18n import norm_lang
from .users import create_user, profile
router = APIRouter()
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
# 同一 IP 的寄信次數(單一 worker,放記憶體就夠)
_ip_hits: dict[str, deque] = defaultdict(deque)
_ip_lock = threading.Lock()
def ip_allowed(ip: str) -> bool:
now = time.monotonic()
with _ip_lock:
q = _ip_hits[ip]
while q and q[0] < now - config.IP_WINDOW:
q.popleft()
if len(q) >= config.IP_LIMIT:
return False
q.append(now)
return True
def is_admin_login(raw: str) -> bool:
return db.admin_ok and raw.strip().lower() == config.ADMIN_LOGIN.lower()
def norm_email(email: str) -> str:
email = email.strip().lower()
if len(email) > 254 or not EMAIL_RE.match(email):
fail(400, "invalid_email")
return email
class CodeRequest(BaseModel):
email: str
lang: str = config.DEFAULT_LANG
class VerifyRequest(BaseModel):
email: str
code: str
lang: str = config.DEFAULT_LANG
@router.post("/api/auth/request-code")
def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection = Depends(get_db)):
sent = {"status": "sent", "expires_in": config.CODE_TTL, "resend_in": config.CODE_RESEND}
if is_admin_login(body.email):
# 管理員不寄信,驗證碼看 Aegis。回應和一般信箱完全相同
if not ip_allowed(client_ip(request)):
fail(429, "too_many_requests")
return sent
email = norm_email(body.email)
now = clock.ts()
conn.execute("DELETE FROM login_codes WHERE expires_at < ?", (now,))
old = conn.execute("SELECT last_sent_at FROM login_codes WHERE email = ?", (email,)).fetchone()
if old and now - old["last_sent_at"] < config.CODE_RESEND:
fail(429, "too_many_requests")
if not ip_allowed(client_ip(request)):
fail(429, "too_many_requests")
# secrets 才是密碼學安全的亂數
code = f"{secrets.randbelow(10**6):06d}"
conn.execute(
"INSERT INTO login_codes(email, code_hash, attempts, expires_at, last_sent_at) VALUES (?, ?, 0, ?, ?) "
"ON CONFLICT(email) DO UPDATE SET code_hash = excluded.code_hash, attempts = 0, "
"expires_at = excluded.expires_at, last_sent_at = excluded.last_sent_at",
(email, sha256(code), now + config.CODE_TTL, now),
)
try:
mailer.send_code(email, code, norm_lang(body.lang))
except Exception as e:
print("Error sending email:", e, flush=True)
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(502, "send_failed")
return sent
def admin_check(conn: sqlite3.Connection, code: str, ip: str) -> str | None:
"""比對管理員 TOTP。成功回傳 None,失敗回傳錯誤代碼。
計數寫在交易裡,同時送出多個請求也不會多猜幾次。"""
now = clock.ts()
with transaction(conn):
if now < get_meta(conn, "admin_lock_until"):
return "too_many_requests"
step = totp.verify(config.ADMIN_TOTP, code, now)
if step is not None and step <= get_meta(conn, "admin_last_step"):
# 碼是對的但用過了(例如登出後馬上用同一組再登入):拒絕,但不算猜錯、不計入鎖定。
# 拿得到正確的碼才會發生,不是暴力猜碼
return "code_used"
if step is not None:
set_meta(conn, "admin_fails", 0)
set_meta(conn, "admin_lock_level", 0)
set_meta(conn, "admin_last_step", step)
print(f"[ADMIN] login from {ip}", flush=True)
return None
fails = get_meta(conn, "admin_fails") + 1
print(f"[ADMIN] login failed from {ip} ({fails}/{config.ADMIN_MAX_FAILS})", flush=True)
if fails < config.ADMIN_MAX_FAILS:
set_meta(conn, "admin_fails", fails)
return "wrong_code"
level = get_meta(conn, "admin_lock_level")
lock = min(config.ADMIN_LOCK_BASE * 2 ** level, config.ADMIN_LOCK_MAX)
set_meta(conn, "admin_fails", 0)
set_meta(conn, "admin_lock_level", level + 1)
set_meta(conn, "admin_lock_until", now + lock)
print(f"[ADMIN] locked for {lock // 60} min", flush=True)
return "too_many_requests"
def issue_session(conn: sqlite3.Connection, response: Response, user: sqlite3.Row) -> dict:
now = clock.ts()
ttl = config.ADMIN_SESSION_TTL if user["uid"] == config.ADMIN_UID else config.SESSION_TTL
token = secrets.token_urlsafe(32)
conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
conn.execute(
"INSERT INTO sessions(token_hash, uid, created_at, expires_at) VALUES (?, ?, ?, ?)",
(sha256(token), user["uid"], now, now + ttl),
)
response.set_cookie(
config.COOKIE_NAME, token, max_age=ttl,
httponly=True, secure=config.COOKIE_SECURE, samesite="lax", path="/",
)
# token 也放在 JSON,之後 Android 用 Authorization: Bearer <token>
return {"token": token, "user": profile(conn, user, user["lang"], private=True)}
@router.post("/api/auth/verify")
def verify(body: VerifyRequest, request: Request, response: Response,
conn: sqlite3.Connection = Depends(get_db)):
if is_admin_login(body.email):
err = admin_check(conn, body.code.strip(), client_ip(request))
if err:
fail(429 if err == "too_many_requests" else 400, err)
admin = conn.execute("SELECT * FROM users WHERE uid = ?", (config.ADMIN_UID,)).fetchone()
return issue_session(conn, response, admin)
email = norm_email(body.email)
code = body.code.strip()
now = clock.ts()
row = conn.execute("SELECT * FROM login_codes WHERE email = ?", (email,)).fetchone()
if row is None:
fail(400, "not_requested")
if row["expires_at"] < now:
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(400, "expired")
# 錯太多次直接作廢,防止暴力猜碼
if not secrets.compare_digest(sha256(code), row["code_hash"]):
attempts = row["attempts"] + 1
if attempts >= config.CODE_MAX_ATTEMPTS:
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(400, "expired")
conn.execute("UPDATE login_codes SET attempts = ? WHERE email = ?", (attempts, email))
fail(400, "wrong_code")
# 驗證碼只能用一次
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
user = create_user(conn, email, body.lang)
return issue_session(conn, response, user)
@router.post("/api/auth/logout")
def logout(request: Request, response: Response, user=Depends(current_user),
conn: sqlite3.Connection = Depends(get_db)):
token = session_token(request)
if token:
conn.execute("DELETE FROM sessions WHERE token_hash = ?", (sha256(token),))
response.delete_cookie(config.COOKIE_NAME, path="/")
return {"status": "ok"}
+199
View File
@@ -0,0 +1,199 @@
"""用 Pillow 畫 INMU 小卡(1080×1350 PNG),第一次被請求時才畫,之後快取在 /data/cards/<uid>/<day>.png。"""
import os
import re
import shutil
import sqlite3
import tempfile
from functools import lru_cache
from pathlib import Path
from urllib.parse import urlparse
from fastapi import APIRouter, Depends
from fastapi.responses import FileResponse
from PIL import Image, ImageDraw, ImageFont, ImageOps
from . import config
from .checkin import stats
from .db import get_db
from .deps import fail
from .i18n import norm_lang, t
from .titles import TIER_COLORS, fmt_uid, uid_tier
Image.MAX_IMAGE_PIXELS = 40_000_000 # 擋解壓縮炸彈
router = APIRouter()
W, H = 1080, 1350
PAD = 48
ACCENT = (240, 164, 58)
TEXT = (245, 243, 250)
MUTED = (185, 179, 201)
CARD_VERSION = 3 # 版面改了就加 1,舊的快取自動作廢
DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
# Debian 套件 fonts-noto-cjk;同一個 .ttc 裡依序是 JP、KR、SC、TC、HK
NOTO_DIR = Path("/usr/share/fonts/opentype/noto")
NOTO_INDEX = {"ja": 0, "ko": 1, "zh-CN": 2, "zh-TW": 3, "en": 0}
# 本機(Windows)開發用的備援字型
WIN_FONTS = {
"zh-TW": ["msjh.ttc", "NotoSansTC-VF.ttf"],
"zh-CN": ["msyh.ttc", "NotoSansSC-VF.ttf", "msjh.ttc"],
"ja": ["YuGothB.ttc", "YuGothR.ttc", "meiryo.ttc"],
"ko": ["malgunbd.ttf", "malgun.ttf"],
"en": ["YuGothB.ttc", "msjh.ttc", "NotoSansTC-VF.ttf"],
}
def _font_candidates(lang: str, bold: bool):
env = config.FONT_BOLD if bold else config.FONT_REGULAR
if env:
yield env, 0
yield str(NOTO_DIR / ("NotoSansCJK-Bold.ttc" if bold else "NotoSansCJK-Regular.ttc")), NOTO_INDEX[lang]
for name in WIN_FONTS[lang]:
yield os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts", name), 0
@lru_cache(maxsize=64)
def font(lang: str, size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
for path, index in _font_candidates(lang, bold):
if os.path.exists(path):
try:
return ImageFont.truetype(path, size, index=index)
except OSError:
continue
return ImageFont.load_default(size)
def fit_text(draw: ImageDraw.ImageDraw, text: str, fnt, max_w: int) -> str:
if draw.textlength(text, font=fnt) <= max_w:
return text
while text and draw.textlength(text + "…", font=fnt) > max_w:
text = text[:-1]
return text + "…"
def rounded_mask(size, radius) -> Image.Image:
mask = Image.new("L", size, 0)
ImageDraw.Draw(mask).rounded_rectangle((0, 0, size[0] - 1, size[1] - 1), radius, fill=255)
return mask
def load_image(path: Path) -> Image.Image | None:
try:
with Image.open(path) as im:
im.seek(0) # gif 只取第一幀
im = ImageOps.exif_transpose(im)
return im.convert("RGB")
except Exception:
return None
def render(user: sqlite3.Row, day: str, meme: str | None, total: int, streak: int) -> Image.Image:
lang = norm_lang(user["lang"])
uid = user["uid"]
# 背景:上下漸層
img = Image.new("RGB", (W, H))
top, bottom = (38, 33, 48), (16, 14, 21)
d = ImageDraw.Draw(img)
for y in range(H):
k = y / (H - 1)
d.line([(0, y), (W, y)], fill=tuple(int(a + (b - a) * k) for a, b in zip(top, bottom)))
# 梗圖
box_w, box_h = W - 2 * PAD, 760
panel = Image.new("RGB", (box_w, box_h), (10, 10, 13))
pic = load_image(config.MEME_DIR / meme) if meme else None
if pic:
pic = ImageOps.contain(pic, (box_w, box_h), Image.LANCZOS)
panel.paste(pic, ((box_w - pic.width) // 2, (box_h - pic.height) // 2))
else:
pd = ImageDraw.Draw(panel)
f = font(lang, 48)
msg = t(lang, "card.no_meme")
pd.text((box_w / 2, box_h / 2), msg, font=f, fill=MUTED, anchor="mm")
img.paste(panel, (PAD, PAD), rounded_mask(panel.size, 28))
# 大頭貼
av_size, av_y = 168, PAD + box_h + 40
avatar = None
if user["avatar_ver"]:
avatar = load_image(config.DATA_DIR / "avatars" / f"{uid}.webp")
if avatar:
avatar = avatar.resize((av_size, av_size), Image.LANCZOS)
else:
avatar = Image.new("RGB", (av_size, av_size), ACCENT)
ad = ImageDraw.Draw(avatar)
initial = (user["display_name"] or "?")[0]
ad.text((av_size / 2, av_size / 2), initial, font=font(lang, 84, True), fill=(30, 26, 36), anchor="mm")
circle = Image.new("L", (av_size, av_size), 0)
ImageDraw.Draw(circle).ellipse((0, 0, av_size - 1, av_size - 1), fill=255)
img.paste(avatar, (PAD, av_y), circle)
# 名稱、UID(特殊序號用背景色標示)
tx = PAD + av_size + 32
max_w = W - PAD - tx
f_name = font(lang, 54, True)
d.text((tx, av_y + 14), fit_text(d, user["display_name"], f_name, max_w), font=f_name, fill=TEXT)
uid_text = f"UID {fmt_uid(uid)}"
tier = uid_tier(uid)
uid_y = av_y + 120 # UID 這一行的垂直中心
if tier:
bg, fg = TIER_COLORS[tier]
f_uid = font("en", 36, True)
tw = d.textlength(uid_text, font=f_uid)
d.rounded_rectangle((tx, uid_y - 28, tx + tw + 36, uid_y + 28), 14, fill=bg)
d.text((tx + 18, uid_y), uid_text, font=f_uid, fill=fg, anchor="lm")
else:
d.text((tx, uid_y), uid_text, font=font("en", 36), fill=MUTED, anchor="lm")
# 天數
line_y = av_y + av_size + 36
d.line([(PAD, line_y), (W - PAD, line_y)], fill=(70, 64, 84), width=2)
f_day = font(lang, 92, True)
d.text((PAD, line_y + 24), fit_text(d, t(lang, "card.day", n=total), f_day, W - 2 * PAD),
font=f_day, fill=TEXT)
sub = f"{t(lang, 'card.streak', n=streak)} · {day}"
d.text((PAD, line_y + 148), sub, font=font(lang, 36), fill=MUTED)
host = urlparse(config.PUBLIC_URL).netloc or config.PUBLIC_URL
footer = f"{host} · Beta" if config.BETA else host
d.text((W - PAD, H - PAD), footer, font=font("en", 30, True), fill=ACCENT, anchor="rs")
return img
def card_dir(uid: int) -> Path:
return config.DATA_DIR / "cards" / str(uid)
def invalidate(uid: int) -> None:
"""名稱、大頭貼、語言改了之後,舊的小卡重畫。"""
shutil.rmtree(card_dir(uid), ignore_errors=True)
def card_path(conn: sqlite3.Connection, uid: int, day: str) -> Path | None:
row = conn.execute("SELECT meme FROM checkins WHERE uid = ? AND day = ?", (uid, day)).fetchone()
if row is None:
return None
path = card_dir(uid) / f"{day}.v{CARD_VERSION}.png"
if path.exists():
return path
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
total, streak = stats(conn, uid, day)
img = render(user, day, row["meme"], total, streak)
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
with os.fdopen(fd, "wb") as f:
img.save(f, "PNG", optimize=True)
os.replace(tmp, path)
return path
@router.get("/card/{uid}/{day}.png")
def get_card(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
if not DAY_RE.match(day):
fail(404, "not_found")
path = card_path(conn, uid, day)
if path is None:
fail(404, "not_found")
return FileResponse(path, media_type="image/png", headers={"Cache-Control": "public, max-age=600"})
+92
View File
@@ -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())
+27
View File
@@ -0,0 +1,27 @@
"""時間集中在這裡,測試只要 monkeypatch `clock.now` 就能模擬換日。"""
from datetime import datetime, timedelta, timezone
from . import config
def now() -> datetime:
return datetime.now(timezone.utc)
def ts() -> int:
return int(now().timestamp())
def today() -> str:
"""簽到日:台灣時間 04:00 換日,格式 YYYY-MM-DD。"""
local = now().astimezone(config.TZ) - timedelta(hours=config.DAY_START_HOUR)
return local.date().isoformat()
def next_reset() -> datetime:
"""下一個台灣時間 04:00(帶時區,前端換算成裝置時間)。"""
local = now().astimezone(config.TZ)
reset = local.replace(hour=config.DAY_START_HOUR, minute=0, second=0, microsecond=0)
if local >= reset:
reset += timedelta(days=1)
return reset
+76
View File
@@ -0,0 +1,76 @@
"""環境變數設定。其他模組一律用 `config.X` 取值(測試會直接改這裡的屬性)。"""
import os
from pathlib import Path
from zoneinfo import ZoneInfo
# 每日簽到的分界:台灣時間 04:00(程式一律明確用這個時區,不依賴容器的 TZ)
TZ = ZoneInfo("Asia/Taipei")
DAY_START_HOUR = 4
LANGS = ("zh-TW", "zh-CN", "ja", "ko", "en")
DEFAULT_LANG = "zh-TW"
_HERE = Path(__file__).resolve().parent
def _default_web_dir() -> Path:
# Docker 裡是 /app/web;本機開發是 <repo>/web
for p in (_HERE.parent / "web", _HERE.parent.parent / "web"):
if p.is_dir():
return p
return _HERE.parent / "web"
def _default_meme_dir() -> Path:
return _HERE.parent.parent / "image"
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
MEME_DIR = Path(os.environ.get("MEME_DIR") or _default_meme_dir())
WEB_DIR = Path(os.environ.get("WEB_DIR") or _default_web_dir())
PUBLIC_URL = os.environ.get("PUBLIC_URL", "http://127.0.0.1:2040").rstrip("/")
COOKIE_SECURE = os.environ.get("COOKIE_SECURE", "0") == "1"
# Beta 期間:網頁標題加 (Beta)、小卡右下角加 · Beta。正式上線設 BETA=0
BETA = os.environ.get("BETA", "1") == "1"
# 寄信用的 SMTP。預設 Gmail(帳號 + 應用程式密碼);換成其他寄信服務只要改這幾個值
SMTP_HOST = os.environ.get("SMTP_HOST") or "smtp.gmail.com"
SMTP_PORT = int(os.environ.get("SMTP_PORT") or 465) # 465 = SSL;587 = STARTTLS
SMTP_USER = os.environ.get("SMTP_USER", "")
SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD", "")
MAIL_FROM = os.environ.get("MAIL_FROM") or "[email protected]"
# 小卡字型;沒設定時依序找 Noto Sans CJK(Docker)→ Windows 內建字型 → Pillow 預設字型
FONT_REGULAR = os.environ.get("FONT_REGULAR", "")
FONT_BOLD = os.environ.get("FONT_BOLD", "")
CODE_TTL = 5 * 60 # 驗證碼有效 5 分鐘
CODE_RESEND = 60 # 同一信箱 60 秒內不能重寄
CODE_MAX_ATTEMPTS = 5 # 錯 5 次作廢
IP_LIMIT = 10 # 同一 IP 10 分鐘最多寄 10 次
IP_WINDOW = 10 * 60
SESSION_TTL = 90 * 24 * 3600
ADMIN_SESSION_TTL = 7 * 24 * 3600
# 管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 ADMIN_TOTP(base32 密鑰)算出的 TOTP。兩個都設定才啟用
ADMIN_LOGIN = os.environ.get("ADMIN_LOGIN", "").strip()
ADMIN_TOTP = os.environ.get("ADMIN_TOTP", "").strip()
ADMIN_UID = 0
ADMIN_MAX_FAILS = 3 # 錯 3 次就鎖
ADMIN_LOCK_BASE = 15 * 60 # 第一次鎖 15 分,之後每次加倍
ADMIN_LOCK_MAX = 24 * 3600
UID_MAX = 99_999_999 # UID 顯示成 8 碼
NAME_MAX = 32
BIO_MAX = 2000
AVATAR_MAX_BYTES = 5 * 1024 * 1024
AVATAR_SIZE = 1024
# 使用者投稿迷因圖:每個帳號每天(04:00 換日)最多 5 張,被拒絕的也算
SUBMIT_PER_DAY = 5
SUBMIT_MAX_BYTES = 5 * 1024 * 1024 # 和大頭貼一樣,錯誤訊息寫的是 5MB
SUBMIT_MAX_SIDE = 2048 # 長邊超過就等比例縮小
COOKIE_NAME = "inmu_session"
+161
View File
@@ -0,0 +1,161 @@
import shutil
import sqlite3
import time
from contextlib import contextmanager
from . import config
# init() 檢查管理員設定後填入;False 時管理員登入完全停用
admin_ok = False
SCHEMA = """
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
uid INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL,
bio_md TEXT NOT NULL DEFAULT '',
lang TEXT NOT NULL,
avatar_ver INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS login_codes (
email TEXT PRIMARY KEY COLLATE NOCASE,
code_hash TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
expires_at INTEGER NOT NULL,
last_sent_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
uid INTEGER NOT NULL REFERENCES users(uid) ON DELETE CASCADE ON UPDATE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_uid ON sessions(uid);
CREATE TABLE IF NOT EXISTS checkins (
uid INTEGER NOT NULL REFERENCES users(uid) ON DELETE CASCADE ON UPDATE CASCADE,
day TEXT NOT NULL,
meme TEXT,
created_at INTEGER NOT NULL,
PRIMARY KEY (uid, day)
);
-- 使用者投稿的迷因圖。待審的檔案在 DATA_DIR/submissions/<id>.<ext>,同意後搬進迷因資料夾
CREATE TABLE IF NOT EXISTS submissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid INTEGER NOT NULL REFERENCES users(uid) ON DELETE CASCADE ON UPDATE CASCADE,
day TEXT NOT NULL, -- 上傳當天(clock.today()),算每日額度用
ext TEXT NOT NULL, -- jpg / png
status TEXT NOT NULL DEFAULT 'pending', -- pending / approved / rejected
meme TEXT, -- 同意後的檔名,例如 inmu_14.jpg
created_at INTEGER NOT NULL,
reviewed_at INTEGER
);
CREATE INDEX IF NOT EXISTS submissions_uid_day ON submissions(uid, day);
CREATE INDEX IF NOT EXISTS submissions_status ON submissions(status, id);
"""
def db_path():
return config.DATA_DIR / "inmu.db"
def connect() -> sqlite3.Connection:
# isolation_level=None:自動 commit,需要交易時自己下 BEGIN
conn = sqlite3.connect(db_path(), isolation_level=None, timeout=10, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA busy_timeout = 10000")
return conn
def init():
config.DATA_DIR.mkdir(parents=True, exist_ok=True)
(config.DATA_DIR / "avatars").mkdir(exist_ok=True)
(config.DATA_DIR / "cards").mkdir(exist_ok=True)
(config.DATA_DIR / "submissions").mkdir(exist_ok=True)
conn = connect()
try:
conn.execute("PRAGMA journal_mode = WAL")
conn.executescript(SCHEMA)
conn.execute("INSERT OR IGNORE INTO meta(key, value) VALUES ('next_uid', 1)")
_migrate_default_names(conn)
_init_admin(conn)
finally:
conn.close()
def _migrate_default_names(conn: sqlite3.Connection) -> None:
"""舊的預設名稱 INMU1 → INMU_1(可以重複執行)。"""
rows = conn.execute("SELECT uid FROM users WHERE display_name = 'INMU' || uid").fetchall()
for (uid,) in rows:
conn.execute("UPDATE users SET display_name = ? WHERE uid = ?", (f"INMU_{uid}", uid))
shutil.rmtree(config.DATA_DIR / "cards" / str(uid), ignore_errors=True)
def _init_admin(conn: sqlite3.Connection) -> None:
"""建立或更新管理員帳號(uid 0)。改了 ADMIN_LOGIN 重啟就會生效。"""
global admin_ok
from . import totp
admin_ok = False
login, secret = config.ADMIN_LOGIN, config.ADMIN_TOTP
if not login or not secret:
return
try:
if len(totp.decode_secret(secret)) < 10:
raise ValueError("too short")
except Exception:
print("[ERROR] ADMIN_TOTP 不是合法的 base32 密鑰(至少 16 個字元),管理員登入停用", flush=True)
return
clash = conn.execute("SELECT uid FROM users WHERE email = ? AND uid != ?",
(login, config.ADMIN_UID)).fetchone()
if clash:
print(f"[ERROR] ADMIN_LOGIN 和 UID {clash[0]} 的信箱相同,管理員登入停用", flush=True)
return
conn.execute(
"INSERT INTO users(uid, email, display_name, lang, created_at) VALUES (?, ?, ?, ?, ?) "
"ON CONFLICT(uid) DO UPDATE SET email = excluded.email",
(config.ADMIN_UID, login, "管理員", config.DEFAULT_LANG, int(time.time())),
)
admin_ok = True
def get_meta(conn: sqlite3.Connection, key: str, default: int = 0) -> int:
row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
return row[0] if row else default
def set_meta(conn: sqlite3.Connection, key: str, value: int) -> None:
conn.execute("INSERT INTO meta(key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, value))
def get_db():
"""FastAPI dependency:每個請求一條連線。"""
conn = connect()
try:
yield conn
finally:
conn.close()
@contextmanager
def transaction(conn: sqlite3.Connection):
"""BEGIN IMMEDIATE:一開始就拿寫入鎖,避免兩個請求同時給號。"""
conn.execute("BEGIN IMMEDIATE")
try:
yield conn
except BaseException:
conn.execute("ROLLBACK")
raise
else:
conn.execute("COMMIT")
+52
View File
@@ -0,0 +1,52 @@
"""共用的 dependency:錯誤格式、session 驗證、取得使用者 IP。"""
import hashlib
import sqlite3
from fastapi import Depends, HTTPException, Request
from . import clock, config
from .db import get_db
def fail(status: int, code: str):
"""錯誤一律回 {"detail": "<code>"},前端用 err.<code> 翻譯。"""
raise HTTPException(status_code=status, detail=code)
def sha256(s: str) -> str:
return hashlib.sha256(s.encode()).hexdigest()
def client_ip(request: Request) -> str:
# port 只綁 127.0.0.1,外部流量都經過 cloudflared,所以可以信任 CF-Connecting-IP
return request.headers.get("cf-connecting-ip") or (request.client.host if request.client else "?")
def session_token(request: Request) -> str | None:
auth = request.headers.get("authorization", "")
if auth.lower().startswith("bearer "):
return auth[7:].strip() or None
return request.cookies.get(config.COOKIE_NAME)
def optional_user(request: Request, conn: sqlite3.Connection = Depends(get_db)) -> sqlite3.Row | None:
token = session_token(request)
if not token:
return None
return conn.execute(
"SELECT u.* FROM sessions s JOIN users u ON u.uid = s.uid "
"WHERE s.token_hash = ? AND s.expires_at > ?",
(sha256(token), clock.ts()),
).fetchone()
def current_user(user: sqlite3.Row | None = Depends(optional_user)) -> sqlite3.Row:
if user is None:
fail(401, "unauthorized")
return user
def admin_user(user: sqlite3.Row = Depends(current_user)) -> sqlite3.Row:
if user["uid"] != config.ADMIN_UID:
fail(403, "forbidden")
return user
+25
View File
@@ -0,0 +1,25 @@
"""伺服器端文字(信件、小卡、頭銜、分享文字)。前端介面文字在 web/i18n。"""
import json
from functools import lru_cache
from pathlib import Path
from .. import config
_DIR = Path(__file__).resolve().parent
@lru_cache(maxsize=None)
def _load(lang: str) -> dict:
with open(_DIR / f"{lang}.json", encoding="utf-8") as f:
return json.load(f)
def norm_lang(lang) -> str:
return lang if lang in config.LANGS else config.DEFAULT_LANG
def t(lang: str, key: str, **kw) -> str:
text = _load(norm_lang(lang)).get(key)
if text is None:
text = _load("en").get(key, key)
return text.format(**kw) if kw else text
+10
View File
@@ -0,0 +1,10 @@
{
"mail.subject": "Your My INMU code: {code}",
"mail.body": "Your My INMU verification code is:\n\n{code}\n\nIt expires in 5 minutes. If you didn't request this, you can ignore this email.\n\n{url}",
"card.day": "Day {n}",
"card.streak": "{n}-day streak",
"card.no_meme": "Meme coming soon",
"share.text": "Day {n} of checking in on My INMU!",
"share.title": "{name}'s INMU card",
"share.open": "Check in too"
}
+10
View File
@@ -0,0 +1,10 @@
{
"mail.subject": "My INMU 認証コード:{code}",
"mail.body": "My INMU の認証コードは:\n\n{code}\n\n有効期限は 5 分です。お心当たりのない場合は、このメールを破棄してください。\n\n{url}",
"card.day": "ログイン {n} 日目",
"card.streak": "連続 {n} 日",
"card.no_meme": "画像準備中",
"share.text": "My INMU でログイン {n} 日目!",
"share.title": "{name} の INMU カード",
"share.open": "自分もログインする"
}
+10
View File
@@ -0,0 +1,10 @@
{
"mail.subject": "My INMU 인증 코드: {code}",
"mail.body": "My INMU 인증 코드는:\n\n{code}\n\n5분 동안 유효합니다. 본인이 요청하지 않았다면 이 메일을 무시해 주세요.\n\n{url}",
"card.day": "출석 {n}일째",
"card.streak": "연속 {n}일",
"card.no_meme": "이미지 준비 중",
"share.text": "My INMU 출석 {n}일째!",
"share.title": "{name}의 INMU 카드",
"share.open": "나도 출석하기"
}
+10
View File
@@ -0,0 +1,10 @@
{
"mail.subject": "My INMU 验证码:{code}",
"mail.body": "你的 My INMU 验证码是:\n\n{code}\n\n5 分钟内有效。如果这不是你本人的操作,请直接忽略这封邮件。\n\n{url}",
"card.day": "签到第 {n} 天",
"card.streak": "连续 {n} 天",
"card.no_meme": "梗图准备中",
"share.text": "我在 My INMU 签到第 {n} 天!",
"share.title": "{name} 的 INMU 小卡",
"share.open": "我也要签到"
}
+10
View File
@@ -0,0 +1,10 @@
{
"mail.subject": "My INMU 驗證碼:{code}",
"mail.body": "你的 My INMU 驗證碼是:\n\n{code}\n\n5 分鐘內有效。如果這不是你本人的操作,請直接忽略這封信。\n\n{url}",
"card.day": "簽到第 {n} 天",
"card.streak": "連續 {n} 天",
"card.no_meme": "梗圖準備中",
"share.text": "我在 My INMU 簽到第 {n} 天!",
"share.title": "{name} 的 INMU 小卡",
"share.open": "我也要簽到"
}
+36
View File
@@ -0,0 +1,36 @@
"""寄送驗證碼。改寫自 RhyculatorServer/Verify_email/main.py 的 send_email(),改成通用 SMTP。
寄信是容器主動連出去(smtp.gmail.com:465 等),不經過 cloudflared tunnel,不用額外開 port。
"""
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid
from . import config
from .i18n import t
def send_code(to_email: str, code: str, lang: str) -> None:
# 本地開發沒有設定 SMTP 帳密時,直接把驗證碼印在 log
if not config.SMTP_USER or not config.SMTP_PASSWORD:
print(f"[DEV] verify code for {to_email}: {code}", flush=True)
return
msg = EmailMessage()
msg["Subject"] = t(lang, "mail.subject", code=code)
# Gmail:MAIL_FROM 要先在「以這個地址寄送郵件」加入別名,否則 Gmail 會改回帳號本身
msg["From"] = formataddr(("My INMU", config.MAIL_FROM))
msg["To"] = to_email
msg["Message-ID"] = make_msgid(domain=config.MAIL_FROM.rpartition("@")[2] or None)
msg.set_content(t(lang, "mail.body", code=code, url=config.PUBLIC_URL))
ctx = ssl.create_default_context()
if config.SMTP_PORT == 465:
smtp = smtplib.SMTP_SSL(config.SMTP_HOST, config.SMTP_PORT, timeout=15, context=ctx)
else:
smtp = smtplib.SMTP(config.SMTP_HOST, config.SMTP_PORT, timeout=15)
smtp.starttls(context=ctx)
with smtp:
smtp.login(config.SMTP_USER, config.SMTP_PASSWORD)
smtp.send_message(msg)
+92
View File
@@ -0,0 +1,92 @@
import hashlib
import mimetypes
from contextlib import asynccontextmanager
from functools import lru_cache
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from . import auth, card, checkin, config, db, share, submissions, users
# python:3.12-slim 沒有 /etc/mime.types,這些副檔名會被當成 text/plain;加上 nosniff 後瀏覽器可能拒絕播放
for _type, _ext in (("image/webp", ".webp"), ("audio/mp4", ".m4a"), ("application/manifest+json", ".webmanifest"),
("image/svg+xml", ".svg"), ("image/x-icon", ".ico")):
mimetypes.add_type(_type, _ext)
CSP = ("default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; "
"script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
@asynccontextmanager
async def lifespan(app: FastAPI):
db.init()
if not config.SMTP_USER or not config.SMTP_PASSWORD:
print("[WARN] SMTP_USER / SMTP_PASSWORD 沒有設定:不會寄信,驗證碼只印在 log([DEV] verify code ...)",
flush=True)
else:
print(f"[mail] {config.SMTP_USER}@{config.SMTP_HOST}:{config.SMTP_PORT}, from {config.MAIL_FROM}", flush=True)
yield
app = FastAPI(title="My INMU", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
@app.middleware("http")
async def guard(request: Request, call_next):
# 防 CSRF:會改資料的 /api 請求要帶 X-INMU: 1(跨站表單帶不了自訂 header)。
# 用 Bearer token 的客戶端(Android)沒有 cookie,不受 CSRF 影響,所以不檢查。
if (request.method in ("POST", "PUT", "PATCH", "DELETE")
and request.url.path.startswith("/api/")
and request.headers.get("x-inmu") != "1"
and not request.headers.get("authorization")):
return JSONResponse({"detail": "csrf"}, status_code=403)
response = await call_next(request)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
response.headers.setdefault("Content-Security-Policy", CSP)
if request.url.path.startswith("/assets/"):
# 沒有這行時 Cloudflare 會自己快取 .js / .css,改版後使用者拿到舊檔。
# no-cache = 每次向伺服器確認,沒變就回 304
response.headers.setdefault("Cache-Control", "no-cache")
return response
for module in (auth, users, checkin, card, share, submissions):
app.include_router(module.router)
@app.get("/healthz")
def healthz():
return {"status": "ok"}
@lru_cache(maxsize=1)
def asset_version() -> str:
"""web/ 底下所有檔案內容的雜湊。檔案一改,網址的 ?v= 就變,Cloudflare 和瀏覽器都會抓新的。"""
h = hashlib.sha256()
for p in sorted(config.WEB_DIR.rglob("*")):
if p.is_file():
h.update(p.relative_to(config.WEB_DIR).as_posix().encode())
h.update(p.read_bytes())
return h.hexdigest()[:10]
def index():
html = (config.WEB_DIR / "index.html").read_text(encoding="utf-8")
html = html.replace("__ASSET_VERSION__", asset_version())
html = html.replace("<!--BETA_TITLE-->", " (Beta)" if config.BETA else "")
html = html.replace("<!--BETA_BADGE-->", ' <small class="beta">(Beta)</small>' if config.BETA else "")
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
@app.get("/favicon.ico", include_in_schema=False)
def favicon():
return FileResponse(config.WEB_DIR / "favicon.ico", headers={"Cache-Control": "public, max-age=86400"})
app.add_api_route("/", index, methods=["GET", "HEAD"], include_in_schema=False)
app.add_api_route("/u/{uid}", index, methods=["GET", "HEAD"], include_in_schema=False)
app.add_api_route("/upload", index, methods=["GET", "HEAD"], include_in_schema=False)
app.add_api_route("/review", index, methods=["GET", "HEAD"], include_in_schema=False)
app.mount("/assets", StaticFiles(directory=config.WEB_DIR, check_dir=False), name="assets")
+72
View File
@@ -0,0 +1,72 @@
"""分享頁 /c/<uid>/<day>:有 og:image,貼到 Discord、X、LINE 會出現小卡預覽。"""
import sqlite3
from html import escape
from fastapi import APIRouter, Depends
from fastapi.responses import HTMLResponse
from . import config
from .card import DAY_RE
from .checkin import stats
from .db import get_db
from .deps import fail
from .i18n import norm_lang, t
from .titles import fmt_uid
router = APIRouter()
PAGE = """<!DOCTYPE html>
<html lang="{lang}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title} · {site}</title>
<meta property="og:type" content="website">
<meta property="og:site_name" content="{site}">
<meta property="og:title" content="{title}">
<meta property="og:description" content="{desc}">
<meta property="og:image" content="{image}">
<meta property="og:image:width" content="1080">
<meta property="og:image:height" content="1350">
<meta property="og:url" content="{url}">
<meta name="twitter:card" content="summary_large_image">
<link rel="icon" href="/favicon.ico" sizes="48x48">
<link rel="icon" href="/assets/icon-192.png" type="image/png" sizes="192x192">
<link rel="apple-touch-icon" href="/assets/apple-touch-icon.png">
<style>
body {{ margin: 0; min-height: 100vh; display: flex; flex-direction: column; align-items: center;
justify-content: center; gap: 24px; background: #121016; color: #f5f3fa;
font-family: system-ui, "Noto Sans CJK TC", sans-serif; padding: 24px; box-sizing: border-box; }}
img {{ width: min(540px, 100%); border-radius: 16px; box-shadow: 0 12px 40px #0008; }}
a {{ background: #f0a43a; color: #1e1a24; padding: 12px 28px; border-radius: 999px;
text-decoration: none; font-weight: 700; }}
</style>
</head>
<body>
<img src="{image_path}" alt="{title}">
<a href="/">{open}</a>
</body>
</html>"""
@router.get("/c/{uid}/{day}", response_class=HTMLResponse)
def share_page(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
if not DAY_RE.match(day):
fail(404, "not_found")
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
if user is None or conn.execute(
"SELECT 1 FROM checkins WHERE uid = ? AND day = ?", (uid, day)).fetchone() is None:
fail(404, "not_found")
lang = norm_lang(user["lang"])
total, _ = stats(conn, uid, day)
image_path = f"/card/{fmt_uid(uid)}/{day}.png"
return PAGE.format(
lang=lang,
site="My INMU (Beta)" if config.BETA else "My INMU",
title=escape(t(lang, "share.title", name=user["display_name"])),
desc=escape(t(lang, "share.text", n=total)),
image=escape(config.PUBLIC_URL + image_path),
image_path=image_path,
url=escape(f"{config.PUBLIC_URL}/c/{fmt_uid(uid)}/{day}"),
open=escape(t(lang, "share.open")),
)
+216
View File
@@ -0,0 +1,216 @@
"""使用者投稿迷因圖,管理員審核。
流程:使用者上傳 → 重新編碼後存在 DATA_DIR/submissions/<id>.<ext>(pending)
→ 管理員同意:依 image/ 的命名規則存成 MEME_DIR/inmu_<下一號>.<ext>,之後的小卡就可能抽到
→ 管理員拒絕:刪掉檔案,紀錄保留(每日額度要算)
"""
import io
import os
import re
import shutil
import sqlite3
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from fastapi import APIRouter, Depends, File, UploadFile
from fastapi.responses import FileResponse
from PIL import Image, ImageOps
from . import clock, config
from .db import get_db, transaction
from .deps import admin_user, current_user, fail
from .titles import fmt_uid, uid_tier
router = APIRouter()
MEME_NAME = re.compile(r"^inmu_(\d+)\.[A-Za-z0-9]+$")
MEDIA_TYPES = {"jpg": "image/jpeg", "png": "image/png", "jpeg": "image/jpeg",
"webp": "image/webp", "gif": "image/gif"}
def submission_dir() -> Path:
return config.DATA_DIR / "submissions"
def pending_path(row: sqlite3.Row) -> Path:
return submission_dir() / f"{row['id']}.{row['ext']}"
def process_meme(data: bytes) -> tuple[bytes, str]:
"""重新編碼成 JPEG(有透明度就用 PNG):去掉 EXIF(含 GPS)和偽裝成圖片的內容,GIF 只取第一格。"""
try:
with Image.open(io.BytesIO(data)) as im:
im.seek(0)
im.load()
im = ImageOps.exif_transpose(im)
has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
im = im.convert("RGBA" if has_alpha else "RGB")
except Exception:
fail(400, "invalid_image")
if max(im.size) > config.SUBMIT_MAX_SIDE:
im.thumbnail((config.SUBMIT_MAX_SIDE, config.SUBMIT_MAX_SIDE), Image.LANCZOS)
out = io.BytesIO()
if has_alpha:
im.save(out, "PNG", optimize=True)
return out.getvalue(), "png"
im.save(out, "JPEG", quality=90, optimize=True)
return out.getvalue(), "jpg"
def write_atomic(path: Path, data: bytes) -> None:
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".", suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
f.write(data)
os.replace(tmp, path)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
def next_meme_number() -> int:
"""迷因資料夾裡 inmu_<n>.* 的最大編號 + 1。"""
nums = [int(m.group(1)) for p in config.MEME_DIR.iterdir() if (m := MEME_NAME.match(p.name))] \
if config.MEME_DIR.is_dir() else []
return max(nums, default=-1) + 1
def iso(ts: int | None) -> str | None:
return datetime.fromtimestamp(ts, timezone.utc).isoformat() if ts else None
def image_url(row: sqlite3.Row) -> str | None:
return None if row["status"] == "rejected" else f"/api/submissions/{row['id']}/image"
def used_today(conn: sqlite3.Connection, uid: int, day: str) -> int:
return conn.execute("SELECT COUNT(*) FROM submissions WHERE uid = ? AND day = ?", (uid, day)).fetchone()[0]
def quota(conn: sqlite3.Connection, uid: int) -> dict:
used = used_today(conn, uid, clock.today())
return {"used": used, "limit": config.SUBMIT_PER_DAY, "remaining": max(0, config.SUBMIT_PER_DAY - used)}
def item(row: sqlite3.Row) -> dict:
return {"id": row["id"], "status": row["status"], "created_at": iso(row["created_at"]),
"image_url": image_url(row)}
def pending_count(conn: sqlite3.Connection) -> int:
return conn.execute("SELECT COUNT(*) FROM submissions WHERE status = 'pending'").fetchone()[0]
# ---------- 使用者 ----------
@router.post("/api/submissions")
def upload(file: UploadFile = File(...), user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
data = file.file.read(config.SUBMIT_MAX_BYTES + 1)
if len(data) > config.SUBMIT_MAX_BYTES:
fail(413, "file_too_large")
body, ext = process_meme(data) # 先處理圖片,不佔用寫入鎖
day = clock.today()
submission_dir().mkdir(parents=True, exist_ok=True)
# BEGIN IMMEDIATE:同時上傳好幾張也不會超過額度;寫檔失敗會連同 INSERT 一起還原
with transaction(conn):
if used_today(conn, user["uid"], day) >= config.SUBMIT_PER_DAY:
fail(429, "quota_exceeded")
cur = conn.execute("INSERT INTO submissions(uid, day, ext, created_at) VALUES (?, ?, ?, ?)",
(user["uid"], day, ext, clock.ts()))
row = conn.execute("SELECT * FROM submissions WHERE id = ?", (cur.lastrowid,)).fetchone()
write_atomic(pending_path(row), body)
return {"item": item(row), **quota(conn, user["uid"])}
@router.get("/api/submissions")
def my_submissions(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
rows = conn.execute("SELECT * FROM submissions WHERE uid = ? ORDER BY id DESC LIMIT 30", (user["uid"],))
return {**quota(conn, user["uid"]), "items": [item(r) for r in rows]}
@router.get("/api/submissions/{sid}/image")
def submission_image(sid: int, user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
row = conn.execute("SELECT * FROM submissions WHERE id = ?", (sid,)).fetchone()
# 只有上傳者本人和管理員看得到;別人一律當作不存在
if row is None or (row["uid"] != user["uid"] and user["uid"] != config.ADMIN_UID):
fail(404, "not_found")
if row["status"] == "pending":
path = pending_path(row)
elif row["status"] == "approved" and row["meme"]:
path = config.MEME_DIR / row["meme"]
else:
fail(404, "not_found")
if not path.is_file():
fail(404, "not_found")
ext = path.suffix.lower().lstrip(".")
return FileResponse(path, media_type=MEDIA_TYPES.get(ext, "application/octet-stream"),
headers={"Cache-Control": "private, max-age=3600"})
# ---------- 管理員審核 ----------
@router.get("/api/admin/submissions")
def next_pending(admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
"""最舊的一張待審投稿(一張一張審)。"""
row = conn.execute(
"SELECT s.*, u.display_name FROM submissions s JOIN users u ON u.uid = s.uid "
"WHERE s.status = 'pending' ORDER BY s.id LIMIT 1").fetchone()
left = pending_count(conn)
if row is None:
return {"item": None, "pending": left}
return {
"item": {
**item(row),
"uploader": {"uid": row["uid"], "uid_str": fmt_uid(row["uid"]), "uid_tier": uid_tier(row["uid"]),
"display_name": row["display_name"]},
},
"pending": left,
}
def _load_pending(conn: sqlite3.Connection, sid: int) -> sqlite3.Row:
row = conn.execute("SELECT * FROM submissions WHERE id = ?", (sid,)).fetchone()
if row is None:
fail(404, "not_found")
if row["status"] != "pending":
fail(409, "already_reviewed")
return row
@router.post("/api/admin/submissions/{sid}/approve")
def approve(sid: int, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
with transaction(conn): # 寫入鎖確保兩次同意不會拿到同一個編號
row = _load_pending(conn, sid)
src = pending_path(row)
if not src.is_file():
fail(404, "not_found")
config.MEME_DIR.mkdir(parents=True, exist_ok=True)
n = next_meme_number()
while any(config.MEME_DIR.glob(f"inmu_{n}.*")):
n += 1
name = f"inmu_{n}.{row['ext']}"
# 先複製成 . 開頭的暫存檔(抽卡會略過),完整寫好再改名
fd, tmp = tempfile.mkstemp(dir=config.MEME_DIR, prefix=".", suffix=".tmp")
os.close(fd)
try:
shutil.copyfile(src, tmp)
os.replace(tmp, config.MEME_DIR / name)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
conn.execute("UPDATE submissions SET status = 'approved', meme = ?, reviewed_at = ? WHERE id = ?",
(name, clock.ts(), sid))
src.unlink(missing_ok=True)
print(f"[review] approved #{sid} from UID {fmt_uid(row['uid'])} -> {name}", flush=True)
return {"id": sid, "status": "approved", "meme": name, "pending": pending_count(conn)}
@router.post("/api/admin/submissions/{sid}/reject")
def reject(sid: int, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
with transaction(conn):
row = _load_pending(conn, sid)
conn.execute("UPDATE submissions SET status = 'rejected', reviewed_at = ? WHERE id = ?", (clock.ts(), sid))
pending_path(row).unlink(missing_ok=True)
print(f"[review] rejected #{sid} from UID {fmt_uid(row['uid'])}", flush=True)
return {"id": sid, "status": "rejected", "pending": pending_count(conn)}
+25
View File
@@ -0,0 +1,25 @@
from . import config
# 特殊序號:UID 用背景色標示,不帶任何權限。8 碼 UID 只要包含這些號碼就算(例如 00114514、51919810)
TIER_PATTERNS = ("1919810", "114514")
# 底色、文字色(網頁的 web/style.css 用同樣的顏色)
TIER_COLORS = {
"admin": ((245, 197, 24), (30, 26, 36)), # 黃 #F5C518
"1919810": ((240, 124, 42), (30, 26, 36)), # 橘 #F07C2A
"114514": ((47, 123, 235), (255, 255, 255)), # 藍 #2F7BEB
}
def fmt_uid(uid: int) -> str:
return f"{uid:08d}"
def uid_tier(uid: int) -> str | None:
if uid == config.ADMIN_UID:
return "admin"
s = fmt_uid(uid)
for pattern in TIER_PATTERNS:
if pattern in s:
return pattern
return None
+40
View File
@@ -0,0 +1,40 @@
"""RFC 6238 TOTP(SHA1、6 碼、30 秒),和 Aegis / Google Authenticator 預設相同。只用標準函式庫。"""
import base64
import hashlib
import hmac
import struct
from urllib.parse import quote
PERIOD = 30
DIGITS = 6
def decode_secret(secret: str) -> bytes:
s = secret.replace(" ", "").upper()
return base64.b32decode(s + "=" * (-len(s) % 8))
def code_at(key: bytes, step: int) -> str:
digest = hmac.new(key, struct.pack(">Q", step), hashlib.sha1).digest()
offset = digest[-1] & 0x0F
value = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF
return f"{value % 10**DIGITS:0{DIGITS}d}"
def verify(secret: str, code: str, unix_time: int, window: int = 1) -> int | None:
"""比對前後各 window 個時間窗(容忍手機時鐘誤差),成功回傳符合的時間步。"""
if len(code) != DIGITS or not code.isdigit():
return None
key = decode_secret(secret)
current = unix_time // PERIOD
matched = None
for step in range(current - window, current + window + 1):
# 全部比完,不提早結束,避免從回應時間猜出哪個時間窗符合
if hmac.compare_digest(code_at(key, step), code) and matched is None:
matched = step
return matched
def uri(secret: str, account: str, issuer: str = "My INMU") -> str:
label = quote(f"{issuer}:{account}")
return f"otpauth://totp/{label}?secret={secret.replace(' ', '').upper()}&issuer={quote(issuer)}"
+201
View File
@@ -0,0 +1,201 @@
import io
import os
import sqlite3
import tempfile
import unicodedata
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, File, Query, UploadFile
from fastapi.responses import FileResponse
from markdown_it import MarkdownIt
from PIL import Image, ImageOps
from pydantic import BaseModel
from . import card, clock, config
from .checkin import stats
from .db import get_db, transaction
from .deps import current_user, fail
from .i18n import norm_lang
from .titles import fmt_uid, uid_tier
router = APIRouter()
# 關閉原始 HTML(輸入的 <script> 會被跳脫)與圖片(避免追蹤用的外部圖片)
_md = MarkdownIt("commonmark", {"html": False, "breaks": True}).enable(["table", "strikethrough"]).disable("image")
def _link_open(self, tokens, idx, options, env):
# add_render_rule 會把函式綁到 renderer 上,所以第一個參數是 self
tokens[idx].attrSet("rel", "nofollow noopener noreferrer")
tokens[idx].attrSet("target", "_blank")
return self.renderToken(tokens, idx, options, env)
_md.add_render_rule("link_open", _link_open)
def render_md(text: str) -> str:
return _md.render(text or "")
# ---------- 帳號建立與 UID 給號 ----------
def create_user(conn: sqlite3.Connection, email: str, lang: str) -> sqlite3.Row:
"""依序給號(從 1 開始;0 是管理員)。不用 AUTOINCREMENT:SQLite 會從現有最大 uid 往後給,
一旦有人被 grant-uid 指定成很大的號碼,之後的號碼就會全部跳過去。"""
with transaction(conn):
row = conn.execute("SELECT * FROM users WHERE email = ?", (email,)).fetchone()
if row:
return row
uid = conn.execute("SELECT value FROM meta WHERE key = 'next_uid'").fetchone()[0]
# 跳過已經被 grant-uid 指定出去的號碼
while conn.execute("SELECT 1 FROM users WHERE uid = ?", (uid,)).fetchone():
uid += 1
if uid > config.UID_MAX:
fail(503, "uid_exhausted")
conn.execute(
"INSERT INTO users(uid, email, display_name, lang, created_at) VALUES (?, ?, ?, ?, ?)",
(uid, email, f"INMU_{uid}", norm_lang(lang), clock.ts()),
)
conn.execute("UPDATE meta SET value = ? WHERE key = 'next_uid'", (uid + 1,))
return conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
# ---------- 個人資料 ----------
def avatar_url(user: sqlite3.Row) -> str | None:
return f"/avatars/{fmt_uid(user['uid'])}.webp?v={user['avatar_ver']}" if user["avatar_ver"] else None
def profile(conn: sqlite3.Connection, user: sqlite3.Row, lang: str, private: bool = False) -> dict:
total, streak = stats(conn, user["uid"], live=True)
out = {
"uid": user["uid"],
"uid_str": fmt_uid(user["uid"]),
"display_name": user["display_name"],
"uid_tier": uid_tier(user["uid"]),
"bio_md": user["bio_md"],
"bio_html": render_md(user["bio_md"]),
"avatar_url": avatar_url(user),
"total_days": total,
"streak": streak,
"created_at": datetime.fromtimestamp(user["created_at"], timezone.utc).isoformat(),
}
if private:
out["email"] = user["email"]
out["lang"] = user["lang"]
out["is_admin"] = user["uid"] == config.ADMIN_UID
if out["is_admin"]:
out["pending_reviews"] = conn.execute(
"SELECT COUNT(*) FROM submissions WHERE status = 'pending'").fetchone()[0]
return out
def clean_name(name: str) -> str:
# 去掉換行等控制字元
name = "".join(ch for ch in name if unicodedata.category(ch) != "Cc").strip()
if not 1 <= len(name) <= config.NAME_MAX:
fail(400, "name_invalid")
return name
class ProfilePatch(BaseModel):
display_name: str | None = None
bio_md: str | None = None
lang: str | None = None
@router.get("/api/me")
def get_me(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
return profile(conn, user, user["lang"], private=True)
@router.patch("/api/me")
def patch_me(body: ProfilePatch, user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
fields = {}
if body.display_name is not None:
fields["display_name"] = clean_name(body.display_name)
if body.bio_md is not None:
bio = body.bio_md.replace("\r\n", "\n")
if len(bio) > config.BIO_MAX:
fail(400, "bio_too_long")
fields["bio_md"] = bio
if body.lang is not None:
if body.lang not in config.LANGS:
fail(400, "invalid_lang")
fields["lang"] = body.lang
if fields:
sets = ", ".join(f"{k} = ?" for k in fields)
conn.execute(f"UPDATE users SET {sets} WHERE uid = ?", (*fields.values(), user["uid"]))
if {"display_name", "lang"} & fields.keys():
card.invalidate(user["uid"])
user = conn.execute("SELECT * FROM users WHERE uid = ?", (user["uid"],)).fetchone()
return profile(conn, user, user["lang"], private=True)
# ---------- 大頭貼 ----------
def process_avatar(data: bytes) -> bytes:
"""置中裁成正方形、縮成 1024×1024、重新編成 WebP(順便去掉 EXIF 與偽裝成圖片的內容)。"""
try:
with Image.open(io.BytesIO(data)) as im:
im.seek(0)
im.load()
im = ImageOps.exif_transpose(im)
has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
im = im.convert("RGBA" if has_alpha else "RGB")
except Exception:
fail(400, "invalid_image")
size = config.AVATAR_SIZE
im = ImageOps.fit(im, (size, size), Image.LANCZOS)
out = io.BytesIO()
im.save(out, "WEBP", quality=90, method=4)
return out.getvalue()
@router.put("/api/me/avatar")
def put_avatar(file: UploadFile = File(...), user=Depends(current_user),
conn: sqlite3.Connection = Depends(get_db)):
data = file.file.read(config.AVATAR_MAX_BYTES + 1)
if len(data) > config.AVATAR_MAX_BYTES:
fail(413, "file_too_large")
webp = process_avatar(data)
folder = config.DATA_DIR / "avatars"
folder.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
with os.fdopen(fd, "wb") as f:
f.write(webp)
os.replace(tmp, folder / f"{user['uid']}.webp")
conn.execute("UPDATE users SET avatar_ver = ? WHERE uid = ?", (clock.ts(), user["uid"]))
card.invalidate(user["uid"])
user = conn.execute("SELECT * FROM users WHERE uid = ?", (user["uid"],)).fetchone()
return profile(conn, user, user["lang"], private=True)
@router.get("/avatars/{uid}.webp")
def get_avatar(uid: int):
path = config.DATA_DIR / "avatars" / f"{uid}.webp"
if not path.exists():
fail(404, "not_found")
return FileResponse(path, media_type="image/webp", headers={"Cache-Control": "public, max-age=86400"})
# ---------- 公開資料 ----------
@router.get("/api/users/{uid}")
def get_user(uid: int, lang: str = Query(config.DEFAULT_LANG), conn: sqlite3.Connection = Depends(get_db)):
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
if user is None:
fail(404, "user_not_found")
return profile(conn, user, lang)
class MarkdownIn(BaseModel):
md: str
@router.post("/api/markdown")
def preview_markdown(body: MarkdownIn, user=Depends(current_user)):
if len(body.md) > config.BIO_MAX:
fail(400, "bio_too_long")
return {"html": render_md(body.md)}