upload to gitea
No files matched your search
@@ -0,0 +1,10 @@
|
||||
.env
|
||||
.git
|
||||
**/__pycache__
|
||||
**/.pytest_cache
|
||||
server/.venv
|
||||
server/tests
|
||||
data
|
||||
image
|
||||
icon
|
||||
tools
|
||||
@@ -0,0 +1,26 @@
|
||||
# 對外網址:分享連結、og:image、信件裡的連結都用這個
|
||||
PUBLIC_URL=https://inmu.sthkm3.org
|
||||
# 經 cloudflared(https)對外時設 1,登入 cookie 只走 https(本機 http://127.0.0.1 也能用)
|
||||
COOKIE_SECURE=1
|
||||
# Beta 期間設 1(網頁標題加 (Beta)、小卡右下角加 · Beta);正式上線改 0,並執行 reset-progress
|
||||
BETA=1
|
||||
# 本機 port(只綁 127.0.0.1,cloudflared 指到 http://localhost:2040)
|
||||
PORT=2040
|
||||
|
||||
# ---- 寄信(SMTP,容器主動連出去,不經過 tunnel)----
|
||||
# 帳密留空 = 不寄信,驗證碼印在 log(docker compose logs app)
|
||||
# Resend(先在後台驗證 inmu.sthkm3.org):USER=resend,PASSWORD=API key
|
||||
# 臨時用 Gmail:HOST=smtp.gmail.com,USER=Gmail 帳號,PASSWORD=應用程式密碼(寄件人會變成那個 Gmail)
|
||||
SMTP_HOST=smtp.resend.com
|
||||
SMTP_PORT=465
|
||||
SMTP_USER=resend
|
||||
SMTP_PASSWORD=
|
||||
# 寄件人,網域要和寄信服務驗證過的網域相同
|
||||
MAIL_FROM=[email protected]
|
||||
|
||||
# ---- 管理員(UID 00000000)----
|
||||
# 登入框的信箱欄輸入 ADMIN_LOGIN,驗證碼用 Aegis 等 TOTP App 算(SHA1、6 位、30 秒)
|
||||
# ADMIN_TOTP 是 base32 密鑰;兩個都留空 = 停用管理員登入。改完執行 docker compose up -d
|
||||
# 換手機時:docker compose exec app python -m app.admin totp-uri
|
||||
ADMIN_LOGIN=
|
||||
ADMIN_TOTP=
|
||||
@@ -0,0 +1,9 @@
|
||||
.env
|
||||
*.ipynb
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
.venv/
|
||||
data/
|
||||
|
||||
# 梗圖(使用者自己提供)
|
||||
image/
|
||||
@@ -0,0 +1,179 @@
|
||||
# My INMU
|
||||
|
||||
每天簽到一次,產生一張 INMU 小卡(累計天數 + 隨機梗圖),可以圖文分享。
|
||||
用信箱驗證碼註冊、登入(沒有密碼)。介面支援繁中、簡中、日、韓、英。網址預定為 `inmu.sthkm3.org`。
|
||||
|
||||
| 服務 | 內容 | port |
|
||||
|---|---|---|
|
||||
| `app` | FastAPI + SQLite:API、網站、小卡圖片(Pillow + Noto Sans CJK) | `127.0.0.1:2040` |
|
||||
|
||||
port 只綁本機,正式上線由 cloudflared tunnel 對外。
|
||||
|
||||
## 啟動
|
||||
|
||||
```
|
||||
cp .env.example .env # SMTP_USER / SMTP_PASSWORD 留空時驗證碼印在 log
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
打開 `http://127.0.0.1:2040`,輸入信箱後用 `docker compose logs app` 找驗證碼(`[DEV] verify code for ...`)。
|
||||
|
||||
| 指令 | 用途 |
|
||||
|---|---|
|
||||
| `docker compose logs -f app` | log(SMTP 帳密沒填時,驗證碼印在這裡) |
|
||||
| `docker compose down` | 停止(資料保留) |
|
||||
| `docker compose down -v` | 停止並刪除 volume `myinmu_inmu-data`(清空帳號與簽到紀錄) |
|
||||
| `docker compose exec app python -m app.admin info <email>` | 查看帳號 |
|
||||
| `docker compose exec app python -m app.admin grant-uid <email> 114514` | 把帳號的 UID 換成指定號碼(1–99999999) |
|
||||
| `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` | 清空所有簽到進度(保留帳號;不加 `--yes` 只顯示會刪什麼) |
|
||||
|
||||
## 梗圖
|
||||
|
||||
放在 `image/`(jpg / png / webp / gif 取第一幀),容器掛載成 `/memes`。
|
||||
每次簽到時隨機抽一張,檔名存進資料庫,所以同一天的小卡重畫也一樣。新增圖片不用重啟;**已經被抽過的圖片不要改名或刪除**,否則舊的小卡會變成「梗圖準備中」。
|
||||
|
||||
### 使用者投稿
|
||||
|
||||
- 登入後側欄的「投稿圖片」(`/upload`):每個帳號每天最多 5 張(台灣時間 04:00 重置,被拒絕的也算),每張上限 5MB
|
||||
- 上傳的圖會重新編碼成 JPEG(有透明度就用 PNG),去掉 EXIF / GPS;長邊超過 2048 會縮小
|
||||
- 待審的檔案放在 volume 的 `/data/submissions/<id>.<ext>`
|
||||
- 管理員側欄的「審核投稿 (N)」(`/review`)一次顯示一張,按同意或拒絕:
|
||||
- 同意:存成 `image/inmu_<目前最大編號 + 1>.jpg`(所以 `image/` 要可寫入),馬上加入抽卡
|
||||
- 拒絕:刪掉檔案,紀錄保留(用來算額度)
|
||||
- 審核結果記在 log(`[review] ...`)
|
||||
|
||||
## 簽到按鈕
|
||||
|
||||
- 按鈕原圖是 `icon/checkin/0.png`(按下前)和 `1.png`(按下後),由 `tools/make_icons.py` 縮成 `web/media/checkin-0.webp`、`checkin-1.webp`
|
||||
- 音效是 `web/media/114514.m4a`(約 1.5 秒)
|
||||
- 按下去會換圖、播音效、噴粒子;音效播完、小卡也下載好之後才亮出小卡並停掉音效
|
||||
|
||||
## 網頁圖標
|
||||
|
||||
原圖放在 `icon/`,換圖後執行下面的指令重新產生 `web/` 裡的 favicon.ico、icon-192/512.png、apple-touch-icon.png、logo.png(以及簽到按鈕的兩張 webp),再重新 build:
|
||||
|
||||
```
|
||||
server/.venv/Scripts/python tools/make_icons.py
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
## UID 與頭銜
|
||||
|
||||
- UID 顯示成 8 碼(`00000001`),資料庫存整數。`00000000` 是管理員,一般使用者從 `00000001` 開始依序給號
|
||||
- 預設名稱是 `INMU_<uid>`(例如 `INMU_1`)
|
||||
- 給號用 `meta.next_uid`,不用 `AUTOINCREMENT`:否則 `grant-uid` 給出很大的號碼之後,之後的號碼會全部跳過去
|
||||
- 特殊序號用 UID 的背景色標示(側欄、個人頁、小卡),不帶任何權限:
|
||||
- `00000000`(管理員):黃底
|
||||
- 8 碼裡包含 `1919810`(例如 `51919810`):橘底
|
||||
- 8 碼裡包含 `114514`(例如 `00114514`):藍底
|
||||
- API 回傳 `uid_tier`:`"admin"`、`"1919810"`、`"114514"` 或 `null`。顏色定義在 `server/app/titles.py` 的 `TIER_COLORS`(小卡)和 `web/style.css` 的 `.uid.tier-*`(網頁),兩邊要一起改
|
||||
|
||||
## 管理員
|
||||
|
||||
- `.env` 設定 `ADMIN_LOGIN`(信箱欄要輸入的字,例如 `sthkm3`)和 `ADMIN_TOTP`(base32 密鑰),改完執行 `docker compose up -d`。兩個都留空就停用管理員登入
|
||||
- 登入:在網頁的信箱欄輸入 `ADMIN_LOGIN`,按「寄送驗證碼」(不會真的寄信),再輸入 Aegis 上的 6 位數
|
||||
- Aegis 設定:TOTP、SHA1、6 位、30 秒
|
||||
- 防護:
|
||||
- 錯 3 次就鎖定,鎖定時間依序是 15 分、30 分、1 小時…上限 24 小時;成功登入後歸零
|
||||
- 鎖定是全域的,換 IP 也繞不過
|
||||
- 每組碼只能用一次
|
||||
- 管理員 session 有效 7 天
|
||||
- 登入成功和失敗都會記在 log(`[ADMIN] ...`)
|
||||
- 被自己鎖住時,執行 `python -m app.admin unlock`
|
||||
|
||||
## Beta 與正式上線
|
||||
|
||||
`.env` 的 `BETA=1`(預設)時,網頁標題顯示「My INMU (Beta)」,小卡右下角加「· Beta」。正式上線時:
|
||||
|
||||
1. `.env` 設 `BETA=0`
|
||||
2. `docker compose up -d`
|
||||
3. `docker compose exec app python -m app.admin reset-progress --yes`
|
||||
|
||||
`reset-progress` 會先把資料庫備份成 `/data/inmu.db.bak-<日期時間>`,再清空所有簽到紀錄和小卡快取。帳號、UID、名稱、大頭貼、自介都保留,Beta 玩家不用重新註冊。
|
||||
|
||||
## 對外部署(inmu.sthkm3.org)
|
||||
|
||||
1. `.env`(`.env.example` 已經是正式環境的值):`PUBLIC_URL=https://inmu.sthkm3.org`、`COOKIE_SECURE=1`
|
||||
2. cloudflared 的 ingress 加一條 `inmu.sthkm3.org → http://localhost:2040`
|
||||
3. 寄信(寄件人 `[email protected]`)。寄信是容器主動連到 SMTP 伺服器,**不經過 tunnel,不用開任何 port**;
|
||||
也**不需要收信**,所以不用 MX、不用 Email Routing。
|
||||
|
||||
用寄信服務(以 Resend 為例,免費方案每天 100 封):
|
||||
1. 註冊 Resend → Domains → Add Domain → 輸入 `inmu.sthkm3.org`
|
||||
2. 把它列出的 DNS 記錄加到 Cloudflare(`sthkm3.org` 這個 zone),通常是:
|
||||
- TXT `resend._domainkey.inmu`(DKIM)
|
||||
- MX 與 TXT `send.inmu`(退信用的子網域與 SPF)
|
||||
|
||||
名稱都和 tunnel 的 `inmu` CNAME 不同,不會衝突。這些記錄都設成 **DNS only**(灰色雲)
|
||||
3. (建議)加 TXT `_dmarc.inmu`:`v=DMARC1; p=none;`
|
||||
4. 等 Resend 顯示 Verified → API Keys 建一把只能寄信(Sending access)的 key
|
||||
5. `.env`:`SMTP_HOST=smtp.resend.com`、`SMTP_PORT=465`、`SMTP_USER=resend`、`SMTP_PASSWORD=<API key>`
|
||||
(以 Resend 後台 SMTP 頁面為準),然後 `docker compose up -d`
|
||||
|
||||
其他會幫網域簽 DKIM 的服務(Amazon SES、Brevo、SMTP2GO 等)做法相同:驗證網域、加 DNS、填 SMTP 設定,程式不用改。
|
||||
|
||||
不建議用 Gmail「以這個地址寄送郵件」別名:要能在 `inmu.sthkm3.org` 收信(MX 和 tunnel 的 CNAME 不能放在同一個名稱),
|
||||
簽名是 gmail.com 容易進垃圾信件,而且 Google 據報將停止對外部網域地址的這項功能。
|
||||
只用 Gmail 帳號本身寄(`SMTP_USER` = Gmail、`SMTP_PASSWORD` = 應用程式密碼)可以當臨時方案,但寄件人會變成那個 Gmail。
|
||||
|
||||
備份:volume `myinmu_inmu-data` 裡的 `inmu.db`、`avatars/`、`submissions/`(`cards/` 是快取,可以刪),以及 `image/`。
|
||||
|
||||
## API
|
||||
|
||||
會改資料的 `/api` 請求要帶 header `X-INMU: 1`(防 CSRF);用 `Authorization: Bearer <token>` 的客戶端不需要。
|
||||
錯誤一律回 `{"detail": "<code>"}`。
|
||||
|
||||
| 方法 路徑 | 說明 |
|
||||
|---|---|
|
||||
| `POST /api/auth/request-code {email, lang}` | 寄 6 碼,5 分鐘有效;同信箱 60 秒一次、同 IP 10 分鐘 10 次 |
|
||||
| `POST /api/auth/verify {email, code, lang}` | 錯 5 次作廢。沒有帳號就自動註冊。回傳 `{token, user}` 並設定 HttpOnly cookie |
|
||||
| `POST /api/auth/logout` | 登出 |
|
||||
| `GET /api/me`、`PATCH /api/me {display_name?, bio_md?, lang?}` | 名稱 1–32 字、自介 2000 字 |
|
||||
| `PUT /api/me/avatar`(multipart `file`) | 上限 5MB,裁成 1024×1024 WebP |
|
||||
| `POST /api/checkin`、`GET /api/checkin/today` | `{day, checked_in, already?, total_days, streak, next_reset, card_url?, share_url?, share_text?}` |
|
||||
| `GET /api/users/{uid}?lang=` | 公開個人資料(`bio_html` 已在伺服器端轉好,原始 HTML 會被跳脫) |
|
||||
| `POST /api/markdown {md}` | 自介預覽 |
|
||||
| `GET /card/{uid}/{day}.png` | 小卡(第一次請求時才畫,快取在 `/data/cards/`) |
|
||||
| `GET /c/{uid}/{day}` | 分享頁(`og:image`) |
|
||||
| `GET /avatars/{uid}.webp`、`GET /healthz` | |
|
||||
| `POST /api/submissions`(multipart `file`) | 投稿迷因圖,每天 5 張(超過回 429 `quota_exceeded`) |
|
||||
| `GET /api/submissions` | `{used, limit, remaining, items: [{id, status, created_at, image_url}]}`,自己最近 30 筆 |
|
||||
| `GET /api/submissions/{id}/image` | 只有上傳者本人和管理員看得到 |
|
||||
| `GET /api/admin/submissions` | 管理員:最舊的一張待審 `{item, pending}` |
|
||||
| `POST /api/admin/submissions/{id}/approve`、`/reject` | 管理員:同意/拒絕(已審過回 409 `already_reviewed`) |
|
||||
|
||||
每日分界是**台灣時間 04:00**(程式固定用 `Asia/Taipei`;容器的 `TZ` 也設成台灣,只影響 log 時間)。
|
||||
`next_reset` 是帶時區的 ISO 時間,網頁會換算成裝置的當地時間顯示。
|
||||
|
||||
## 開發
|
||||
|
||||
```
|
||||
cd server
|
||||
python -m venv .venv
|
||||
.venv/Scripts/python -m pip install -r requirements-dev.txt # Windows
|
||||
.venv/Scripts/python -m pytest -q
|
||||
DATA_DIR=../data .venv/Scripts/python -m uvicorn app.main:app --port 2040 --reload
|
||||
```
|
||||
|
||||
本機沒有 Noto Sans CJK 時,小卡會改用 Windows 內建字型(`FONT_REGULAR` / `FONT_BOLD` 可以指定)。
|
||||
|
||||
## 檔案
|
||||
|
||||
```
|
||||
server/app/
|
||||
main.py 路由、CSRF header 檢查、靜態檔
|
||||
auth.py 驗證碼登入、session
|
||||
users.py UID 給號、個人資料、大頭貼、自介 Markdown
|
||||
checkin.py 簽到、累計 / 連續天數、抽梗圖
|
||||
submissions.py 使用者投稿迷因圖、管理員審核
|
||||
card.py 畫小卡
|
||||
share.py 分享頁
|
||||
admin.py 管理指令
|
||||
mailer.py Gmail SMTP(沿用 RhyculatorServer/Verify_email)
|
||||
i18n/ 信件、小卡、頭銜文字
|
||||
web/ 網站(純 HTML/JS);i18n/ 是介面文字,media/ 是簽到按鈕的圖和音效
|
||||
image/ 梗圖(管理員同意的投稿也會寫進來)
|
||||
icon/ 圖標與簽到按鈕的原圖(不打包進 Docker)
|
||||
```
|
||||
@@ -0,0 +1,36 @@
|
||||
# My INMU:簽到伺服器(FastAPI + SQLite)與網站
|
||||
# 用法:複製 .env.example 成 .env 後執行 docker compose up -d --build
|
||||
|
||||
name: myinmu
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: server/Dockerfile
|
||||
environment:
|
||||
PUBLIC_URL: ${PUBLIC_URL:-http://127.0.0.1:2040}
|
||||
COOKIE_SECURE: ${COOKIE_SECURE:-0}
|
||||
BETA: ${BETA:-1} # 1 = 網頁標題與小卡標示 Beta;正式上線設 0
|
||||
SMTP_HOST: ${SMTP_HOST:-smtp.gmail.com}
|
||||
SMTP_PORT: ${SMTP_PORT:-465}
|
||||
SMTP_USER: ${SMTP_USER:-}
|
||||
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
|
||||
MAIL_FROM: ${MAIL_FROM:[email protected]}
|
||||
ADMIN_LOGIN: ${ADMIN_LOGIN:-}
|
||||
ADMIN_TOTP: ${ADMIN_TOTP:-}
|
||||
TZ: Asia/Taipei # 容器時區(log、date);換日邏輯在程式裡固定用台灣時間 04:00
|
||||
volumes:
|
||||
- inmu-data:/data # inmu.db、avatars/、cards/
|
||||
- ./image:/memes # 迷因圖放在 image/;管理員同意的投稿也會寫進這裡(inmu_<n>.jpg)
|
||||
ports:
|
||||
- "127.0.0.1:${PORT:-2040}:2040"
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:2040/healthz')"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
volumes:
|
||||
inmu-data:
|
||||
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 957 KiB |
@@ -0,0 +1,22 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
|
||||
# Pillow 畫小卡需要中日韓字型(NotoSansCJK-Regular/Bold.ttc)
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends fonts-noto-cjk \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY server/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY server/app ./app
|
||||
COPY web ./web
|
||||
|
||||
ENV DATA_DIR=/data MEME_DIR=/memes WEB_DIR=/app/web
|
||||
EXPOSE 2040
|
||||
|
||||
# SQLite 與記憶體裡的限流都假設只有一個 worker
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "2040", "--workers", "1"]
|
||||
@@ -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()
|
||||
@@ -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"}
|
||||
@@ -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"})
|
||||
@@ -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())
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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")
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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": "自分もログインする"
|
||||
}
|
||||
@@ -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": "나도 출석하기"
|
||||
}
|
||||
@@ -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": "我也要签到"
|
||||
}
|
||||
@@ -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": "我也要簽到"
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
@@ -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")),
|
||||
)
|
||||
@@ -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)}
|
||||
@@ -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
|
||||
@@ -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)}"
|
||||
@@ -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)}
|
||||
@@ -0,0 +1,3 @@
|
||||
-r requirements.txt
|
||||
pytest==8.*
|
||||
httpx
|
||||
@@ -0,0 +1,6 @@
|
||||
fastapi==0.115.*
|
||||
uvicorn[standard]==0.32.*
|
||||
pillow==11.*
|
||||
python-multipart==0.0.*
|
||||
markdown-it-py==3.*
|
||||
tzdata
|
||||
@@ -0,0 +1,65 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
|
||||
from app import auth, clock, config, mailer, totp
|
||||
|
||||
ADMIN_LOGIN = "sthkm3"
|
||||
ADMIN_TOTP = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" # 測試用密鑰
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.value = datetime(2026, 11, 21, 3, 0, tzinfo=timezone.utc) # 台灣時間 11:00
|
||||
|
||||
def set(self, iso: str):
|
||||
self.value = datetime.fromisoformat(iso).astimezone(timezone.utc)
|
||||
|
||||
def __call__(self):
|
||||
return self.value
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_clock(monkeypatch):
|
||||
c = Clock()
|
||||
monkeypatch.setattr(clock, "now", c)
|
||||
return c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sent(monkeypatch):
|
||||
"""攔截寄信,回傳 {email: 最後一個驗證碼}。"""
|
||||
box = {}
|
||||
monkeypatch.setattr(mailer, "send_code", lambda email, code, lang: box.__setitem__(email, code))
|
||||
return box
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(tmp_path, monkeypatch, fake_clock, sent):
|
||||
memes = tmp_path / "memes"
|
||||
memes.mkdir()
|
||||
Image.new("RGB", (640, 480), (200, 80, 80)).save(memes / "test.png")
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path / "data")
|
||||
monkeypatch.setattr(config, "MEME_DIR", memes)
|
||||
monkeypatch.setattr(config, "ADMIN_LOGIN", ADMIN_LOGIN)
|
||||
monkeypatch.setattr(config, "ADMIN_TOTP", ADMIN_TOTP)
|
||||
auth._ip_hits.clear()
|
||||
from app.main import app
|
||||
with TestClient(app, headers={"X-INMU": "1"}) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def login(client, sent, email="[email protected]", lang="zh-TW"):
|
||||
r = client.post("/api/auth/request-code", json={"email": email, "lang": lang})
|
||||
assert r.status_code == 200, r.text
|
||||
r = client.post("/api/auth/verify", json={"email": email, "code": sent[email.lower()], "lang": lang})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def admin_code(fake_clock, offset_steps=0):
|
||||
"""用假時鐘算出管理員的 TOTP。"""
|
||||
step = int(fake_clock.value.timestamp()) // totp.PERIOD + offset_steps
|
||||
return totp.code_at(totp.decode_secret(ADMIN_TOTP), step)
|
||||
@@ -0,0 +1,129 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import admin, config, db, totp
|
||||
|
||||
from .conftest import ADMIN_LOGIN, admin_code, login
|
||||
|
||||
|
||||
def admin_login(client, code, login_name=ADMIN_LOGIN):
|
||||
return client.post("/api/auth/verify", json={"email": login_name, "code": code})
|
||||
|
||||
|
||||
def test_totp_rfc6238_vector():
|
||||
# RFC 6238 附錄 B(SHA1,密鑰 "12345678901234567890"),取後 6 碼
|
||||
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
|
||||
assert totp.code_at(totp.decode_secret(secret), 59 // 30) == "287082"
|
||||
assert totp.code_at(totp.decode_secret(secret), 1111111109 // 30) == "081804"
|
||||
assert totp.verify(secret, "287082", 59) == 1
|
||||
assert totp.verify(secret, "287082", 59 + 30) == 1 # 前一個時間窗也接受
|
||||
assert totp.verify(secret, "287082", 59 + 90) is None # 太舊
|
||||
assert totp.verify(secret, "abc", 59) is None
|
||||
|
||||
|
||||
def test_admin_request_code_does_not_send(client, sent):
|
||||
r = client.post("/api/auth/request-code", json={"email": "STHKM3"})
|
||||
assert r.status_code == 200 and r.json()["status"] == "sent"
|
||||
assert sent == {}
|
||||
|
||||
|
||||
def test_admin_login(client, fake_clock):
|
||||
r = admin_login(client, admin_code(fake_clock))
|
||||
assert r.status_code == 200, r.text
|
||||
user = r.json()["user"]
|
||||
assert user["uid"] == 0 and user["uid_str"] == "00000000"
|
||||
assert user["is_admin"] is True and user["uid_tier"] == "admin" and "title" not in user
|
||||
assert "Max-Age=604800" in r.headers["set-cookie"] # 管理員 session 7 天
|
||||
me = client.get("/api/me").json()
|
||||
assert me["is_admin"] is True
|
||||
# 管理員也能簽到,小卡會畫頭銜
|
||||
c = client.post("/api/checkin").json()
|
||||
assert c["card_url"].startswith("/card/00000000/")
|
||||
assert client.get(c["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_admin_code_single_use(client, fake_clock):
|
||||
code = admin_code(fake_clock)
|
||||
assert admin_login(client, code).status_code == 200
|
||||
# 登出後馬上用同一組碼再登入:拒絕,但不算失敗,重試幾次都不會鎖
|
||||
for _ in range(5):
|
||||
r = admin_login(client, code)
|
||||
assert r.status_code == 400 and r.json()["detail"] == "code_used"
|
||||
# 前一個時間窗的碼也不能用(時間步不能倒退)
|
||||
assert admin_login(client, admin_code(fake_clock, -1)).json()["detail"] == "code_used"
|
||||
conn = db.connect()
|
||||
assert db.get_meta(conn, "admin_fails") == 0 and db.get_meta(conn, "admin_lock_until") == 0
|
||||
# Aegis 換下一組碼就能登入
|
||||
fake_clock.value += timedelta(seconds=30)
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 200
|
||||
|
||||
|
||||
def test_admin_lockout(client, fake_clock):
|
||||
good = admin_code(fake_clock)
|
||||
wrong = "000000" if good != "000000" else "111111"
|
||||
assert admin_login(client, wrong).json()["detail"] == "wrong_code"
|
||||
assert admin_login(client, wrong).json()["detail"] == "wrong_code"
|
||||
r = admin_login(client, wrong) # 第 3 次就鎖
|
||||
assert r.status_code == 429
|
||||
# 鎖定中,正確的碼也不行
|
||||
assert admin_login(client, good).status_code == 429
|
||||
|
||||
# 15 分鐘後解鎖
|
||||
fake_clock.value += timedelta(minutes=15)
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 200
|
||||
|
||||
|
||||
def test_admin_lock_doubles(client, fake_clock):
|
||||
for minutes in (15, 30, 60):
|
||||
for _ in range(3):
|
||||
admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111")
|
||||
fake_clock.value += timedelta(minutes=minutes) - timedelta(seconds=1)
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 429
|
||||
fake_clock.value += timedelta(seconds=1)
|
||||
conn = db.connect()
|
||||
assert db.get_meta(conn, "admin_lock_level") == 3
|
||||
|
||||
|
||||
def test_admin_unlock_command(client, fake_clock):
|
||||
for _ in range(3):
|
||||
admin_login(client, "000000" if admin_code(fake_clock) != "000000" else "111111")
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 429
|
||||
admin.main(["unlock"])
|
||||
assert admin_login(client, admin_code(fake_clock)).status_code == 200
|
||||
|
||||
|
||||
def test_admin_disabled_without_secret(client, sent, fake_clock, monkeypatch):
|
||||
monkeypatch.setattr(config, "ADMIN_TOTP", "")
|
||||
db.init()
|
||||
r = client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN})
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_email"
|
||||
assert admin_login(client, admin_code(fake_clock)).json()["detail"] == "invalid_email"
|
||||
|
||||
|
||||
def test_admin_login_renamed(client, fake_clock, monkeypatch):
|
||||
monkeypatch.setattr(config, "ADMIN_LOGIN", "boss")
|
||||
db.init()
|
||||
assert admin_login(client, admin_code(fake_clock), "sthkm3").json()["detail"] == "invalid_email"
|
||||
r = admin_login(client, admin_code(fake_clock), "boss")
|
||||
assert r.status_code == 200 and r.json()["user"]["uid"] == 0
|
||||
|
||||
|
||||
def test_admin_login_clash_disables(client, sent, fake_clock, monkeypatch):
|
||||
login(client, sent, "[email protected]")
|
||||
monkeypatch.setattr(config, "ADMIN_LOGIN", "[email protected]")
|
||||
db.init()
|
||||
assert db.admin_ok is False
|
||||
|
||||
|
||||
def test_totp_uri(capsys, client):
|
||||
admin.main(["totp-uri"])
|
||||
last = capsys.readouterr().out.strip().splitlines()[-1]
|
||||
assert last.startswith("otpauth://totp/My%20INMU%3Asthkm3?secret=")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("uid", ["0", "-1"])
|
||||
def test_cannot_grant_admin_uid(client, sent, uid):
|
||||
login(client, sent)
|
||||
with pytest.raises(SystemExit):
|
||||
admin.main(["grant-uid", "[email protected]", uid])
|
||||
@@ -0,0 +1,260 @@
|
||||
import io
|
||||
from datetime import timedelta
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from PIL import Image
|
||||
|
||||
from app import db
|
||||
from app.main import app
|
||||
|
||||
from .conftest import login
|
||||
|
||||
|
||||
# ---------- 登入 ----------
|
||||
|
||||
def test_register_and_login(client, sent):
|
||||
data = login(client, sent, "[email protected]")
|
||||
assert data["user"]["uid"] == 1
|
||||
assert data["user"]["uid_str"] == "00000001"
|
||||
assert data["user"]["display_name"] == "INMU_1"
|
||||
assert data["user"]["is_admin"] is False
|
||||
assert data["user"]["email"] == "[email protected]"
|
||||
assert data["token"]
|
||||
assert client.get("/api/me").json()["uid"] == 1
|
||||
|
||||
# 同一個信箱再登入一次是同一個帳號
|
||||
client.cookies.clear()
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"}) # 別人註冊不影響
|
||||
assert login(client, sent, "[email protected]")["user"]["uid"] == 1
|
||||
|
||||
|
||||
def test_bearer_token(client, sent):
|
||||
token = login(client, sent)["token"]
|
||||
client.cookies.clear()
|
||||
assert client.get("/api/me").status_code == 401
|
||||
# Bearer 不需要 X-INMU
|
||||
bare = TestClient(app)
|
||||
r = bare.post("/api/checkin", headers={"Authorization": f"Bearer {token}"})
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_csrf_header_required(client, sent):
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin", headers={"X-INMU": ""})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_resend_limit(client, sent, fake_clock):
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
r = client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
assert r.status_code == 429
|
||||
fake_clock.value += timedelta(seconds=61)
|
||||
assert client.post("/api/auth/request-code", json={"email": "[email protected]"}).status_code == 200
|
||||
|
||||
|
||||
def test_wrong_code_five_times(client, sent):
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
right = sent["[email protected]"]
|
||||
wrong = "000000" if right != "000000" else "111111"
|
||||
for _ in range(4):
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": wrong})
|
||||
assert r.json()["detail"] == "wrong_code"
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": wrong})
|
||||
assert r.json()["detail"] == "expired"
|
||||
# 作廢後正確的碼也不能用
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": right})
|
||||
assert r.json()["detail"] == "not_requested"
|
||||
|
||||
|
||||
def test_code_expires(client, sent, fake_clock):
|
||||
client.post("/api/auth/request-code", json={"email": "[email protected]"})
|
||||
fake_clock.value += timedelta(minutes=5, seconds=1)
|
||||
r = client.post("/api/auth/verify", json={"email": "[email protected]", "code": sent["[email protected]"]})
|
||||
assert r.json()["detail"] == "expired"
|
||||
|
||||
|
||||
def test_invalid_email(client):
|
||||
r = client.post("/api/auth/request-code", json={"email": "not-an-email"})
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_email"
|
||||
|
||||
|
||||
def test_logout(client, sent):
|
||||
login(client, sent)
|
||||
assert client.post("/api/auth/logout").status_code == 200
|
||||
client.cookies.clear()
|
||||
assert client.get("/api/me").status_code == 401
|
||||
|
||||
|
||||
# ---------- 簽到 ----------
|
||||
|
||||
def test_checkin_once_per_jst_day(client, sent, fake_clock):
|
||||
login(client, sent)
|
||||
fake_clock.set("2026-11-21T12:00:00+08:00")
|
||||
r = client.post("/api/checkin").json()
|
||||
assert r["already"] is False and r["total_days"] == 1 and r["streak"] == 1
|
||||
assert r["day"] == "2026-11-21"
|
||||
assert r["card_url"] == "/card/00000001/2026-11-21.png"
|
||||
assert r["share_url"].endswith("/c/00000001/2026-11-21")
|
||||
|
||||
r = client.post("/api/checkin").json()
|
||||
assert r["already"] is True and r["total_days"] == 1
|
||||
|
||||
# 台灣時間隔天 03:59 還算同一天
|
||||
fake_clock.set("2026-11-22T03:59:59+08:00")
|
||||
assert client.post("/api/checkin").json()["already"] is True
|
||||
|
||||
# 日本時間 00:00 換日
|
||||
fake_clock.set("2026-11-22T04:00:00+08:00")
|
||||
r = client.post("/api/checkin").json()
|
||||
assert r["already"] is False and r["total_days"] == 2 and r["streak"] == 2
|
||||
|
||||
|
||||
def test_streak_breaks(client, sent, fake_clock):
|
||||
login(client, sent)
|
||||
for day in ("2026-11-01", "2026-11-02", "2026-11-04"):
|
||||
fake_clock.set(f"{day}T09:00:00+08:00")
|
||||
client.post("/api/checkin")
|
||||
r = client.get("/api/checkin/today").json()
|
||||
assert r["total_days"] == 3 and r["streak"] == 1
|
||||
|
||||
# 隔天還沒簽到時,連續天數保留昨天的紀錄
|
||||
fake_clock.set("2026-11-05T09:00:00+08:00")
|
||||
r = client.get("/api/checkin/today").json()
|
||||
assert r["checked_in"] is False and r["streak"] == 1
|
||||
assert r["next_reset"] == "2026-11-06T04:00:00+08:00"
|
||||
# 凌晨 02:00 時還沒換日,下次換日是當天 04:00
|
||||
fake_clock.set("2026-11-06T02:00:00+08:00")
|
||||
r = client.get("/api/checkin/today").json()
|
||||
assert r["day"] == "2026-11-05" and r["next_reset"] == "2026-11-06T04:00:00+08:00"
|
||||
|
||||
|
||||
def test_checkin_requires_login(client):
|
||||
assert client.post("/api/checkin").status_code == 401
|
||||
|
||||
|
||||
# ---------- UID ----------
|
||||
|
||||
def test_uid_sequence_skips_granted(client, sent):
|
||||
from app import admin
|
||||
|
||||
login(client, sent, "[email protected]")
|
||||
admin.main(["grant-uid", "[email protected]", "99999999"])
|
||||
# 下一位仍然拿到正常的下一號
|
||||
assert login(client, sent, "[email protected]")["user"]["uid"] == 2
|
||||
|
||||
|
||||
def test_uid_tier_by_substring(client, sent):
|
||||
conn = db.connect()
|
||||
conn.execute("UPDATE meta SET value = 114514 WHERE key = 'next_uid'")
|
||||
u = login(client, sent, "[email protected]")["user"]
|
||||
assert u["uid_str"] == "00114514" and u["uid_tier"] == "114514"
|
||||
assert login(client, sent, "[email protected]")["user"]["uid_tier"] is None # 00114515
|
||||
conn.execute("UPDATE meta SET value = 51919810 WHERE key = 'next_uid'")
|
||||
u = login(client, sent, "[email protected]")["user"]
|
||||
assert u["uid_str"] == "51919810" and u["uid_tier"] == "1919810"
|
||||
assert client.get("/api/users/51919810").json()["uid_tier"] == "1919810"
|
||||
# 小卡也能正常產生(會畫頭銜)
|
||||
client.cookies.clear()
|
||||
login(client, sent, "[email protected]")
|
||||
r = client.post("/api/checkin").json()
|
||||
assert client.get(r["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_grant_uid_range(client, sent):
|
||||
import pytest
|
||||
from app import admin
|
||||
|
||||
login(client, sent, "[email protected]")
|
||||
for bad in ("0", "100000000"):
|
||||
with pytest.raises(SystemExit):
|
||||
admin.main(["grant-uid", "[email protected]", bad])
|
||||
|
||||
|
||||
def test_granted_uid_keeps_checkins(client, sent):
|
||||
from app import admin
|
||||
|
||||
login(client, sent, "[email protected]")
|
||||
client.post("/api/checkin")
|
||||
admin.main(["grant-uid", "[email protected]", "114514"])
|
||||
me = client.get("/api/me").json() # session 也跟著改 uid
|
||||
assert me["uid_str"] == "00114514" and me["total_days"] == 1
|
||||
|
||||
|
||||
def test_old_default_name_migrated(client, sent):
|
||||
login(client, sent)
|
||||
conn = db.connect()
|
||||
conn.execute("UPDATE users SET display_name = 'INMU1' WHERE uid = 1")
|
||||
db.init()
|
||||
assert client.get("/api/me").json()["display_name"] == "INMU_1"
|
||||
|
||||
|
||||
# ---------- 個人資料 ----------
|
||||
|
||||
def _png(w, h, color=(10, 200, 30)):
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), color).save(buf, "PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_avatar_resized(client, sent):
|
||||
login(client, sent)
|
||||
r = client.put("/api/me/avatar", files={"file": ("a.png", _png(1600, 900), "image/png")})
|
||||
assert r.status_code == 200, r.text
|
||||
url = r.json()["avatar_url"]
|
||||
img = Image.open(io.BytesIO(client.get(url).content))
|
||||
assert img.format == "WEBP" and img.size == (1024, 1024)
|
||||
|
||||
|
||||
def test_avatar_rejects_non_image(client, sent):
|
||||
login(client, sent)
|
||||
r = client.put("/api/me/avatar", files={"file": ("a.png", b"<script>alert(1)</script>", "image/png")})
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
|
||||
|
||||
|
||||
def test_profile_patch_and_markdown_escape(client, sent):
|
||||
login(client, sent)
|
||||
r = client.patch("/api/me", json={"display_name": " 野獸\n先輩 ", "bio_md": "**hi** <script>x</script>"})
|
||||
data = r.json()
|
||||
assert data["display_name"] == "野獸先輩"
|
||||
assert "<strong>hi</strong>" in data["bio_html"]
|
||||
assert "<script>" not in data["bio_html"]
|
||||
assert client.patch("/api/me", json={"display_name": "x" * 33}).json()["detail"] == "name_invalid"
|
||||
assert client.patch("/api/me", json={"bio_md": "x" * 2001}).json()["detail"] == "bio_too_long"
|
||||
assert client.patch("/api/me", json={"lang": "fr"}).json()["detail"] == "invalid_lang"
|
||||
|
||||
|
||||
def test_public_profile_hides_email(client, sent):
|
||||
login(client, sent)
|
||||
data = client.get("/api/users/1").json()
|
||||
assert "email" not in data and data["uid"] == 1
|
||||
assert client.get("/api/users/999").status_code == 404
|
||||
|
||||
|
||||
# ---------- 小卡與分享 ----------
|
||||
|
||||
def test_card_and_share_page(client, sent):
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin").json()
|
||||
png = client.get(r["card_url"])
|
||||
assert png.status_code == 200
|
||||
img = Image.open(io.BytesIO(png.content))
|
||||
assert img.size == (1080, 1350)
|
||||
|
||||
page = client.get(f"/c/1/{r['day']}")
|
||||
assert page.status_code == 200 and 'property="og:image"' in page.text
|
||||
assert client.get("/card/1/2000-01-01.png").status_code == 404
|
||||
assert client.get("/c/1/not-a-day").status_code == 404
|
||||
|
||||
|
||||
def test_card_rerendered_after_rename(client, sent):
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin").json()
|
||||
first = client.get(r["card_url"]).content
|
||||
client.patch("/api/me", json={"display_name": "New Name"})
|
||||
assert client.get(r["card_url"]).content != first
|
||||
|
||||
|
||||
def test_index_served(client):
|
||||
assert client.get("/").status_code == 200
|
||||
assert client.get("/u/1").status_code == 200
|
||||
assert client.get("/healthz").json() == {"status": "ok"}
|
||||
@@ -0,0 +1,60 @@
|
||||
import pytest
|
||||
|
||||
from app import admin, config, db
|
||||
from app.titles import uid_tier
|
||||
|
||||
from .conftest import login
|
||||
|
||||
|
||||
@pytest.mark.parametrize("uid,tier", [
|
||||
(0, "admin"), (114514, "114514"), (51919810, "1919810"), (1919810, "1919810"),
|
||||
(11451400, "114514"), (1, None), (11451, None), (99999999, None),
|
||||
])
|
||||
def test_uid_tier(uid, tier):
|
||||
assert uid_tier(uid) == tier
|
||||
|
||||
|
||||
@pytest.mark.parametrize("beta", [True, False])
|
||||
def test_beta_switch(client, sent, monkeypatch, beta):
|
||||
monkeypatch.setattr(config, "BETA", beta)
|
||||
html = client.get("/").text
|
||||
assert ("(Beta)" in html) is beta
|
||||
assert "<!--BETA" not in html
|
||||
login(client, sent)
|
||||
r = client.post("/api/checkin").json()
|
||||
page = client.get(f"/c/00000001/{r['day']}").text
|
||||
assert ('content="My INMU (Beta)"' in page) is beta
|
||||
assert client.get(r["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_reset_progress(client, sent, capsys):
|
||||
login(client, sent)
|
||||
client.patch("/api/me", json={"display_name": "Beta tester"})
|
||||
first = client.post("/api/checkin").json()
|
||||
assert client.get(first["card_url"]).status_code == 200
|
||||
|
||||
# 沒有 --yes 不做任何事
|
||||
admin.main(["reset-progress"])
|
||||
assert client.get("/api/checkin/today").json()["total_days"] == 1
|
||||
|
||||
admin.main(["reset-progress", "--yes"])
|
||||
today = client.get("/api/checkin/today").json()
|
||||
assert today["total_days"] == 0 and today["checked_in"] is False
|
||||
me = client.get("/api/me").json() # 帳號、名稱、session 都還在
|
||||
assert me["display_name"] == "Beta tester" and me["uid_str"] == "00000001"
|
||||
assert list(config.DATA_DIR.glob("inmu.db.bak-*"))
|
||||
assert not any((config.DATA_DIR / "cards").iterdir())
|
||||
# 同一天可以重新簽到
|
||||
again = client.post("/api/checkin").json()
|
||||
assert again["already"] is False and again["total_days"] == 1
|
||||
assert db.connect().execute("SELECT value FROM meta WHERE key = 'next_uid'").fetchone()[0] == 2
|
||||
|
||||
|
||||
def test_assets_versioned_and_not_cached_by_proxies(client):
|
||||
html = client.get("/").text
|
||||
assert "__ASSET_VERSION__" not in html
|
||||
assert '/assets/app.js?v=' in html and '/assets/style.css?v=' in html
|
||||
r = client.get("/assets/app.js")
|
||||
assert r.headers["cache-control"] == "no-cache"
|
||||
etag = r.headers["etag"]
|
||||
assert client.get("/assets/app.js", headers={"If-None-Match": etag}).status_code == 304
|
||||
@@ -0,0 +1,59 @@
|
||||
from app import config, mailer
|
||||
|
||||
|
||||
class FakeSMTP:
|
||||
instances = []
|
||||
|
||||
def __init__(self, host, port, timeout=None, context=None):
|
||||
self.host, self.port, self.sent, self.tls = host, port, [], False
|
||||
FakeSMTP.instances.append(self)
|
||||
|
||||
def starttls(self, context=None):
|
||||
self.tls = True
|
||||
|
||||
def login(self, user, password):
|
||||
self.login_as = (user, password)
|
||||
|
||||
def send_message(self, msg):
|
||||
self.sent.append(msg)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
|
||||
def _setup(monkeypatch, port):
|
||||
FakeSMTP.instances.clear()
|
||||
monkeypatch.setattr(mailer.smtplib, "SMTP_SSL", FakeSMTP)
|
||||
monkeypatch.setattr(mailer.smtplib, "SMTP", FakeSMTP)
|
||||
monkeypatch.setattr(config, "SMTP_HOST", "smtp.example.com")
|
||||
monkeypatch.setattr(config, "SMTP_PORT", port)
|
||||
monkeypatch.setattr(config, "SMTP_USER", "[email protected]")
|
||||
monkeypatch.setattr(config, "SMTP_PASSWORD", "app-password")
|
||||
monkeypatch.setattr(config, "MAIL_FROM", "[email protected]")
|
||||
|
||||
|
||||
def test_sends_from_noreply(monkeypatch):
|
||||
_setup(monkeypatch, 465)
|
||||
mailer.send_code("[email protected]", "123456", "ja")
|
||||
smtp = FakeSMTP.instances[0]
|
||||
assert (smtp.host, smtp.port, smtp.tls) == ("smtp.example.com", 465, False)
|
||||
msg = smtp.sent[0]
|
||||
assert msg["From"] == "My INMU <[email protected]>"
|
||||
assert msg["To"] == "[email protected]"
|
||||
assert "123456" in msg["Subject"] and "認証コード" in msg["Subject"]
|
||||
assert msg["Message-ID"].endswith("@inmu.sthkm3.org>")
|
||||
|
||||
|
||||
def test_starttls_on_587(monkeypatch):
|
||||
_setup(monkeypatch, 587)
|
||||
mailer.send_code("[email protected]", "123456", "en")
|
||||
assert FakeSMTP.instances[0].tls is True
|
||||
|
||||
|
||||
def test_dev_mode_prints(monkeypatch, capsys):
|
||||
monkeypatch.setattr(config, "SMTP_USER", "")
|
||||
mailer.send_code("[email protected]", "654321", "en")
|
||||
assert "654321" in capsys.readouterr().out
|
||||
@@ -0,0 +1,178 @@
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app import admin, checkin, config, db
|
||||
|
||||
from .conftest import ADMIN_LOGIN, admin_code, login
|
||||
|
||||
|
||||
def _img(fmt="PNG", color=(10, 200, 30), size=(300, 200), **kw):
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", size, color).save(buf, fmt, **kw)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def upload(client, token, data=None, name="a.png"):
|
||||
return client.post("/api/submissions", headers=bearer(token),
|
||||
files={"file": (name, data or _img(), "image/png")})
|
||||
|
||||
|
||||
def admin_token(client, fake_clock):
|
||||
r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock)})
|
||||
assert r.status_code == 200, r.text
|
||||
return r.json()["token"]
|
||||
|
||||
|
||||
def test_upload_and_daily_quota(client, sent, fake_clock):
|
||||
tok = login(client, sent)["token"]
|
||||
r = upload(client, tok)
|
||||
assert r.status_code == 200, r.text
|
||||
data = r.json()
|
||||
assert data["item"]["status"] == "pending" and data["remaining"] == 4 and data["limit"] == 5
|
||||
for _ in range(4):
|
||||
assert upload(client, tok).status_code == 200
|
||||
r = upload(client, tok)
|
||||
assert r.status_code == 429 and r.json()["detail"] == "quota_exceeded"
|
||||
|
||||
# 台灣時間隔天 03:59 還是同一天,04:00 才重置
|
||||
fake_clock.set("2026-11-22T03:59:00+08:00")
|
||||
assert upload(client, tok).status_code == 429
|
||||
fake_clock.set("2026-11-22T04:00:00+08:00")
|
||||
assert upload(client, tok).json()["remaining"] == 4
|
||||
|
||||
mine = client.get("/api/submissions", headers=bearer(tok)).json()
|
||||
assert mine["used"] == 1 and len(mine["items"]) == 6
|
||||
|
||||
|
||||
def test_rejected_still_counts(client, sent, fake_clock):
|
||||
tok = login(client, sent)["token"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
for _ in range(5):
|
||||
sid = upload(client, tok).json()["item"]["id"]
|
||||
assert client.post(f"/api/admin/submissions/{sid}/reject", headers=bearer(adm)).status_code == 200
|
||||
assert upload(client, tok).json()["detail"] == "quota_exceeded"
|
||||
|
||||
|
||||
def test_upload_validation(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
r = upload(client, tok, b"<script>alert(1)</script>")
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
|
||||
r = upload(client, tok, b"x" * (config.SUBMIT_MAX_BYTES + 1))
|
||||
assert r.status_code == 413 and r.json()["detail"] == "file_too_large"
|
||||
# 失敗的不算額度
|
||||
assert client.get("/api/submissions", headers=bearer(tok)).json()["used"] == 0
|
||||
|
||||
|
||||
def test_upload_strips_exif_and_shrinks(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "SecretCam"
|
||||
item = upload(client, tok, _img("JPEG", size=(4000, 1000), exif=exif), "a.jpg").json()["item"]
|
||||
saved = config.DATA_DIR / "submissions" / f"{item['id']}.jpg"
|
||||
with Image.open(saved) as im:
|
||||
assert im.format == "JPEG" and len(im.getexif()) == 0
|
||||
assert im.size == (2048, 512)
|
||||
|
||||
|
||||
def test_png_with_alpha_stays_png(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGBA", (50, 50), (0, 0, 0, 0)).save(buf, "PNG")
|
||||
item = upload(client, tok, buf.getvalue()).json()["item"]
|
||||
assert (config.DATA_DIR / "submissions" / f"{item['id']}.png").is_file()
|
||||
|
||||
|
||||
def test_permissions(client, sent, fake_clock):
|
||||
a = login(client, sent, "[email protected]")["token"]
|
||||
b = login(client, sent, "[email protected]")["token"]
|
||||
sid = upload(client, a).json()["item"]["id"]
|
||||
url = f"/api/submissions/{sid}/image"
|
||||
assert client.get(url, headers=bearer(a)).status_code == 200
|
||||
assert client.get(url, headers=bearer(b)).status_code == 404 # 別人的投稿當作不存在
|
||||
for method, path in (("get", "/api/admin/submissions"),
|
||||
("post", f"/api/admin/submissions/{sid}/approve"),
|
||||
("post", f"/api/admin/submissions/{sid}/reject")):
|
||||
assert getattr(client, method)(path, headers=bearer(b)).status_code == 403
|
||||
adm = admin_token(client, fake_clock)
|
||||
assert client.get(url, headers=bearer(adm)).status_code == 200
|
||||
assert "pending_reviews" not in client.get("/api/me", headers=bearer(a)).json()
|
||||
assert client.get("/api/me", headers=bearer(adm)).json()["pending_reviews"] == 1
|
||||
|
||||
|
||||
def test_approve_names_like_image_folder(client, sent, fake_clock):
|
||||
for name in ("inmu_0.png", "inmu_7.jpg"):
|
||||
Image.new("RGB", (10, 10)).save(config.MEME_DIR / name)
|
||||
tok = login(client, sent)["token"]
|
||||
first = upload(client, tok).json()["item"]["id"]
|
||||
second = upload(client, tok).json()["item"]["id"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
|
||||
# 一張一張審:先拿到最舊的
|
||||
r = client.get("/api/admin/submissions", headers=bearer(adm)).json()
|
||||
assert r["pending"] == 2 and r["item"]["id"] == first
|
||||
assert r["item"]["uploader"]["uid_str"] == "00000001"
|
||||
|
||||
r = client.post(f"/api/admin/submissions/{first}/approve", headers=bearer(adm))
|
||||
assert r.status_code == 200 and r.json()["meme"] == "inmu_8.jpg" and r.json()["pending"] == 1
|
||||
assert (config.MEME_DIR / "inmu_8.jpg").is_file()
|
||||
assert not (config.DATA_DIR / "submissions" / f"{first}.jpg").exists()
|
||||
assert "inmu_8.jpg" in checkin.list_memes()
|
||||
assert client.post(f"/api/admin/submissions/{first}/approve", headers=bearer(adm)).status_code == 409
|
||||
assert client.post(f"/api/admin/submissions/{first}/reject", headers=bearer(adm)).status_code == 409
|
||||
|
||||
assert client.post(f"/api/admin/submissions/{second}/approve",
|
||||
headers=bearer(adm)).json()["meme"] == "inmu_9.jpg"
|
||||
assert client.get("/api/admin/submissions", headers=bearer(adm)).json() == {"item": None, "pending": 0}
|
||||
# 已同意的投稿,本人還是看得到圖
|
||||
assert client.get(f"/api/submissions/{first}/image", headers=bearer(tok)).status_code == 200
|
||||
# 沒有暫存檔留在迷因資料夾
|
||||
assert not [p for p in config.MEME_DIR.iterdir() if p.name.startswith(".")]
|
||||
|
||||
|
||||
def test_approved_meme_shows_on_card(client, sent, fake_clock, monkeypatch):
|
||||
for p in config.MEME_DIR.iterdir():
|
||||
p.unlink()
|
||||
tok = login(client, sent)["token"]
|
||||
sid = upload(client, tok).json()["item"]["id"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
client.post(f"/api/admin/submissions/{sid}/approve", headers=bearer(adm))
|
||||
assert checkin.list_memes() == ["inmu_0.jpg"]
|
||||
r = client.post("/api/checkin", headers=bearer(tok)).json()
|
||||
conn = db.connect()
|
||||
assert conn.execute("SELECT meme FROM checkins WHERE uid = 1").fetchone()[0] == "inmu_0.jpg"
|
||||
assert client.get(r["card_url"]).status_code == 200
|
||||
|
||||
|
||||
def test_reject_deletes_file(client, sent, fake_clock):
|
||||
tok = login(client, sent)["token"]
|
||||
sid = upload(client, tok).json()["item"]["id"]
|
||||
adm = admin_token(client, fake_clock)
|
||||
assert client.post(f"/api/admin/submissions/{sid}/reject", headers=bearer(adm)).json()["status"] == "rejected"
|
||||
assert not (config.DATA_DIR / "submissions" / f"{sid}.png").exists()
|
||||
item = client.get("/api/submissions", headers=bearer(tok)).json()["items"][0]
|
||||
assert item["status"] == "rejected" and item["image_url"] is None
|
||||
assert client.get(f"/api/submissions/{sid}/image", headers=bearer(tok)).status_code == 404
|
||||
assert client.post("/api/admin/submissions/9999/reject", headers=bearer(adm)).status_code == 404
|
||||
|
||||
|
||||
def test_reset_progress_keeps_submissions(client, sent):
|
||||
tok = login(client, sent)["token"]
|
||||
upload(client, tok)
|
||||
admin.main(["reset-progress", "--yes"])
|
||||
assert client.get("/api/submissions", headers=bearer(tok)).json()["used"] == 1
|
||||
|
||||
|
||||
def test_upload_and_review_pages_served(client):
|
||||
assert client.get("/upload").status_code == 200
|
||||
assert client.get("/review").status_code == 200
|
||||
|
||||
|
||||
def test_media_content_types(client):
|
||||
for path, ctype in (("/assets/media/checkin-0.webp", "image/webp"), ("/assets/media/114514.m4a", "audio/mp4")):
|
||||
r = client.get(path)
|
||||
assert r.status_code == 200 and r.headers["content-type"].startswith(ctype)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""從 icon/ 裡的圖片產生網頁用的圖:
|
||||
|
||||
server/.venv/Scripts/python tools/make_icons.py # 用 icon/ 裡的第一張圖當圖標
|
||||
server/.venv/Scripts/python tools/make_icons.py icon/x.png
|
||||
|
||||
另外把 icon/checkin/0.png、1.png(簽到按鈕按下前/後)縮成 web/media/checkin-0.webp、checkin-1.webp。
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
WEB = ROOT / "web"
|
||||
IMG_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
|
||||
|
||||
src = Path(sys.argv[1]) if len(sys.argv) > 1 else next(
|
||||
p for p in sorted((ROOT / "icon").iterdir()) if p.is_file() and p.suffix.lower() in IMG_EXTS)
|
||||
with Image.open(src) as im:
|
||||
im = ImageOps.exif_transpose(im).convert("RGB")
|
||||
im = ImageOps.fit(im, (512, 512), Image.LANCZOS) # 不是正方形時置中裁切
|
||||
|
||||
im.save(WEB / "favicon.ico", sizes=[(16, 16), (32, 32), (48, 48)])
|
||||
for name, size in {"icon-192.png": 192, "icon-512.png": 512, "apple-touch-icon.png": 180, "logo.png": 64}.items():
|
||||
im.resize((size, size), Image.LANCZOS).save(WEB / name, optimize=True)
|
||||
print(f"{src.name} -> web/favicon.ico, icon-192.png, icon-512.png, apple-touch-icon.png, logo.png")
|
||||
|
||||
# 簽到按鈕的兩張圖:原圖 1280×1280 約 1 MB,縮成 512×512 WebP,手機載入才快
|
||||
faces = ROOT / "icon" / "checkin"
|
||||
(WEB / "media").mkdir(exist_ok=True)
|
||||
for n in ("0", "1"):
|
||||
p = next((faces / f"{n}{ext}" for ext in IMG_EXTS if (faces / f"{n}{ext}").exists()), None)
|
||||
if p is None:
|
||||
continue
|
||||
with Image.open(p) as im:
|
||||
im = ImageOps.fit(ImageOps.exif_transpose(im).convert("RGB"), (512, 512), Image.LANCZOS)
|
||||
out = WEB / "media" / f"checkin-{n}.webp"
|
||||
im.save(out, "WEBP", quality=85, method=6)
|
||||
print(f"checkin/{p.name} -> web/media/{out.name} ({out.stat().st_size // 1024} KB)")
|
||||
@@ -0,0 +1,672 @@
|
||||
// My INMU 前端:純 JS,沒有框架
|
||||
const LANGS = ["zh-TW", "zh-CN", "ja", "ko", "en"];
|
||||
const HTML_LANG = { "zh-TW": "zh-Hant-TW", "zh-CN": "zh-Hans-CN", ja: "ja", ko: "ko", en: "en" };
|
||||
const DEFAULT_AVATAR = "/assets/avatar.svg";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const SITE_TITLE = document.title; // 伺服器會依 BETA 開關加上 (Beta)
|
||||
// 伺服器填入的檔案版本,語言檔網址也帶上,改版後不會拿到快取的舊檔
|
||||
const ASSET_V = document.querySelector('meta[name="asset-version"]')?.content || "";
|
||||
const FACE = [0, 1].map((n) => `/assets/media/checkin-${n}.webp?v=${ASSET_V}`);
|
||||
const SFX_MAX_MS = 1600; // 音效約 1.5 秒;ended 沒觸發(例如播放失敗)時的保險時間
|
||||
const SUBMIT_MAX_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
const state = {
|
||||
lang: "zh-TW",
|
||||
dict: {},
|
||||
me: null,
|
||||
today: null,
|
||||
email: "",
|
||||
cardBust: Date.now(),
|
||||
resendTimer: null,
|
||||
resetTimer: null,
|
||||
};
|
||||
|
||||
// ---------- i18n ----------
|
||||
|
||||
function detectLang() {
|
||||
const saved = localStorage.getItem("lang");
|
||||
if (LANGS.includes(saved)) return saved;
|
||||
for (const raw of navigator.languages || [navigator.language || ""]) {
|
||||
const l = raw.toLowerCase();
|
||||
if (/^zh-(tw|hk|mo|hant)/.test(l)) return "zh-TW";
|
||||
if (l.startsWith("zh")) return "zh-CN";
|
||||
if (l.startsWith("ja")) return "ja";
|
||||
if (l.startsWith("ko")) return "ko";
|
||||
if (l.startsWith("en")) return "en";
|
||||
}
|
||||
return "en";
|
||||
}
|
||||
|
||||
async function loadLang(lang) {
|
||||
const res = await fetch(`/assets/i18n/${lang}.json?v=${ASSET_V}`);
|
||||
state.dict = await res.json();
|
||||
state.lang = lang;
|
||||
localStorage.setItem("lang", lang);
|
||||
document.documentElement.lang = HTML_LANG[lang];
|
||||
$("lang").value = lang;
|
||||
document.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); });
|
||||
document.querySelectorAll("[data-i18n-aria]").forEach((el) => {
|
||||
el.setAttribute("aria-label", t(el.dataset.i18nAria));
|
||||
});
|
||||
}
|
||||
|
||||
function t(key, vars = {}) {
|
||||
let s = state.dict[key] ?? key;
|
||||
for (const [k, v] of Object.entries(vars)) s = s.replaceAll(`{${k}}`, v);
|
||||
return s;
|
||||
}
|
||||
|
||||
// ---------- API ----------
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(code, status) { super(code); this.code = code; this.status = status; }
|
||||
}
|
||||
|
||||
async function api(method, path, body) {
|
||||
const opt = { method, headers: { "X-INMU": "1" }, credentials: "same-origin" };
|
||||
if (body instanceof FormData) {
|
||||
opt.body = body;
|
||||
} else if (body !== undefined) {
|
||||
opt.headers["Content-Type"] = "application/json";
|
||||
opt.body = JSON.stringify(body);
|
||||
}
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(path, opt);
|
||||
} catch {
|
||||
throw new ApiError("network", 0);
|
||||
}
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new ApiError(typeof data.detail === "string" ? data.detail : "unknown", res.status);
|
||||
return data;
|
||||
}
|
||||
|
||||
function errText(e) {
|
||||
const key = `err.${e?.code || "unknown"}`;
|
||||
return key in state.dict ? t(key) : t("err.unknown");
|
||||
}
|
||||
|
||||
function showError(el, e) {
|
||||
if (e) { el.textContent = errText(e); el.hidden = false; } else { el.hidden = true; }
|
||||
}
|
||||
|
||||
function toast(msg) {
|
||||
const el = $("toast");
|
||||
el.textContent = msg;
|
||||
el.hidden = false;
|
||||
clearTimeout(toast.timer);
|
||||
toast.timer = setTimeout(() => { el.hidden = true; }, 2500);
|
||||
}
|
||||
|
||||
// ---------- 側邊欄:登入 / 個人資訊 ----------
|
||||
|
||||
// 特殊序號(管理員、含 114514 / 1919810)用背景色標示,顏色在 style.css 的 .uid.tier-*
|
||||
function showUid(el, user) {
|
||||
el.textContent = `UID ${user.uid_str}`;
|
||||
el.className = user.uid_tier ? `uid tier-${user.uid_tier}` : "uid";
|
||||
}
|
||||
|
||||
function renderSidebar() {
|
||||
const me = state.me;
|
||||
$("auth-box").hidden = !!me;
|
||||
$("me-box").hidden = !me;
|
||||
if (!me) return;
|
||||
$("me-avatar").src = me.avatar_url || DEFAULT_AVATAR;
|
||||
$("me-name").textContent = me.display_name;
|
||||
showUid($("me-uid"), me);
|
||||
$("me-link").href = `/u/${me.uid_str}`;
|
||||
$("review-link").hidden = !me.is_admin;
|
||||
if (me.is_admin) $("review-link").textContent = t("nav.review", { n: me.pending_reviews ?? 0 });
|
||||
}
|
||||
|
||||
function showCodeStep(show) {
|
||||
$("email-form").hidden = show;
|
||||
$("code-form").hidden = !show;
|
||||
showError($("auth-error"), null);
|
||||
if (show) {
|
||||
$("code-sent-msg").textContent = t("auth.sent", { email: state.email });
|
||||
$("code").value = "";
|
||||
$("code").focus();
|
||||
}
|
||||
}
|
||||
|
||||
function startResendCountdown(seconds) {
|
||||
clearInterval(state.resendTimer);
|
||||
const btn = $("resend");
|
||||
let left = seconds;
|
||||
const tick = () => {
|
||||
btn.disabled = left > 0;
|
||||
btn.textContent = left > 0 ? t("auth.resend_wait", { s: left }) : t("auth.resend");
|
||||
if (left-- <= 0) clearInterval(state.resendTimer);
|
||||
};
|
||||
tick();
|
||||
state.resendTimer = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
async function sendCode() {
|
||||
const r = await api("POST", "/api/auth/request-code", { email: state.email, lang: state.lang });
|
||||
showCodeStep(true);
|
||||
startResendCountdown(r.resend_in);
|
||||
}
|
||||
|
||||
async function withBusy(button, fn) {
|
||||
button.disabled = true;
|
||||
try { await fn(); } finally { button.disabled = false; }
|
||||
}
|
||||
|
||||
function bindAuth() {
|
||||
$("email-form").addEventListener("submit", (ev) => {
|
||||
ev.preventDefault();
|
||||
state.email = $("email").value.trim();
|
||||
withBusy(ev.submitter || $("email-form").querySelector("button"), async () => {
|
||||
try { await sendCode(); } catch (e) { showError($("auth-error"), e); }
|
||||
});
|
||||
});
|
||||
|
||||
$("code-form").addEventListener("submit", (ev) => {
|
||||
ev.preventDefault();
|
||||
const code = $("code").value.replace(/\D/g, "");
|
||||
withBusy(ev.submitter || $("code-form").querySelector("button[type=submit]"), async () => {
|
||||
try {
|
||||
const r = await api("POST", "/api/auth/verify", { email: state.email, code, lang: state.lang });
|
||||
state.me = r.user;
|
||||
clearInterval(state.resendTimer);
|
||||
showCodeStep(false);
|
||||
$("email").value = "";
|
||||
if (r.user.lang !== state.lang) await loadLang(r.user.lang);
|
||||
renderSidebar();
|
||||
closeMenu();
|
||||
await route();
|
||||
} catch (e) {
|
||||
showError($("auth-error"), e);
|
||||
if (e.code === "expired" || e.code === "not_requested") $("code").value = "";
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$("resend").addEventListener("click", async () => {
|
||||
try { await sendCode(); } catch (e) { showError($("auth-error"), e); }
|
||||
});
|
||||
|
||||
$("change-email").addEventListener("click", () => {
|
||||
clearInterval(state.resendTimer);
|
||||
showCodeStep(false);
|
||||
$("email").focus();
|
||||
});
|
||||
|
||||
$("logout").addEventListener("click", async () => {
|
||||
try { await api("POST", "/api/auth/logout"); } catch { /* 已經登出也沒關係 */ }
|
||||
state.me = null;
|
||||
state.today = null;
|
||||
renderSidebar();
|
||||
await route();
|
||||
});
|
||||
|
||||
$("guest-login").addEventListener("click", () => {
|
||||
openMenu();
|
||||
$("email").focus();
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 簽到 ----------
|
||||
|
||||
function showCheckinPart(part) {
|
||||
for (const id of ["checkin-guest", "checkin-ready", "checkin-done"]) $(id).hidden = id !== part;
|
||||
}
|
||||
|
||||
function statsText(d) {
|
||||
return `${t("checkin.total", { n: d.total_days })} · ${t("checkin.streak", { n: d.streak })}`;
|
||||
}
|
||||
|
||||
function renderToday(justChecked) {
|
||||
const d = state.today;
|
||||
if (!d.checked_in) {
|
||||
$("checkin-face").src = FACE[0];
|
||||
$("checkin-btn").classList.remove("pressed");
|
||||
showCheckinPart("checkin-ready");
|
||||
$("ready-stats").textContent = d.total_days ? statsText(d) : "";
|
||||
} else {
|
||||
showCheckinPart("checkin-done");
|
||||
$("checkin-msg").textContent = justChecked ? t("checkin.success") : t("checkin.done_today");
|
||||
const src = `${d.card_url}?v=${state.cardBust}`;
|
||||
if ($("card-img").getAttribute("src") !== src) $("card-img").src = src;
|
||||
$("download-btn").href = src;
|
||||
$("download-btn").setAttribute("download", `inmu-${d.day}.png`);
|
||||
$("done-stats").textContent = statsText(d);
|
||||
}
|
||||
startResetCountdown();
|
||||
}
|
||||
|
||||
function fmtDuration(ms) {
|
||||
const s = Math.max(0, Math.floor(ms / 1000));
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
return `${pad(Math.floor(s / 3600))}:${pad(Math.floor((s % 3600) / 60))}:${pad(s % 60)}`;
|
||||
}
|
||||
|
||||
function startResetCountdown() {
|
||||
clearInterval(state.resetTimer);
|
||||
const el = $("next-reset");
|
||||
if (!state.today) { el.hidden = true; return; }
|
||||
const target = Date.parse(state.today.next_reset);
|
||||
// 伺服器以台灣時間 04:00 換日,這裡換算成裝置的當地時間顯示
|
||||
const when = new Intl.DateTimeFormat(HTML_LANG[state.lang], {
|
||||
month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23",
|
||||
}).format(new Date(target));
|
||||
el.hidden = false;
|
||||
const tick = async () => {
|
||||
const left = target - Date.now();
|
||||
el.textContent = t("checkin.next", { time: when, t: fmtDuration(left) });
|
||||
if (left <= 0) {
|
||||
clearInterval(state.resetTimer);
|
||||
await refreshToday(); // 換日了
|
||||
}
|
||||
};
|
||||
tick();
|
||||
state.resetTimer = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
async function refreshToday() {
|
||||
try {
|
||||
state.today = await api("GET", "/api/checkin/today");
|
||||
renderToday(false);
|
||||
} catch (e) {
|
||||
if (e.status === 401) { state.me = null; renderSidebar(); showGuest(); } else toast(errText(e));
|
||||
}
|
||||
}
|
||||
|
||||
function showGuest() {
|
||||
clearInterval(state.resetTimer);
|
||||
$("next-reset").hidden = true;
|
||||
showCheckinPart("checkin-guest");
|
||||
}
|
||||
|
||||
async function showCheckin() {
|
||||
showView("view-checkin");
|
||||
if (!state.me) return showGuest();
|
||||
await refreshToday();
|
||||
}
|
||||
|
||||
async function shareCard() {
|
||||
const d = state.today;
|
||||
const text = `${d.share_text} ${d.share_url}`;
|
||||
try {
|
||||
const blob = await fetch($("card-img").src).then((r) => r.blob());
|
||||
const file = new File([blob], `inmu-${d.day}.png`, { type: "image/png" });
|
||||
if (navigator.canShare && navigator.canShare({ files: [file] })) {
|
||||
await navigator.share({ files: [file], text });
|
||||
return;
|
||||
}
|
||||
if (navigator.share) {
|
||||
await navigator.share({ text: d.share_text, url: d.share_url });
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.name === "AbortError") return; // 使用者自己取消
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
toast(t("share.copied"));
|
||||
} catch {
|
||||
window.prompt("", text);
|
||||
}
|
||||
}
|
||||
|
||||
// 按下簽到時從按鈕中心噴出粒子(顏色對應主色與 UID 的三種顏色,夾幾個「1」呼應 0 → 1)
|
||||
function burst(el) {
|
||||
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
||||
const r = el.getBoundingClientRect();
|
||||
const cx = r.left + r.width / 2;
|
||||
const cy = r.top + r.height / 2;
|
||||
const colors = ["#f0a43a", "#f5c518", "#2f7beb", "#f07c2a", "#ffffff"];
|
||||
const count = 28;
|
||||
for (let i = 0; i < count; i++) {
|
||||
const p = document.createElement("span");
|
||||
const digit = i % 6 === 0;
|
||||
p.className = digit ? "particle digit" : "particle";
|
||||
if (digit) p.textContent = "1";
|
||||
const angle = (i / count) * Math.PI * 2 + Math.random() * 0.5;
|
||||
const dist = r.width * 0.55 + Math.random() * r.width * 0.7;
|
||||
const size = digit ? 18 + Math.random() * 14 : 6 + Math.random() * 8;
|
||||
p.style.cssText = [
|
||||
`--x:${cx}px`, `--y:${cy}px`,
|
||||
`--dx:${(Math.cos(angle) * dist).toFixed(1)}px`, `--dy:${(Math.sin(angle) * dist).toFixed(1)}px`,
|
||||
`--s:${size.toFixed(1)}px`, `--c:${colors[i % colors.length]}`,
|
||||
`--r:${Math.round(Math.random() * 360 - 180)}deg`, `--d:${(0.7 + Math.random() * 0.4).toFixed(2)}s`,
|
||||
].join(";");
|
||||
p.addEventListener("animationend", () => p.remove());
|
||||
document.body.appendChild(p);
|
||||
}
|
||||
}
|
||||
|
||||
// 等音效播完(或保險時間到)
|
||||
function waitSfx(sfx) {
|
||||
return new Promise((resolve) => {
|
||||
const done = () => { clearTimeout(timer); sfx.removeEventListener("ended", done); resolve(); };
|
||||
const timer = setTimeout(done, SFX_MAX_MS);
|
||||
sfx.addEventListener("ended", done);
|
||||
});
|
||||
}
|
||||
|
||||
// 先把小卡下載好,切換畫面時才不會看到空白
|
||||
function preloadImage(src, maxMs = 6000) {
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image();
|
||||
const timer = setTimeout(resolve, maxMs);
|
||||
img.onload = img.onerror = () => { clearTimeout(timer); resolve(); };
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
|
||||
function bindCheckin() {
|
||||
const btn = $("checkin-btn");
|
||||
const sfx = $("checkin-sfx");
|
||||
btn.addEventListener("click", () => withBusy(btn, async () => {
|
||||
// 0 → 1、播音效、噴粒子,同時送出簽到;音效播完而且小卡下載好才亮出小卡,並關掉音效
|
||||
$("checkin-face").src = FACE[1];
|
||||
btn.classList.remove("pressed");
|
||||
void btn.offsetWidth; // 重新觸發動畫
|
||||
btn.classList.add("pressed");
|
||||
sfx.currentTime = 0;
|
||||
sfx.play().catch(() => { /* 不能播就算了 */ });
|
||||
burst(btn);
|
||||
const sfxDone = waitSfx(sfx);
|
||||
try {
|
||||
const today = await api("POST", "/api/checkin");
|
||||
await Promise.all([sfxDone, today.card_url ? preloadImage(`${today.card_url}?v=${state.cardBust}`) : null]);
|
||||
sfx.pause();
|
||||
state.today = today;
|
||||
renderToday(!today.already);
|
||||
loadMe(); // 更新側欄的天數
|
||||
} catch (e) {
|
||||
sfx.pause();
|
||||
$("checkin-face").src = FACE[0];
|
||||
btn.classList.remove("pressed");
|
||||
toast(errText(e));
|
||||
}
|
||||
}));
|
||||
$("share-btn").addEventListener("click", shareCard);
|
||||
}
|
||||
|
||||
// ---------- 畫面切換 ----------
|
||||
|
||||
function showView(id) {
|
||||
for (const v of ["view-checkin", "view-user", "view-upload", "view-review"]) $(v).hidden = v !== id;
|
||||
if (id !== "view-checkin") clearInterval(state.resetTimer);
|
||||
}
|
||||
|
||||
// ---------- 投稿迷因圖 ----------
|
||||
|
||||
function renderUploads(r) {
|
||||
$("upload-quota").textContent = t("upload.remaining", { n: r.remaining, max: r.limit });
|
||||
$("upload-pick").classList.toggle("busy", r.remaining <= 0);
|
||||
const list = $("upload-list");
|
||||
list.replaceChildren();
|
||||
$("upload-empty").hidden = r.items.length > 0;
|
||||
for (const it of r.items) {
|
||||
const box = document.createElement("div");
|
||||
box.className = "sub-item";
|
||||
if (it.image_url) {
|
||||
const img = document.createElement("img");
|
||||
img.src = it.image_url;
|
||||
img.alt = "";
|
||||
img.loading = "lazy";
|
||||
box.append(img);
|
||||
}
|
||||
const badge = document.createElement("span");
|
||||
badge.className = `sub-status ${it.status}`;
|
||||
badge.textContent = t(`upload.status.${it.status}`);
|
||||
box.append(badge);
|
||||
list.append(box);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshUploads() {
|
||||
try {
|
||||
renderUploads(await api("GET", "/api/submissions"));
|
||||
} catch (e) {
|
||||
showError($("upload-error"), e);
|
||||
$("upload-pick").classList.remove("busy");
|
||||
}
|
||||
}
|
||||
|
||||
async function showUpload() {
|
||||
showView("view-upload");
|
||||
document.title = `${t("nav.upload")} · ${SITE_TITLE}`;
|
||||
showError($("upload-error"), null);
|
||||
if (!state.me) { location.replace("/"); return; }
|
||||
await refreshUploads();
|
||||
}
|
||||
|
||||
function bindUpload() {
|
||||
$("upload-file").addEventListener("change", async (ev) => {
|
||||
const files = [...ev.target.files];
|
||||
ev.target.value = "";
|
||||
if (!files.length) return;
|
||||
$("upload-pick").classList.add("busy");
|
||||
showError($("upload-error"), null);
|
||||
let ok = 0;
|
||||
for (const file of files) { // 一張一張傳,額度用完就停
|
||||
if (file.size > SUBMIT_MAX_BYTES) { showError($("upload-error"), { code: "file_too_large" }); continue; }
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
try {
|
||||
await api("POST", "/api/submissions", fd);
|
||||
ok++;
|
||||
} catch (e) {
|
||||
showError($("upload-error"), e);
|
||||
if (e.code === "quota_exceeded") break;
|
||||
}
|
||||
}
|
||||
if (ok) toast(t("upload.done", { n: ok }));
|
||||
await refreshUploads();
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 管理員審核(一張一張) ----------
|
||||
|
||||
async function loadReview() {
|
||||
try {
|
||||
const r = await api("GET", "/api/admin/submissions");
|
||||
$("review-left").textContent = t("review.left", { n: r.pending });
|
||||
state.me.pending_reviews = r.pending;
|
||||
renderSidebar();
|
||||
const it = r.item;
|
||||
$("review-item").hidden = !it;
|
||||
$("review-empty").hidden = !!it;
|
||||
if (!it) return;
|
||||
$("review-item").dataset.id = it.id;
|
||||
$("review-img").src = it.image_url;
|
||||
$("review-name").textContent = it.uploader.display_name;
|
||||
$("review-name").href = `/u/${it.uploader.uid_str}`;
|
||||
showUid($("review-uid"), it.uploader);
|
||||
$("review-time").textContent = new Date(it.created_at).toLocaleString(HTML_LANG[state.lang]);
|
||||
} catch (e) {
|
||||
if (e.status === 401 || e.status === 403) { location.replace("/"); return; }
|
||||
toast(errText(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function showReview() {
|
||||
showView("view-review");
|
||||
document.title = `${t("review.heading")} · ${SITE_TITLE}`;
|
||||
if (!state.me?.is_admin) { location.replace("/"); return; }
|
||||
await loadReview();
|
||||
}
|
||||
|
||||
function bindReview() {
|
||||
const buttons = [$("review-approve"), $("review-reject")];
|
||||
const decide = async (action) => {
|
||||
const sid = $("review-item").dataset.id;
|
||||
buttons.forEach((b) => { b.disabled = true; });
|
||||
try {
|
||||
await api("POST", `/api/admin/submissions/${sid}/${action}`);
|
||||
toast(t(`review.${action}d`));
|
||||
} catch (e) {
|
||||
// 已經審過(例如另一個分頁)就直接跳下一張
|
||||
if (e.code !== "already_reviewed" && e.code !== "not_found") toast(errText(e));
|
||||
} finally {
|
||||
buttons.forEach((b) => { b.disabled = false; });
|
||||
}
|
||||
await loadReview();
|
||||
};
|
||||
$("review-approve").addEventListener("click", () => decide("approve"));
|
||||
$("review-reject").addEventListener("click", () => decide("reject"));
|
||||
}
|
||||
|
||||
// ---------- 個人頁 ----------
|
||||
|
||||
async function showUser(uid) {
|
||||
showView("view-user");
|
||||
try {
|
||||
const u = await api("GET", `/api/users/${uid}?lang=${state.lang}`);
|
||||
$("user-card").hidden = false;
|
||||
$("user-missing").hidden = true;
|
||||
$("user-avatar").src = u.avatar_url || DEFAULT_AVATAR;
|
||||
$("user-name").textContent = u.display_name;
|
||||
showUid($("user-uid"), u);
|
||||
$("user-stats").textContent = statsText(u);
|
||||
const bio = $("user-bio");
|
||||
if (u.bio_md.trim()) {
|
||||
bio.innerHTML = u.bio_html; // 伺服器端已關閉原始 HTML
|
||||
bio.classList.remove("empty");
|
||||
} else {
|
||||
bio.textContent = t("user.no_bio");
|
||||
bio.classList.add("empty");
|
||||
}
|
||||
const joined = new Date(u.created_at).toLocaleDateString(HTML_LANG[state.lang]);
|
||||
$("user-joined").textContent = t("user.joined", { d: joined });
|
||||
document.title = `${u.display_name} · ${SITE_TITLE}`;
|
||||
} catch {
|
||||
$("user-card").hidden = true;
|
||||
$("user-missing").hidden = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 編輯個人資料 ----------
|
||||
|
||||
function bindProfile() {
|
||||
const dialog = $("profile-dialog");
|
||||
|
||||
$("edit-profile").addEventListener("click", () => {
|
||||
const me = state.me;
|
||||
$("edit-avatar").src = me.avatar_url || DEFAULT_AVATAR;
|
||||
$("edit-name").value = me.display_name;
|
||||
$("edit-bio").value = me.bio_md;
|
||||
setPreview(false);
|
||||
showError($("profile-error"), null);
|
||||
closeMenu();
|
||||
dialog.showModal();
|
||||
});
|
||||
|
||||
$("profile-cancel").addEventListener("click", () => dialog.close());
|
||||
|
||||
$("avatar-file").addEventListener("change", async (ev) => {
|
||||
const file = ev.target.files[0];
|
||||
ev.target.value = "";
|
||||
if (!file) return;
|
||||
if (file.size > 5 * 1024 * 1024) return showError($("profile-error"), { code: "file_too_large" });
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
try {
|
||||
state.me = await api("PUT", "/api/me/avatar", fd);
|
||||
state.cardBust = Date.now();
|
||||
$("edit-avatar").src = state.me.avatar_url;
|
||||
showError($("profile-error"), null);
|
||||
renderSidebar();
|
||||
} catch (e) {
|
||||
showError($("profile-error"), e);
|
||||
}
|
||||
});
|
||||
|
||||
$("preview-toggle").addEventListener("click", async () => {
|
||||
if (!$("edit-preview").hidden) return setPreview(false);
|
||||
try {
|
||||
const r = await api("POST", "/api/markdown", { md: $("edit-bio").value });
|
||||
$("edit-preview").innerHTML = r.html;
|
||||
setPreview(true);
|
||||
} catch (e) {
|
||||
showError($("profile-error"), e);
|
||||
}
|
||||
});
|
||||
|
||||
$("profile-form").addEventListener("submit", (ev) => {
|
||||
ev.preventDefault();
|
||||
withBusy($("profile-save"), async () => {
|
||||
try {
|
||||
state.me = await api("PATCH", "/api/me", {
|
||||
display_name: $("edit-name").value,
|
||||
bio_md: $("edit-bio").value,
|
||||
});
|
||||
state.cardBust = Date.now();
|
||||
dialog.close();
|
||||
toast(t("profile.saved"));
|
||||
renderSidebar();
|
||||
await route();
|
||||
} catch (e) {
|
||||
showError($("profile-error"), e);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function setPreview(on) {
|
||||
$("edit-preview").hidden = !on;
|
||||
$("edit-bio").hidden = on;
|
||||
$("preview-toggle").textContent = on ? t("profile.edit_back") : t("profile.preview");
|
||||
}
|
||||
|
||||
// ---------- 手機選單 ----------
|
||||
|
||||
function openMenu() { $("sidebar").classList.add("open"); }
|
||||
function closeMenu() { $("sidebar").classList.remove("open"); }
|
||||
|
||||
// ---------- 啟動 ----------
|
||||
|
||||
async function loadMe() {
|
||||
try {
|
||||
state.me = await api("GET", "/api/me");
|
||||
} catch {
|
||||
state.me = null;
|
||||
}
|
||||
renderSidebar();
|
||||
}
|
||||
|
||||
async function route() {
|
||||
document.title = SITE_TITLE;
|
||||
const m = location.pathname.match(/^\/u\/(\d+)$/);
|
||||
if (m) return showUser(m[1]);
|
||||
if (location.pathname === "/upload") return showUpload();
|
||||
if (location.pathname === "/review") return showReview();
|
||||
return showCheckin();
|
||||
}
|
||||
|
||||
async function init() {
|
||||
await loadLang(detectLang());
|
||||
bindAuth();
|
||||
bindCheckin();
|
||||
bindProfile();
|
||||
bindUpload();
|
||||
bindReview();
|
||||
|
||||
$("menu-toggle").addEventListener("click", () => $("sidebar").classList.toggle("open"));
|
||||
|
||||
$("lang").addEventListener("change", async (ev) => {
|
||||
await loadLang(ev.target.value);
|
||||
if (state.me) {
|
||||
try {
|
||||
// 語言也會用在信件、小卡與分享文字,所以同步到伺服器
|
||||
state.me = await api("PATCH", "/api/me", { lang: state.lang });
|
||||
state.cardBust = Date.now();
|
||||
} catch { /* 介面已經切換,伺服器同步失敗就算了 */ }
|
||||
}
|
||||
renderSidebar();
|
||||
if (!$("code-form").hidden) $("code-sent-msg").textContent = t("auth.sent", { email: state.email });
|
||||
await route();
|
||||
});
|
||||
|
||||
await loadMe();
|
||||
await route();
|
||||
}
|
||||
|
||||
init();
|
||||
|
After Width: | Height: | Size: 40 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" fill="#3a3448"/><circle cx="32" cy="25" r="12" fill="#8a82a0"/><path d="M10 60c2-13 11-20 22-20s20 7 22 20z" fill="#8a82a0"/></svg>
|
||||
|
After Width: | Height: | Size: 221 B |
|
After Width: | Height: | Size: 7.4 KiB |
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"lang.label": "Language",
|
||||
"menu": "Menu",
|
||||
"auth.heading": "Log in / Sign up",
|
||||
"auth.hint": "We'll email you a code. Your account is created the first time you log in.",
|
||||
"auth.email": "Email",
|
||||
"auth.send": "Send code",
|
||||
"auth.sent": "We sent a code to {email}. It expires in 5 minutes.",
|
||||
"auth.code": "6-digit code",
|
||||
"auth.verify": "Log in",
|
||||
"auth.resend": "Resend",
|
||||
"auth.resend_wait": "Resend in {s}s",
|
||||
"auth.change_email": "Use a different email",
|
||||
"auth.logout": "Log out",
|
||||
"profile.view": "My profile",
|
||||
"profile.edit": "Edit profile",
|
||||
"profile.avatar": "Avatar",
|
||||
"profile.avatar_hint": "Cropped to a 1024×1024 square, up to 5 MB",
|
||||
"profile.avatar_change": "Change avatar",
|
||||
"profile.name": "Name",
|
||||
"profile.bio": "About me (Markdown supported)",
|
||||
"profile.preview": "Preview",
|
||||
"profile.edit_back": "Keep editing",
|
||||
"profile.save": "Save",
|
||||
"profile.cancel": "Cancel",
|
||||
"profile.saved": "Saved",
|
||||
"checkin.button": "Check in",
|
||||
"checkin.login_first": "Log in to check in once a day and get an INMU card.",
|
||||
"checkin.ready": "You haven't checked in today",
|
||||
"checkin.success": "Checked in!",
|
||||
"checkin.done_today": "You've already checked in today",
|
||||
"checkin.total": "{n} days total",
|
||||
"checkin.streak": "{n}-day streak",
|
||||
"checkin.next": "Next check-in: {time} (in {t})",
|
||||
"share.button": "Share",
|
||||
"share.download": "Download image",
|
||||
"share.copied": "Copied the share text and link",
|
||||
"user.joined": "Joined {d}",
|
||||
"user.not_found": "User not found",
|
||||
"user.back": "Back to home",
|
||||
"user.no_bio": "No bio yet.",
|
||||
"err.invalid_email": "That email address doesn't look right",
|
||||
"err.too_many_requests": "Too many requests. Please try again later",
|
||||
"err.send_failed": "Couldn't send the email. Please try again later",
|
||||
"err.not_requested": "Send a code first",
|
||||
"err.expired": "This code has expired. Send a new one",
|
||||
"err.wrong_code": "Wrong code",
|
||||
"err.unauthorized": "Please log in",
|
||||
"err.name_invalid": "Names must be 1–32 characters",
|
||||
"err.bio_too_long": "Your bio can be up to 2000 characters",
|
||||
"err.file_too_large": "File too large (5 MB max)",
|
||||
"err.invalid_image": "Couldn't read that image",
|
||||
"err.network": "Connection failed",
|
||||
"err.unknown": "Something went wrong",
|
||||
"err.code_used": "This code has already been used. Please get a new code in a moment",
|
||||
"nav.upload": "Submit images",
|
||||
"nav.review": "Review submissions ({n})",
|
||||
"upload.heading": "Submit images",
|
||||
"upload.hint": "Upload images you think belong on an INMU card. Approved images join the draw. Up to 5 per day (resets at 04:00 Taiwan time), 5MB each.",
|
||||
"upload.choose": "Choose images",
|
||||
"upload.remaining": "{n} / {max} uploads left today",
|
||||
"upload.done": "Uploaded {n}, waiting for review",
|
||||
"upload.mine": "My submissions",
|
||||
"upload.empty": "No submissions yet.",
|
||||
"upload.status.pending": "Pending",
|
||||
"upload.status.approved": "Added",
|
||||
"upload.status.rejected": "Not accepted",
|
||||
"review.heading": "Review submissions",
|
||||
"review.left": "{n} waiting",
|
||||
"review.approve": "Approve",
|
||||
"review.reject": "Reject",
|
||||
"review.approved": "Approved and added to the draw",
|
||||
"review.rejected": "Rejected",
|
||||
"review.empty": "Nothing to review right now",
|
||||
"err.quota_exceeded": "You've used today's uploads. Come back tomorrow",
|
||||
"err.forbidden": "Not allowed",
|
||||
"err.already_reviewed": "This one has already been reviewed",
|
||||
"err.not_found": "Not found"
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"lang.label": "言語",
|
||||
"menu": "メニュー",
|
||||
"auth.heading": "ログイン / 登録",
|
||||
"auth.hint": "メールアドレスに認証コードを送ります。初回ログイン時にアカウントが作成されます。",
|
||||
"auth.email": "メールアドレス",
|
||||
"auth.send": "認証コードを送信",
|
||||
"auth.sent": "{email} に認証コードを送りました(有効期限 5 分)。",
|
||||
"auth.code": "6 桁の認証コード",
|
||||
"auth.verify": "ログイン",
|
||||
"auth.resend": "再送信",
|
||||
"auth.resend_wait": "{s} 秒後に再送信できます",
|
||||
"auth.change_email": "別のメールアドレスを使う",
|
||||
"auth.logout": "ログアウト",
|
||||
"profile.view": "マイページ",
|
||||
"profile.edit": "プロフィール編集",
|
||||
"profile.avatar": "アイコン",
|
||||
"profile.avatar_hint": "1024×1024 の正方形に切り抜きます(最大 5MB)",
|
||||
"profile.avatar_change": "アイコンを変更",
|
||||
"profile.name": "名前",
|
||||
"profile.bio": "自己紹介(Markdown 対応)",
|
||||
"profile.preview": "プレビュー",
|
||||
"profile.edit_back": "編集に戻る",
|
||||
"profile.save": "保存",
|
||||
"profile.cancel": "キャンセル",
|
||||
"profile.saved": "保存しました",
|
||||
"checkin.button": "ログインボーナス",
|
||||
"checkin.login_first": "ログインすると毎日 1 回、INMU カードがもらえます。",
|
||||
"checkin.ready": "今日はまだ受け取っていません",
|
||||
"checkin.success": "受け取りました!",
|
||||
"checkin.done_today": "今日はもう受け取りました",
|
||||
"checkin.total": "累計 {n} 日",
|
||||
"checkin.streak": "連続 {n} 日",
|
||||
"checkin.next": "次回:{time}(あと {t})",
|
||||
"share.button": "シェア",
|
||||
"share.download": "画像を保存",
|
||||
"share.copied": "シェア用のテキストとリンクをコピーしました",
|
||||
"user.joined": "{d} に参加",
|
||||
"user.not_found": "ユーザーが見つかりません",
|
||||
"user.back": "トップへ",
|
||||
"user.no_bio": "自己紹介はまだありません。",
|
||||
"err.invalid_email": "メールアドレスの形式が正しくありません",
|
||||
"err.too_many_requests": "リクエストが多すぎます。しばらくしてからお試しください",
|
||||
"err.send_failed": "メールを送信できませんでした。しばらくしてからお試しください",
|
||||
"err.not_requested": "先に認証コードを送信してください",
|
||||
"err.expired": "認証コードが無効になりました。再送信してください",
|
||||
"err.wrong_code": "認証コードが違います",
|
||||
"err.unauthorized": "ログインしてください",
|
||||
"err.name_invalid": "名前は 1〜32 文字にしてください",
|
||||
"err.bio_too_long": "自己紹介は 2000 文字までです",
|
||||
"err.file_too_large": "ファイルが大きすぎます(最大 5MB)",
|
||||
"err.invalid_image": "この画像は読み込めません",
|
||||
"err.network": "接続できませんでした",
|
||||
"err.unknown": "エラーが発生しました",
|
||||
"err.code_used": "この認証コードは使用済みです。しばらくしてから新しいコードをお使いください",
|
||||
"nav.upload": "画像を投稿",
|
||||
"nav.review": "投稿の審査({n})",
|
||||
"upload.heading": "画像を投稿",
|
||||
"upload.hint": "カードに載せたい画像をアップロードしてください。審査に通るとガチャに追加されます。1日5枚まで(台湾時間 04:00 にリセット)、5MBまで。",
|
||||
"upload.choose": "画像を選ぶ",
|
||||
"upload.remaining": "今日はあと {n} / {max} 枚",
|
||||
"upload.done": "{n} 枚アップロードしました(審査待ち)",
|
||||
"upload.mine": "自分の投稿",
|
||||
"upload.empty": "まだ投稿がありません。",
|
||||
"upload.status.pending": "審査中",
|
||||
"upload.status.approved": "採用",
|
||||
"upload.status.rejected": "不採用",
|
||||
"review.heading": "投稿の審査",
|
||||
"review.left": "審査待ち {n} 枚",
|
||||
"review.approve": "採用",
|
||||
"review.reject": "却下",
|
||||
"review.approved": "採用しました",
|
||||
"review.rejected": "却下しました",
|
||||
"review.empty": "審査待ちの投稿はありません",
|
||||
"err.quota_exceeded": "今日の投稿枠を使い切りました。また明日どうぞ",
|
||||
"err.forbidden": "権限がありません",
|
||||
"err.already_reviewed": "この投稿はすでに審査済みです",
|
||||
"err.not_found": "見つかりません"
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"lang.label": "언어",
|
||||
"menu": "메뉴",
|
||||
"auth.heading": "로그인 / 가입",
|
||||
"auth.hint": "이메일로 인증 코드를 보내드립니다. 처음 로그인하면 계정이 자동으로 만들어집니다.",
|
||||
"auth.email": "이메일",
|
||||
"auth.send": "인증 코드 보내기",
|
||||
"auth.sent": "{email}(으)로 인증 코드를 보냈습니다. 5분 동안 유효합니다.",
|
||||
"auth.code": "6자리 인증 코드",
|
||||
"auth.verify": "로그인",
|
||||
"auth.resend": "다시 보내기",
|
||||
"auth.resend_wait": "{s}초 후 다시 보낼 수 있습니다",
|
||||
"auth.change_email": "다른 이메일 사용",
|
||||
"auth.logout": "로그아웃",
|
||||
"profile.view": "내 프로필",
|
||||
"profile.edit": "프로필 편집",
|
||||
"profile.avatar": "프로필 사진",
|
||||
"profile.avatar_hint": "1024×1024 정사각형으로 잘립니다 (최대 5MB)",
|
||||
"profile.avatar_change": "사진 변경",
|
||||
"profile.name": "이름",
|
||||
"profile.bio": "자기소개 (Markdown 지원)",
|
||||
"profile.preview": "미리보기",
|
||||
"profile.edit_back": "계속 편집",
|
||||
"profile.save": "저장",
|
||||
"profile.cancel": "취소",
|
||||
"profile.saved": "저장했습니다",
|
||||
"checkin.button": "출석 체크",
|
||||
"checkin.login_first": "로그인하면 하루에 한 번 출석하고 INMU 카드를 받을 수 있습니다.",
|
||||
"checkin.ready": "오늘은 아직 출석하지 않았습니다",
|
||||
"checkin.success": "출석 완료!",
|
||||
"checkin.done_today": "오늘은 이미 출석했습니다",
|
||||
"checkin.total": "누적 {n}일",
|
||||
"checkin.streak": "연속 {n}일",
|
||||
"checkin.next": "다음 출석: {time} ({t} 남음)",
|
||||
"share.button": "공유",
|
||||
"share.download": "이미지 저장",
|
||||
"share.copied": "공유 문구와 링크를 복사했습니다",
|
||||
"user.joined": "{d} 가입",
|
||||
"user.not_found": "사용자를 찾을 수 없습니다",
|
||||
"user.back": "홈으로",
|
||||
"user.no_bio": "아직 자기소개가 없습니다.",
|
||||
"err.invalid_email": "이메일 형식이 올바르지 않습니다",
|
||||
"err.too_many_requests": "요청이 너무 많습니다. 잠시 후 다시 시도해 주세요",
|
||||
"err.send_failed": "메일을 보내지 못했습니다. 잠시 후 다시 시도해 주세요",
|
||||
"err.not_requested": "먼저 인증 코드를 보내 주세요",
|
||||
"err.expired": "인증 코드가 만료되었습니다. 다시 보내 주세요",
|
||||
"err.wrong_code": "인증 코드가 틀렸습니다",
|
||||
"err.unauthorized": "로그인해 주세요",
|
||||
"err.name_invalid": "이름은 1~32자여야 합니다",
|
||||
"err.bio_too_long": "자기소개는 최대 2000자입니다",
|
||||
"err.file_too_large": "파일이 너무 큽니다 (최대 5MB)",
|
||||
"err.invalid_image": "이미지를 읽을 수 없습니다",
|
||||
"err.network": "연결에 실패했습니다",
|
||||
"err.unknown": "오류가 발생했습니다",
|
||||
"err.code_used": "이미 사용한 인증 코드입니다. 잠시 후 새 코드를 사용해 주세요",
|
||||
"nav.upload": "이미지 투고",
|
||||
"nav.review": "투고 심사 ({n})",
|
||||
"upload.heading": "이미지 투고",
|
||||
"upload.hint": "카드에 넣고 싶은 이미지를 올려 주세요. 심사를 통과하면 뽑기에 추가됩니다. 하루 최대 5장(대만 시간 04:00 초기화), 5MB까지.",
|
||||
"upload.choose": "이미지 선택",
|
||||
"upload.remaining": "오늘 {n} / {max}장 더 올릴 수 있어요",
|
||||
"upload.done": "{n}장 업로드했어요 (심사 대기)",
|
||||
"upload.mine": "내 투고",
|
||||
"upload.empty": "아직 투고한 이미지가 없어요.",
|
||||
"upload.status.pending": "심사 중",
|
||||
"upload.status.approved": "채택",
|
||||
"upload.status.rejected": "미채택",
|
||||
"review.heading": "투고 심사",
|
||||
"review.left": "심사 대기 {n}장",
|
||||
"review.approve": "승인",
|
||||
"review.reject": "거절",
|
||||
"review.approved": "승인했어요",
|
||||
"review.rejected": "거절했어요",
|
||||
"review.empty": "심사할 투고가 없어요",
|
||||
"err.quota_exceeded": "오늘 투고 한도를 다 썼어요. 내일 다시 와 주세요",
|
||||
"err.forbidden": "권한이 없어요",
|
||||
"err.already_reviewed": "이미 심사한 투고예요",
|
||||
"err.not_found": "찾을 수 없어요"
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"lang.label": "语言",
|
||||
"menu": "菜单",
|
||||
"auth.heading": "登录 / 注册",
|
||||
"auth.hint": "输入邮箱接收验证码,第一次登录会自动创建账号。",
|
||||
"auth.email": "邮箱",
|
||||
"auth.send": "发送验证码",
|
||||
"auth.sent": "验证码已发送到 {email},5 分钟内有效。",
|
||||
"auth.code": "6 位数验证码",
|
||||
"auth.verify": "登录",
|
||||
"auth.resend": "重新发送",
|
||||
"auth.resend_wait": "{s} 秒后可重发",
|
||||
"auth.change_email": "换一个邮箱",
|
||||
"auth.logout": "退出登录",
|
||||
"profile.view": "我的主页",
|
||||
"profile.edit": "编辑个人资料",
|
||||
"profile.avatar": "头像",
|
||||
"profile.avatar_hint": "会裁成 1024×1024 正方形,上限 5MB",
|
||||
"profile.avatar_change": "更换头像",
|
||||
"profile.name": "名称",
|
||||
"profile.bio": "自我介绍(支持 Markdown)",
|
||||
"profile.preview": "预览",
|
||||
"profile.edit_back": "继续编辑",
|
||||
"profile.save": "保存",
|
||||
"profile.cancel": "取消",
|
||||
"profile.saved": "已保存",
|
||||
"checkin.button": "签到",
|
||||
"checkin.login_first": "登录后每天都能签到一次,拿一张 INMU 小卡。",
|
||||
"checkin.ready": "今天还没签到",
|
||||
"checkin.success": "签到成功!",
|
||||
"checkin.done_today": "今天已经签到了",
|
||||
"checkin.total": "累计 {n} 天",
|
||||
"checkin.streak": "连续 {n} 天",
|
||||
"checkin.next": "下次签到:{time}(还有 {t})",
|
||||
"share.button": "分享",
|
||||
"share.download": "下载图片",
|
||||
"share.copied": "已复制分享文字和链接",
|
||||
"user.joined": "{d} 加入",
|
||||
"user.not_found": "找不到这个用户",
|
||||
"user.back": "回首页",
|
||||
"user.no_bio": "这个人还没写自我介绍。",
|
||||
"err.invalid_email": "邮箱格式不正确",
|
||||
"err.too_many_requests": "请求太频繁,请稍后再试",
|
||||
"err.send_failed": "验证邮件发送失败,请稍后再试",
|
||||
"err.not_requested": "请先发送验证码",
|
||||
"err.expired": "验证码已失效,请重新发送",
|
||||
"err.wrong_code": "验证码错误",
|
||||
"err.unauthorized": "请先登录",
|
||||
"err.name_invalid": "名称需要 1–32 个字",
|
||||
"err.bio_too_long": "自我介绍最多 2000 字",
|
||||
"err.file_too_large": "文件太大(上限 5MB)",
|
||||
"err.invalid_image": "无法读取这张图片",
|
||||
"err.network": "连接失败,请检查网络",
|
||||
"err.unknown": "发生错误,请稍后再试",
|
||||
"err.code_used": "这组验证码已经用过,请稍后获取新的验证码",
|
||||
"nav.upload": "投稿图片",
|
||||
"nav.review": "审核投稿({n})",
|
||||
"upload.heading": "投稿图片",
|
||||
"upload.hint": "上传你觉得适合放上小卡的图,审核通过后就会加入抽卡。每天最多 5 张(台湾时间 04:00 重置),上限 5MB。",
|
||||
"upload.choose": "选择图片",
|
||||
"upload.remaining": "今天还能上传 {n} / {max} 张",
|
||||
"upload.done": "已上传 {n} 张,等待审核",
|
||||
"upload.mine": "我的投稿",
|
||||
"upload.empty": "还没有投稿过。",
|
||||
"upload.status.pending": "审核中",
|
||||
"upload.status.approved": "已加入",
|
||||
"upload.status.rejected": "未通过",
|
||||
"review.heading": "审核投稿",
|
||||
"review.left": "待审 {n} 张",
|
||||
"review.approve": "同意",
|
||||
"review.reject": "拒绝",
|
||||
"review.approved": "已同意,加入抽卡",
|
||||
"review.rejected": "已拒绝",
|
||||
"review.empty": "目前没有待审的投稿",
|
||||
"err.quota_exceeded": "今天的投稿额度已经用完,明天再来",
|
||||
"err.forbidden": "没有权限",
|
||||
"err.already_reviewed": "这张已经审核过了",
|
||||
"err.not_found": "找不到"
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"lang.label": "語言",
|
||||
"menu": "選單",
|
||||
"auth.heading": "登入 / 註冊",
|
||||
"auth.hint": "輸入信箱收驗證碼,第一次登入會自動建立帳號。",
|
||||
"auth.email": "信箱",
|
||||
"auth.send": "寄送驗證碼",
|
||||
"auth.sent": "驗證碼已寄到 {email},5 分鐘內有效。",
|
||||
"auth.code": "6 位數驗證碼",
|
||||
"auth.verify": "登入",
|
||||
"auth.resend": "重新寄送",
|
||||
"auth.resend_wait": "{s} 秒後可重寄",
|
||||
"auth.change_email": "換一個信箱",
|
||||
"auth.logout": "登出",
|
||||
"profile.view": "我的個人頁",
|
||||
"profile.edit": "編輯個人資料",
|
||||
"profile.avatar": "大頭貼",
|
||||
"profile.avatar_hint": "會裁成 1024×1024 正方形,上限 5MB",
|
||||
"profile.avatar_change": "更換大頭貼",
|
||||
"profile.name": "名稱",
|
||||
"profile.bio": "自我介紹(支援 Markdown)",
|
||||
"profile.preview": "預覽",
|
||||
"profile.edit_back": "繼續編輯",
|
||||
"profile.save": "儲存",
|
||||
"profile.cancel": "取消",
|
||||
"profile.saved": "已儲存",
|
||||
"checkin.button": "簽到",
|
||||
"checkin.login_first": "登入後每天都能簽到一次,拿一張 INMU 小卡。",
|
||||
"checkin.ready": "今天還沒簽到",
|
||||
"checkin.success": "簽到成功!",
|
||||
"checkin.done_today": "今天已經簽到了",
|
||||
"checkin.total": "累計 {n} 天",
|
||||
"checkin.streak": "連續 {n} 天",
|
||||
"checkin.next": "下次簽到:{time}(還有 {t})",
|
||||
"share.button": "分享",
|
||||
"share.download": "下載圖片",
|
||||
"share.copied": "已複製分享文字和連結",
|
||||
"user.joined": "{d} 加入",
|
||||
"user.not_found": "找不到這個使用者",
|
||||
"user.back": "回首頁",
|
||||
"user.no_bio": "這個人還沒寫自我介紹。",
|
||||
"err.invalid_email": "信箱格式不正確",
|
||||
"err.too_many_requests": "請求太頻繁,請稍後再試",
|
||||
"err.send_failed": "驗證信寄送失敗,請稍後再試",
|
||||
"err.not_requested": "請先寄送驗證碼",
|
||||
"err.expired": "驗證碼已失效,請重新寄送",
|
||||
"err.wrong_code": "驗證碼錯誤",
|
||||
"err.unauthorized": "請先登入",
|
||||
"err.name_invalid": "名稱需要 1–32 個字",
|
||||
"err.bio_too_long": "自我介紹最多 2000 字",
|
||||
"err.file_too_large": "檔案太大(上限 5MB)",
|
||||
"err.invalid_image": "無法讀取這張圖片",
|
||||
"err.network": "連線失敗,請檢查網路",
|
||||
"err.unknown": "發生錯誤,請稍後再試",
|
||||
"err.code_used": "這組驗證碼已經用過,請稍後取得新的驗證碼",
|
||||
"nav.upload": "投稿圖片",
|
||||
"nav.review": "審核投稿({n})",
|
||||
"upload.heading": "投稿圖片",
|
||||
"upload.hint": "上傳你覺得適合放上小卡的圖,審核通過後就會加入抽卡。每天最多 5 張(台灣時間 04:00 重置),上限 5MB。",
|
||||
"upload.choose": "選擇圖片",
|
||||
"upload.remaining": "今天還能上傳 {n} / {max} 張",
|
||||
"upload.done": "已上傳 {n} 張,等待審核",
|
||||
"upload.mine": "我的投稿",
|
||||
"upload.empty": "還沒有投稿過。",
|
||||
"upload.status.pending": "審核中",
|
||||
"upload.status.approved": "已加入",
|
||||
"upload.status.rejected": "未通過",
|
||||
"review.heading": "審核投稿",
|
||||
"review.left": "待審 {n} 張",
|
||||
"review.approve": "同意",
|
||||
"review.reject": "拒絕",
|
||||
"review.approved": "已同意,加入抽卡",
|
||||
"review.rejected": "已拒絕",
|
||||
"review.empty": "目前沒有待審的投稿",
|
||||
"err.quota_exceeded": "今天的投稿額度已經用完,明天再來",
|
||||
"err.forbidden": "沒有權限",
|
||||
"err.already_reviewed": "這張已經審核過了",
|
||||
"err.not_found": "找不到"
|
||||
}
|
||||
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 213 KiB |
@@ -0,0 +1,179 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hant-TW">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>My INMU<!--BETA_TITLE--></title>
|
||||
<meta name="description" content="My INMU">
|
||||
<meta name="theme-color" content="#121016">
|
||||
<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">
|
||||
<link rel="manifest" href="/assets/manifest.webmanifest">
|
||||
<meta name="asset-version" content="__ASSET_VERSION__">
|
||||
<link rel="stylesheet" href="/assets/style.css?v=__ASSET_VERSION__">
|
||||
<script type="module" src="/assets/app.js?v=__ASSET_VERSION__"></script>
|
||||
<link rel="preload" as="image" href="/assets/media/checkin-1.webp?v=__ASSET_VERSION__">
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout">
|
||||
<aside id="sidebar">
|
||||
<div class="brand">
|
||||
<a href="/"><img class="logo" src="/assets/logo.png" alt="" width="32" height="32"><span>My INMU<!--BETA_BADGE--></span></a>
|
||||
<button id="menu-toggle" class="icon-btn only-mobile" type="button" data-i18n-aria="menu">☰</button>
|
||||
</div>
|
||||
|
||||
<div id="sidebar-body">
|
||||
<section id="auth-box" hidden>
|
||||
<h2 data-i18n="auth.heading"></h2>
|
||||
<p class="hint" data-i18n="auth.hint"></p>
|
||||
<form id="email-form" novalidate>
|
||||
<label><span data-i18n="auth.email"></span>
|
||||
<input type="text" inputmode="email" id="email" required autocomplete="username" autocapitalize="off" spellcheck="false" maxlength="254">
|
||||
</label>
|
||||
<button type="submit" class="primary" data-i18n="auth.send"></button>
|
||||
</form>
|
||||
<form id="code-form" hidden novalidate>
|
||||
<p class="hint" id="code-sent-msg"></p>
|
||||
<label><span data-i18n="auth.code"></span>
|
||||
<input id="code" inputmode="numeric" maxlength="6" autocomplete="one-time-code" required>
|
||||
</label>
|
||||
<button type="submit" class="primary" data-i18n="auth.verify"></button>
|
||||
<div class="row">
|
||||
<button type="button" class="link" id="resend"></button>
|
||||
<button type="button" class="link" id="change-email" data-i18n="auth.change_email"></button>
|
||||
</div>
|
||||
</form>
|
||||
<p class="error" id="auth-error" hidden></p>
|
||||
</section>
|
||||
|
||||
<section id="me-box" hidden>
|
||||
<img id="me-avatar" class="avatar" alt="" width="96" height="96">
|
||||
<div class="me-name" id="me-name"></div>
|
||||
<div class="uid" id="me-uid"></div>
|
||||
<nav class="me-nav">
|
||||
<a id="me-link" href="/" data-i18n="profile.view"></a>
|
||||
<a id="upload-link" href="/upload" data-i18n="nav.upload"></a>
|
||||
<a id="review-link" href="/review" hidden></a>
|
||||
<button type="button" class="link" id="edit-profile" data-i18n="profile.edit"></button>
|
||||
<button type="button" class="link" id="logout" data-i18n="auth.logout"></button>
|
||||
</nav>
|
||||
</section>
|
||||
|
||||
<label class="lang"><span data-i18n="lang.label"></span>
|
||||
<select id="lang">
|
||||
<option value="zh-TW">繁體中文</option>
|
||||
<option value="zh-CN">简体中文</option>
|
||||
<option value="ja">日本語</option>
|
||||
<option value="ko">한국어</option>
|
||||
<option value="en">English</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main id="main">
|
||||
<section id="view-checkin" hidden>
|
||||
<div id="checkin-guest" class="center" hidden>
|
||||
<div class="big-mark">INMU</div>
|
||||
<p data-i18n="checkin.login_first"></p>
|
||||
<button id="guest-login" class="primary" type="button" data-i18n="auth.heading"></button>
|
||||
</div>
|
||||
<div id="checkin-ready" class="center" hidden>
|
||||
<p class="muted" data-i18n="checkin.ready"></p>
|
||||
<button id="checkin-btn" class="checkin-btn" type="button">
|
||||
<img id="checkin-face" src="/assets/media/checkin-0.webp?v=__ASSET_VERSION__" alt="" width="512" height="512" draggable="false">
|
||||
<span class="checkin-label" data-i18n="checkin.button"></span>
|
||||
</button>
|
||||
<audio id="checkin-sfx" src="/assets/media/114514.m4a?v=__ASSET_VERSION__" preload="auto"></audio>
|
||||
<p class="stats" id="ready-stats"></p>
|
||||
</div>
|
||||
<div id="checkin-done" class="center" hidden>
|
||||
<p class="checkin-msg" id="checkin-msg"></p>
|
||||
<img id="card-img" class="card-img" alt="INMU card" width="1080" height="1350">
|
||||
<div class="row actions">
|
||||
<button id="share-btn" class="primary" type="button" data-i18n="share.button"></button>
|
||||
<a id="download-btn" class="button" download data-i18n="share.download"></a>
|
||||
</div>
|
||||
<p class="stats" id="done-stats"></p>
|
||||
</div>
|
||||
<p class="hint center-text" id="next-reset" hidden></p>
|
||||
</section>
|
||||
|
||||
<section id="view-upload" hidden>
|
||||
<h1 data-i18n="upload.heading"></h1>
|
||||
<p class="hint" data-i18n="upload.hint"></p>
|
||||
<div class="row upload-bar">
|
||||
<label class="button primary" for="upload-file" id="upload-pick" data-i18n="upload.choose"></label>
|
||||
<input type="file" id="upload-file" accept="image/*" multiple hidden>
|
||||
<span class="muted" id="upload-quota"></span>
|
||||
</div>
|
||||
<p class="error" id="upload-error" hidden></p>
|
||||
<h2 data-i18n="upload.mine"></h2>
|
||||
<p class="hint" id="upload-empty" data-i18n="upload.empty" hidden></p>
|
||||
<div class="sub-grid" id="upload-list"></div>
|
||||
</section>
|
||||
|
||||
<section id="view-review" hidden>
|
||||
<h1 data-i18n="review.heading"></h1>
|
||||
<p class="muted" id="review-left"></p>
|
||||
<div id="review-item" class="center" hidden>
|
||||
<img id="review-img" class="review-img" alt="">
|
||||
<p class="review-meta">
|
||||
<a id="review-name" href="/"></a> <span class="uid" id="review-uid"></span><br>
|
||||
<span class="hint" id="review-time"></span>
|
||||
</p>
|
||||
<div class="row actions">
|
||||
<button type="button" id="review-reject" data-i18n="review.reject"></button>
|
||||
<button type="button" class="primary" id="review-approve" data-i18n="review.approve"></button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="center-text muted" id="review-empty" data-i18n="review.empty" hidden></p>
|
||||
</section>
|
||||
|
||||
<section id="view-user" hidden>
|
||||
<div id="user-card" class="profile" hidden>
|
||||
<img id="user-avatar" class="avatar large" alt="" width="160" height="160">
|
||||
<h1 id="user-name"></h1>
|
||||
<div class="uid" id="user-uid"></div>
|
||||
<p class="stats" id="user-stats"></p>
|
||||
<div class="bio" id="user-bio"></div>
|
||||
<p class="hint" id="user-joined"></p>
|
||||
</div>
|
||||
<p id="user-missing" class="center-text" hidden data-i18n="user.not_found"></p>
|
||||
<p class="center-text"><a href="/" data-i18n="user.back"></a></p>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<dialog id="profile-dialog">
|
||||
<form id="profile-form" method="dialog" novalidate>
|
||||
<h2 data-i18n="profile.edit"></h2>
|
||||
<div class="avatar-edit">
|
||||
<img id="edit-avatar" class="avatar" alt="" width="96" height="96">
|
||||
<div>
|
||||
<label class="button" for="avatar-file" data-i18n="profile.avatar_change"></label>
|
||||
<input type="file" id="avatar-file" accept="image/*" hidden>
|
||||
<p class="hint" data-i18n="profile.avatar_hint"></p>
|
||||
</div>
|
||||
</div>
|
||||
<label><span data-i18n="profile.name"></span>
|
||||
<input id="edit-name" maxlength="32" required>
|
||||
</label>
|
||||
<label><span data-i18n="profile.bio"></span>
|
||||
<textarea id="edit-bio" rows="8" maxlength="2000"></textarea>
|
||||
</label>
|
||||
<div class="bio preview" id="edit-preview" hidden></div>
|
||||
<p class="error" id="profile-error" hidden></p>
|
||||
<div class="row dialog-actions">
|
||||
<button type="button" class="link" id="preview-toggle" data-i18n="profile.preview"></button>
|
||||
<span class="spacer"></span>
|
||||
<button type="button" id="profile-cancel" data-i18n="profile.cancel"></button>
|
||||
<button type="submit" class="primary" id="profile-save" data-i18n="profile.save"></button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<div id="toast" role="status" hidden></div>
|
||||
</body>
|
||||
</html>
|
||||
|
After Width: | Height: | Size: 7.2 KiB |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "My INMU",
|
||||
"short_name": "My INMU",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#121016",
|
||||
"theme_color": "#121016",
|
||||
"icons": [
|
||||
{ "src": "/assets/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||
{ "src": "/assets/icon-512.png", "sizes": "512x512", "type": "image/png" }
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 8.6 KiB |
@@ -0,0 +1,281 @@
|
||||
:root {
|
||||
--bg: #121016;
|
||||
--panel: #1c1922;
|
||||
--panel-2: #26222e;
|
||||
--line: #3a3448;
|
||||
--text: #f5f3fa;
|
||||
--muted: #b9b3c9;
|
||||
--accent: #f0a43a;
|
||||
--accent-ink: #1e1a24;
|
||||
--error: #ff7a7a;
|
||||
--radius: 12px;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
html, body { margin: 0; height: 100%; }
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 16px/1.6 system-ui, -apple-system, "Segoe UI", "Noto Sans TC", "Noto Sans JP", "Noto Sans KR",
|
||||
"Microsoft JhengHei", "PingFang TC", sans-serif;
|
||||
}
|
||||
a { color: var(--accent); }
|
||||
|
||||
.layout { display: flex; min-height: 100vh; }
|
||||
|
||||
/* ---------- 側邊欄 ---------- */
|
||||
#sidebar {
|
||||
width: 280px;
|
||||
flex-shrink: 0;
|
||||
background: var(--panel);
|
||||
border-right: 1px solid var(--line);
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
.brand { display: flex; align-items: center; justify-content: space-between; }
|
||||
.brand a { display: flex; align-items: center; gap: 10px; color: var(--text); text-decoration: none;
|
||||
font-weight: 800; font-size: 20px; }
|
||||
.brand .logo { border-radius: 8px; object-fit: cover; }
|
||||
#sidebar-body { display: flex; flex-direction: column; gap: 24px; flex: 1; }
|
||||
#sidebar h2 { font-size: 18px; margin: 0 0 4px; }
|
||||
|
||||
form { display: flex; flex-direction: column; gap: 12px; }
|
||||
label { display: flex; flex-direction: column; gap: 4px; font-size: 14px; color: var(--muted); }
|
||||
input, textarea, select {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
width: 100%;
|
||||
}
|
||||
input:focus, textarea:focus, select:focus { outline: 2px solid var(--accent); outline-offset: 0; }
|
||||
#code { letter-spacing: .4em; font-size: 20px; text-align: center; }
|
||||
textarea { resize: vertical; min-height: 120px; }
|
||||
|
||||
button, .button {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-2);
|
||||
color: var(--text);
|
||||
border-radius: 999px;
|
||||
padding: 9px 20px;
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 700; }
|
||||
button.link { background: none; border: none; padding: 0; color: var(--accent); border-radius: 0; }
|
||||
button.link:disabled { color: var(--muted); }
|
||||
.icon-btn { padding: 4px 10px; border-radius: 8px; font-size: 20px; }
|
||||
|
||||
.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
|
||||
.spacer { flex: 1; }
|
||||
.hint { font-size: 13px; color: var(--muted); margin: 0; }
|
||||
.muted { color: var(--muted); }
|
||||
.error { color: var(--error); font-size: 14px; margin: 0; }
|
||||
|
||||
#me-box { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; }
|
||||
.me-name { font-size: 20px; font-weight: 700; word-break: break-word; }
|
||||
.me-nav { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; margin-top: 12px; }
|
||||
.me-nav a { text-decoration: none; }
|
||||
|
||||
.avatar { border-radius: 50%; object-fit: cover; background: var(--panel-2); width: 96px; height: 96px; }
|
||||
.avatar.large { width: 160px; height: 160px; }
|
||||
|
||||
.beta { font-size: 12px; font-weight: 600; color: var(--muted); }
|
||||
|
||||
/* UID:特殊序號用背景色標示(和小卡的 server/app/titles.py TIER_COLORS 一致) */
|
||||
.uid { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.uid.tier-admin, .uid.tier-1919810, .uid.tier-114514 {
|
||||
display: inline-block;
|
||||
font-weight: 700;
|
||||
padding: 2px 10px;
|
||||
border-radius: 8px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.uid.tier-admin { background: #f5c518; color: #1e1a24; }
|
||||
.uid.tier-1919810 { background: #f07c2a; color: #1e1a24; }
|
||||
.uid.tier-114514 { background: #2f7beb; color: #fff; }
|
||||
|
||||
.lang { margin-top: auto; }
|
||||
|
||||
/* ---------- 主畫面 ---------- */
|
||||
#main { flex: 1; padding: 40px 24px; display: flex; justify-content: center; }
|
||||
#view-checkin, #view-user, #view-upload, #view-review { width: 100%; max-width: 560px; }
|
||||
#view-upload h1, #view-review h1 { font-size: 24px; margin: 0 0 8px; }
|
||||
#view-upload h2 { font-size: 18px; margin: 28px 0 12px; }
|
||||
.center { display: flex; flex-direction: column; align-items: center; gap: 16px; text-align: center; }
|
||||
.center-text { text-align: center; }
|
||||
|
||||
.big-mark { font-size: 72px; font-weight: 900; letter-spacing: .1em; color: var(--accent); margin-top: 10vh; }
|
||||
|
||||
/* 簽到按鈕:圓角方形,平常是 checkin-0,按下去換成 checkin-1 + 音效 + 粒子 */
|
||||
.checkin-btn {
|
||||
position: relative;
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
margin-top: 8vh;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border-radius: 28%;
|
||||
border: 3px solid var(--accent);
|
||||
background: var(--panel-2);
|
||||
box-shadow: 0 16px 48px #f0a43a44;
|
||||
transition: transform .15s;
|
||||
}
|
||||
.checkin-btn img { width: 100%; height: 100%; object-fit: cover; display: block; user-select: none; }
|
||||
.checkin-label {
|
||||
position: absolute;
|
||||
left: 0; right: 0; bottom: 0;
|
||||
padding: 6px 0 8px;
|
||||
background: linear-gradient(transparent, #000c 70%);
|
||||
color: #fff;
|
||||
font-size: 22px;
|
||||
font-weight: 900;
|
||||
letter-spacing: .1em;
|
||||
}
|
||||
.checkin-btn:hover:not(:disabled) { transform: scale(1.04); }
|
||||
.checkin-btn:active:not(:disabled) { transform: scale(.97); }
|
||||
.checkin-btn:disabled { opacity: 1; }
|
||||
.checkin-btn.pressed { animation: press-pop .45s ease-out; }
|
||||
@keyframes press-pop {
|
||||
0% { transform: scale(.92); }
|
||||
45% { transform: scale(1.1) rotate(-2deg); }
|
||||
100% { transform: scale(1); }
|
||||
}
|
||||
|
||||
/* 粒子:位置、方向、距離、顏色由 app.js 用 CSS 變數指定 */
|
||||
.particle {
|
||||
position: fixed;
|
||||
left: var(--x);
|
||||
top: var(--y);
|
||||
width: var(--s);
|
||||
height: var(--s);
|
||||
border-radius: 50%;
|
||||
background: var(--c);
|
||||
pointer-events: none;
|
||||
z-index: 20;
|
||||
animation: burst var(--d, .9s) cubic-bezier(.12, .75, .3, 1) forwards;
|
||||
}
|
||||
.particle.digit {
|
||||
width: auto;
|
||||
height: auto;
|
||||
background: none;
|
||||
color: var(--c);
|
||||
font-size: var(--s);
|
||||
font-weight: 900;
|
||||
line-height: 1;
|
||||
text-shadow: 0 2px 6px #0008;
|
||||
}
|
||||
@keyframes burst {
|
||||
from { transform: translate(-50%, -50%) scale(1); opacity: 1; }
|
||||
70% { opacity: 1; }
|
||||
to { transform: translate(calc(-50% + var(--dx)), calc(-50% + var(--dy))) scale(.3) rotate(var(--r)); opacity: 0; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.particle { display: none; }
|
||||
.checkin-btn.pressed { animation: none; }
|
||||
}
|
||||
|
||||
.checkin-msg { font-size: 22px; font-weight: 700; margin: 0; }
|
||||
.card-img { width: 100%; height: auto; border-radius: 16px; box-shadow: 0 12px 40px #0008; background: var(--panel); }
|
||||
.stats { color: var(--muted); margin: 0; font-size: 15px; }
|
||||
.actions { justify-content: center; }
|
||||
|
||||
/* ---------- 投稿 / 審核 ---------- */
|
||||
.upload-bar { margin-top: 16px; }
|
||||
.upload-bar label.button { color: var(--accent-ink); background: var(--accent); border-color: var(--accent); font-weight: 700; }
|
||||
.upload-bar label.button.busy { opacity: .5; pointer-events: none; }
|
||||
.sub-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 12px; }
|
||||
.sub-item { position: relative; border-radius: 10px; overflow: hidden; background: var(--panel-2); aspect-ratio: 1; }
|
||||
.sub-item img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.sub-status {
|
||||
position: absolute;
|
||||
left: 6px; bottom: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
background: #000b;
|
||||
color: var(--text);
|
||||
}
|
||||
.sub-status.approved { background: #2f9e5a; color: #fff; }
|
||||
.sub-status.rejected { background: #6b3a3a; color: #fff; }
|
||||
.review-img { max-width: 100%; max-height: 60vh; border-radius: 12px; background: var(--panel); box-shadow: 0 12px 40px #0008; }
|
||||
.review-meta { margin: 0; line-height: 1.9; }
|
||||
#review-name { font-weight: 700; text-decoration: none; }
|
||||
|
||||
.profile { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
|
||||
.profile h1 { margin: 12px 0 0; font-size: 28px; word-break: break-word; }
|
||||
|
||||
.bio {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 4px 20px;
|
||||
margin-top: 16px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.bio pre { overflow-x: auto; background: var(--panel-2); padding: 12px; border-radius: 8px; }
|
||||
.bio code { background: var(--panel-2); padding: 1px 5px; border-radius: 4px; }
|
||||
.bio pre code { padding: 0; }
|
||||
.bio blockquote { margin: 0; padding-left: 12px; border-left: 3px solid var(--line); color: var(--muted); }
|
||||
.bio table { border-collapse: collapse; }
|
||||
.bio th, .bio td { border: 1px solid var(--line); padding: 4px 8px; }
|
||||
.bio.empty { color: var(--muted); padding: 16px 20px; }
|
||||
|
||||
/* ---------- 編輯個人資料 ---------- */
|
||||
dialog {
|
||||
width: min(560px, calc(100vw - 32px));
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
}
|
||||
dialog::backdrop { background: #000a; }
|
||||
dialog h2 { margin: 0 0 4px; }
|
||||
.avatar-edit { display: flex; gap: 16px; align-items: center; }
|
||||
.avatar-edit .button { margin-bottom: 6px; }
|
||||
.preview { margin-top: 0; max-height: 300px; overflow-y: auto; }
|
||||
.dialog-actions { margin-top: 8px; }
|
||||
|
||||
#toast {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: 32px;
|
||||
transform: translateX(-50%);
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line);
|
||||
padding: 10px 20px;
|
||||
border-radius: 999px;
|
||||
box-shadow: 0 8px 24px #0008;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.only-mobile { display: none; }
|
||||
|
||||
/* ---------- 手機:側欄收到上方 ---------- */
|
||||
@media (max-width: 760px) {
|
||||
.layout { flex-direction: column; }
|
||||
#sidebar { width: 100%; border-right: none; border-bottom: 1px solid var(--line); padding: 12px 16px; gap: 12px; }
|
||||
.only-mobile { display: inline-flex; }
|
||||
#sidebar:not(.open) #sidebar-body { display: none; }
|
||||
#sidebar-body { padding-bottom: 8px; }
|
||||
#main { padding: 24px 16px; }
|
||||
.checkin-btn { width: 180px; height: 180px; margin-top: 6vh; }
|
||||
.checkin-label { font-size: 18px; }
|
||||
.big-mark { font-size: 56px; margin-top: 6vh; }
|
||||
}
|
||||