This commit is contained in:
Sahik committed 2026-11-22 18:38:53 +08:00
commit 21851bf8c5
61 files changed
+5260

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
.env
.git
**/__pycache__
**/.pytest_cache
server/.venv
server/tests
data
image
icon
tools
media-src
+28
View File
@@ -0,0 +1,28 @@
# 對外網址:分享連結、og:image、信件裡的連結都用這個
PUBLIC_URL=https://zhiwu-project.sthkm3.org
# 經 cloudflared(https)對外時設 1,登入 cookie 只走 https(本機 http://127.0.0.1 也能用)
COOKIE_SECURE=1
# 1 = 網頁標題加 (Beta)、小卡右下角加 · Beta
BETA=0
# 本機除錯用的 port(只綁 127.0.0.1)。容器內固定是 2040,cloudflared 指到 http://zhiwuproject:2040
PORT=2041
# cloudflared 容器所在的 Docker 網路名稱(docker network ls);沒有就先 docker network create tunnel
TUNNEL_NETWORK=tunnel
# ---- 寄信(SMTP,容器主動連出去,不經過 tunnel)----
# 帳密留空 = 不寄信,驗證碼印在 log(docker compose logs zhiwuproject)
# Resend: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 zhiwuproject python -m app.admin totp-uri
ADMIN_LOGIN=
ADMIN_TOTP=
+9
View File
@@ -0,0 +1,9 @@
.env
*.ipynb
__pycache__/
.pytest_cache/
.venv/
data/
# 圖庫(使用者自己提供)
image/
+183
View File
@@ -0,0 +1,183 @@
# 吱鼯計畫
> 你今天吱吱了嗎
每天吱吱簽到一次,產生一張吱吱小卡(簽到天數 + 吱吱次數 + 隨機圖片),可以圖文分享。
用信箱驗證碼註冊、登入(沒有密碼)。介面支援繁中、簡中、日、韓、英。網址是 `zhiwu-project.sthkm3.org`。
寫法沿用 My_INMU(FastAPI + SQLite + 純 HTML/JS),差別在簽到畫面和吱吱次數。
| 服務 | 內容 | port |
|---|---|---|
| `zhiwuproject` | FastAPI + SQLite:API、網站、小卡圖片(Pillow + Noto Sans CJK) | 容器內 `2040`;本機除錯 `127.0.0.1:2041` |
## 啟動
```
cp .env.example .env # SMTP_USER / SMTP_PASSWORD 留空時驗證碼印在 log
docker network create tunnel # 只有第一次;已經有 cloudflared 的網路就把名稱填進 .env 的 TUNNEL_NETWORK
docker compose up -d --build
```
打開 `http://127.0.0.1:2041`,輸入信箱後用 `docker compose logs zhiwuproject` 找驗證碼(`[DEV] verify code for ...`)。
| 指令 | 用途 |
|---|---|
| `docker compose logs -f zhiwuproject` | log(SMTP 帳密沒填時,驗證碼印在這裡) |
| `docker compose down` | 停止(資料保留) |
| `docker compose down -v` | 停止並刪除 volume `zhiwuproject_zhiwu-data`(清空帳號與簽到紀錄) |
| `docker compose exec zhiwuproject python -m app.admin info <email>` | 查看帳號 |
| `docker compose exec zhiwuproject python -m app.admin grant-uid <email> 777` | 把帳號的 UID 換成指定號碼(1–99999999) |
| `docker compose exec zhiwuproject python -m app.admin unlock` | 解除管理員登入鎖定 |
| `docker compose exec zhiwuproject python -m app.admin totp-uri` | 印出 Aegis 用的 `otpauth://` 連結(換手機時用) |
| `docker compose exec zhiwuproject python -m app.admin reset-progress --yes` | 清空所有簽到進度與吱吱次數(保留帳號;不加 `--yes` 只顯示會刪什麼) |
## 對外部署(zhiwu-project.sthkm3.org)
cloudflared 用容器名稱連進來,所以兩個容器要在同一個 Docker 網路:
1. `.env`:`PUBLIC_URL=https://zhiwu-project.sthkm3.org`、`COOKIE_SECURE=1`、`TUNNEL_NETWORK=<cloudflared 所在的網路>`(`docker network ls` 查)
2. Cloudflare 後台的 Public Hostname:`zhiwu-project.sthkm3.org → http://zhiwuproject:2040`
3. `docker compose up -d --build`
- 容器名稱與 hostname 固定是 `zhiwuproject`,容器內固定聽 `2040`
- `.env` 的 `PORT`(預設 2041)只是把容器的 2040 綁到本機 `127.0.0.1` 方便除錯,tunnel 不經過它;預設不用 2040 是為了不和同一台機器上的 My_INMU 相撞
- 寄信是容器主動連到 SMTP 伺服器,不經過 tunnel。`MAIL_FROM` 的網域要和寄信服務驗證過的網域相同
備份:volume `zhiwuproject_zhiwu-data` 裡的 `zhiwu.db`、`avatars/`、`submissions/`(`cards/` 是快取,可以刪),以及 `image/`。
## 吱吱(簽到畫面)
今天還沒簽到時,登入後整個畫面會被吱吱影片蓋住:
1. 還沒點擊:停在影片第一幀,中間寫「點擊吱吱」
2. 點一下:影片有聲播到完(約 1.6 秒),同時送出簽到
3. 影片播完、小卡也下載好之後,亮出小卡
小卡下方的「**繼續吱吱**」會回到同一個全螢幕畫面:點一下播一次、吱吱次數 +1,播完才能再點(播放中點了沒有反應),不會跳去小卡;按左上角「回到小卡」離開,小卡會換成新的次數。
繼續吱吱畫面中下方有「**全自動吱吱**」開關:打開後每播完一次就自動接著吱下一次(一樣一次 +1、受一秒一次的限制),再按一次或回到小卡就停止。
左上角的「等等再吱」可以先關掉全螢幕(用側欄、換語言、登出),頁面上會留一個「去吱吱」的入口。
### 兩個獨立的數字
| | 怎麼加 | 存在哪 |
|---|---|---|
| 簽到天數(累計 / 連續) | 每天(台灣時間 04:00 換日)第一次吱吱 +1 | `checkins` 一天一筆 |
| 吱吱次數 | 每吱一下 +1:簽到那一下算一次,繼續吱吱每點一下算一次 | `users.clicks` |
- 繼續吱吱每點一下就送一次 `POST /api/zhi {n: 1}`;沒送成功的會留著補送
- **一個帳號一秒只能吱一次**:伺服器端也擋,同一秒內多送的、或一次送很多下的,都只算一下(`config.py` 的 `ZHI_RATE` / `ZHI_BURST`)
- 兩個數字都顯示在小卡、個人頁和簽到頁
### 影片與圖標
原檔不打包進 Docker,換檔後重新產生再 build:
```
server/.venv/Scripts/python -m pip install imageio-ffmpeg # 自帶 ffmpeg
server/.venv/Scripts/python tools/make_media.py # media-src/zhizhi.mp4 → web/media/zhizhi.mp4(faststart)、zhizhi-poster.webp(第一幀)
server/.venv/Scripts/python tools/make_icons.py # icon/zhiwu.jpg → web/ 的 favicon.ico、icon-192/512.png、apple-touch-icon.png、logo.png
docker compose up -d --build
```
`make_icons.py` 也會產生 `server/app/assets/default-meme.jpg`:圖庫是空的時候小卡用這張。
## 圖庫
放在 `image/`(jpg / png / webp / gif 取第一幀),容器掛載成 `/memes`。
每次簽到時隨機抽一張,檔名存進資料庫,所以同一天的小卡重畫也一樣。新增圖片不用重啟;**已經被抽過的圖片不要改名或刪除**,否則舊的小卡會變成預設圖。
### 使用者投稿
- 登入後側欄的「投稿圖片」(`/upload`):每個帳號每天最多 5 張(台灣時間 04:00 重置,被拒絕的也算),每張上限 5MB
- 上傳的圖會重新編碼成 JPEG(有透明度就用 PNG),去掉 EXIF / GPS;長邊超過 2048 會縮小
- 待審的檔案放在 volume 的 `/data/submissions/<id>.<ext>`
- 管理員側欄的「審核投稿 (N)」(`/review`)一次顯示一張,按同意或拒絕:
- 同意:存成 `image/zhiwu_<目前最大編號 + 1>.jpg`(所以 `image/` 要可寫入),馬上加入抽卡
- 拒絕:刪掉檔案,紀錄保留(用來算額度)
## UID
- UID 顯示成 8 碼(`00000001`),資料庫存整數。`00000000` 是管理員(黃底標示),一般使用者從 `00000001` 開始依序給號
- 預設名稱是 `吱鼯_<uid>`
- 給號用 `meta.next_uid`,不用 `AUTOINCREMENT`:否則 `grant-uid` 給出很大的號碼之後,之後的號碼會全部跳過去
### 顏色與稱號
管理員可以幫任何 UID 指定一個顏色和一個稱號(只是顯示用,不帶權限)。顏色會套在 UID 和稱號上,顯示在側欄、個人頁、審核頁和小卡。
- 網頁:用管理員登入後打開對方的個人頁 `/u/<uid>`,下方會多一個「稱號與顏色」表單;「清除」可以拿掉
- 指令:`docker compose exec zhiwuproject python -m app.admin set-title <uid> --title 稱號 --color '#ff8a1f'`(`--clear` 清除)
- 稱號最多 16 個字,可以留空只上顏色;只給稱號沒選顏色時用主色。文字顏色會依底色的亮度自動選深色或白色
- 管理員自己沒指定時維持預設的黃底
## 管理員
- `.env` 設定 `ADMIN_LOGIN`(信箱欄要輸入的字)和 `ADMIN_TOTP`(base32 密鑰),改完執行 `docker compose up -d`。兩個都留空就停用管理員登入
- 登入:在網頁的信箱欄輸入 `ADMIN_LOGIN`,按「寄送驗證碼」(不會真的寄信),再輸入 Aegis 上的 6 位數(TOTP、SHA1、6 位、30 秒)
- 錯 3 次就全域鎖定(15 分、30 分、1 小時…上限 24 小時);每組碼只能用一次;session 有效 7 天
- 被自己鎖住時,執行 `python -m app.admin unlock`
`.env` 的 `BETA=1` 會在網頁標題加「(Beta)」、小卡右下角加「· Beta」;預設是 0。
## API
會改資料的 `/api` 請求要帶 header `X-ZHIWU: 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 字;回傳含 `total_days`、`streak`、`clicks` |
| `PUT /api/me/avatar`(multipart `file`) | 上限 5MB,裁成 1024×1024 WebP |
| `POST /api/checkin`、`GET /api/checkin/today` | `{day, checked_in, already?, total_days, streak, clicks, next_reset, card_url?, share_url?, share_text?}` |
| `POST /api/zhi {n}` | 繼續吱吱:吱吱次數 +1(一個帳號一秒一次)。回傳 `{clicks, added}`,`added` 是實際加的(被限流時是 0) |
| `GET /api/users/{uid}?lang=` | 公開個人資料(含 `title`、`title_color`、`uid_tier`) |
| `PUT /api/admin/users/{uid}/title {title, color}` | 管理員:指定 UID 的稱號與顏色(`#rrggbb`);兩個都空 = 清除 |
| `POST /api/markdown {md}` | 自介預覽 |
| `GET /card/{uid}/{day}.png` | 小卡。快取在 `/data/cards/<uid>/<day>.v<版本>.c<吱吱次數>.png`,次數變了就重畫;網頁會加 `?c=<次數>` |
| `GET /c/{uid}/{day}` | 分享頁(`og:image`) |
| `GET /avatars/{uid}.webp`、`GET /healthz` | |
| `POST /api/submissions`(multipart `file`)、`GET /api/submissions` | 投稿圖片(每天 5 張)、自己最近 30 筆 |
| `GET /api/submissions/{id}/image` | 只有上傳者本人和管理員看得到 |
| `GET /api/admin/submissions`、`POST /api/admin/submissions/{id}/approve`、`/reject` | 管理員審核 |
每日分界是**台灣時間 04:00**(程式固定用 `Asia/Taipei`)。
## 開發
```
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 MEME_DIR=../image .venv/Scripts/python -m uvicorn app.main:app --port 2040 --reload
```
直接跑 uvicorn 不會讀 `.env`(那是給 docker compose 用的),所以不會寄信,驗證碼印在終端機。
本機沒有 Noto Sans CJK 時,小卡會改用 Windows 內建字型(`FONT_REGULAR` / `FONT_BOLD` 可以指定)。
## 檔案
```
server/app/
main.py 路由、CSRF header 檢查、靜態檔
auth.py 驗證碼登入、session
users.py UID 給號、個人資料、大頭貼、自介 Markdown
checkin.py 簽到、累計 / 連續天數、抽圖、吱吱次數(/api/zhi)
submissions.py 使用者投稿圖片、管理員審核
card.py 畫小卡
share.py 分享頁
admin.py 管理指令
mailer.py SMTP 寄信
i18n/ 信件、小卡、分享文字
assets/ 小卡的預設圖
web/ 網站(純 HTML/JS);i18n/ 是介面文字,media/ 是吱吱影片與第一幀
image/ 圖庫(管理員同意的投稿也會寫進來)
icon/、media-src/ 圖標與影片的原檔(不打包進 Docker)
tools/ make_icons.py、make_media.py
```
+49
View File
@@ -0,0 +1,49 @@
# 吱鼯計畫:簽到伺服器(FastAPI + SQLite)與網站
# 用法:複製 .env.example 成 .env 後執行 docker compose up -d --build
# 對外:cloudflared 的 Public Hostname zhiwu-project.sthkm3.org → http://zhiwuproject:2040
name: zhiwuproject
services:
zhiwuproject:
container_name: zhiwuproject # cloudflared 用這個名字連進來(http://zhiwuproject:2040)
hostname: zhiwuproject
build:
context: .
dockerfile: server/Dockerfile
environment:
PUBLIC_URL: ${PUBLIC_URL:-http://127.0.0.1:2041}
COOKIE_SECURE: ${COOKIE_SECURE:-0}
BETA: ${BETA:-0} # 1 = 網頁標題與小卡標示 Beta
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:
- zhiwu-data:/data # zhiwu.db、avatars/、cards/、submissions/
- ./image:/memes # 圖庫放在 image/;管理員同意的投稿也會寫進這裡(zhiwu_<n>.jpg)
ports:
# 只給本機除錯用(http://127.0.0.1:2041)。tunnel 走容器網路的 2040,不經過這裡
- "127.0.0.1:${PORT:-2041}:2040"
networks:
- tunnel
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
networks:
# cloudflared 容器所在的網路,兩邊在同一個網路才能用容器名稱互連。
# 名稱寫在 .env 的 TUNNEL_NETWORK(docker network ls 可以查);沒有就先建:docker network create tunnel
tunnel:
external: true
name: ${TUNNEL_NETWORK:-tunnel}
volumes:
zhiwu-data:
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.
+22
View File
@@ -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"]
View File
Whitespace-only changes.
+159
View File
@@ -0,0 +1,159 @@
"""管理指令(在容器裡執行):
docker compose exec zhiwuproject python -m app.admin info <email>
docker compose exec zhiwuproject python -m app.admin grant-uid <email> 777
docker compose exec zhiwuproject python -m app.admin set-title <uid> --title 稱號 --color '#ff8a1f' # --clear 清除
docker compose exec zhiwuproject python -m app.admin test-mail <email>
docker compose exec zhiwuproject python -m app.admin unlock # 解除管理員登入鎖定
docker compose exec zhiwuproject python -m app.admin totp-uri # 印出 Aegis 用的 otpauth:// 連結
docker compose exec zhiwuproject 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_set_title(args):
"""指定某個 UID 的顏色與稱號;--clear 清除。網頁上管理員也可以在個人頁設定。"""
from .titles import DEFAULT_TITLE_COLOR, valid_color
from . import card
title, color = ("", "") if args.clear else (args.title.strip(), args.color.strip().lower())
if len(title) > config.TITLE_MAX:
sys.exit(f"稱號最多 {config.TITLE_MAX} 個字")
if color and not valid_color(color):
sys.exit("顏色要寫成 #rrggbb,例如 #ff8a1f")
if title and not color:
color = DEFAULT_TITLE_COLOR
conn = db.connect()
cur = conn.execute("UPDATE users SET title = ?, title_color = ? WHERE uid = ?", (title, color, args.uid))
if cur.rowcount == 0:
sys.exit("找不到這個 UID")
card.invalidate(args.uid)
print(f"uid={fmt_uid(args.uid)} title={title!r} color={color or '-'}")
def cmd_grant_uid(args):
"""把某個帳號的 UID 換成指定號碼(1–99999999,例如 777)。不會影響之後的依序給號。"""
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"zhiwu.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")
conn.execute("UPDATE users SET clicks = 0")
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("set-title", help="指定 UID 的顏色與稱號")
s.add_argument("uid", type=int)
s.add_argument("--title", default="")
s.add_argument("--color", default="", help="#rrggbb")
s.add_argument("--clear", action="store_true", help="清除稱號與顏色")
s.set_defaults(func=cmd_set_title)
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()
Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

+192
View File
@@ -0,0 +1,192 @@
"""信箱驗證碼登入(沒有密碼):第一次驗證成功就自動建立帳號。
管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 Aegis 算的 TOTP(不寄信)。錯 3 次就全域鎖定,時間逐次加倍。
"""
import re
import secrets
import sqlite3
import threading
import time
from collections import defaultdict, deque
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel
from . import clock, config, db, mailer, totp
from .db import get_db, get_meta, set_meta, transaction
from .deps import client_ip, current_user, fail, session_token, sha256
from .i18n import norm_lang
from .users import create_user, profile
router = APIRouter()
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
# 同一 IP 的寄信次數(單一 worker,放記憶體就夠)
_ip_hits: dict[str, deque] = defaultdict(deque)
_ip_lock = threading.Lock()
def ip_allowed(ip: str) -> bool:
now = time.monotonic()
with _ip_lock:
q = _ip_hits[ip]
while q and q[0] < now - config.IP_WINDOW:
q.popleft()
if len(q) >= config.IP_LIMIT:
return False
q.append(now)
return True
def is_admin_login(raw: str) -> bool:
return db.admin_ok and raw.strip().lower() == config.ADMIN_LOGIN.lower()
def norm_email(email: str) -> str:
email = email.strip().lower()
if len(email) > 254 or not EMAIL_RE.match(email):
fail(400, "invalid_email")
return email
class CodeRequest(BaseModel):
email: str
lang: str = config.DEFAULT_LANG
class VerifyRequest(BaseModel):
email: str
code: str
lang: str = config.DEFAULT_LANG
@router.post("/api/auth/request-code")
def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection = Depends(get_db)):
sent = {"status": "sent", "expires_in": config.CODE_TTL, "resend_in": config.CODE_RESEND}
if is_admin_login(body.email):
# 管理員不寄信,驗證碼看 Aegis。回應和一般信箱完全相同
if not ip_allowed(client_ip(request)):
fail(429, "too_many_requests")
return sent
email = norm_email(body.email)
now = clock.ts()
conn.execute("DELETE FROM login_codes WHERE expires_at < ?", (now,))
old = conn.execute("SELECT last_sent_at FROM login_codes WHERE email = ?", (email,)).fetchone()
if old and now - old["last_sent_at"] < config.CODE_RESEND:
fail(429, "too_many_requests")
if not ip_allowed(client_ip(request)):
fail(429, "too_many_requests")
# secrets 才是密碼學安全的亂數
code = f"{secrets.randbelow(10**6):06d}"
conn.execute(
"INSERT INTO login_codes(email, code_hash, attempts, expires_at, last_sent_at) VALUES (?, ?, 0, ?, ?) "
"ON CONFLICT(email) DO UPDATE SET code_hash = excluded.code_hash, attempts = 0, "
"expires_at = excluded.expires_at, last_sent_at = excluded.last_sent_at",
(email, sha256(code), now + config.CODE_TTL, now),
)
try:
mailer.send_code(email, code, norm_lang(body.lang))
except Exception as e:
print("Error sending email:", e, flush=True)
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(502, "send_failed")
return sent
def admin_check(conn: sqlite3.Connection, code: str, ip: str) -> str | None:
"""比對管理員 TOTP。成功回傳 None,失敗回傳錯誤代碼。
計數寫在交易裡,同時送出多個請求也不會多猜幾次。"""
now = clock.ts()
with transaction(conn):
if now < get_meta(conn, "admin_lock_until"):
return "too_many_requests"
step = totp.verify(config.ADMIN_TOTP, code, now)
if step is not None and step <= get_meta(conn, "admin_last_step"):
# 碼是對的但用過了(例如登出後馬上用同一組再登入):拒絕,但不算猜錯、不計入鎖定。
# 拿得到正確的碼才會發生,不是暴力猜碼
return "code_used"
if step is not None:
set_meta(conn, "admin_fails", 0)
set_meta(conn, "admin_lock_level", 0)
set_meta(conn, "admin_last_step", step)
print(f"[ADMIN] login from {ip}", flush=True)
return None
fails = get_meta(conn, "admin_fails") + 1
print(f"[ADMIN] login failed from {ip} ({fails}/{config.ADMIN_MAX_FAILS})", flush=True)
if fails < config.ADMIN_MAX_FAILS:
set_meta(conn, "admin_fails", fails)
return "wrong_code"
level = get_meta(conn, "admin_lock_level")
lock = min(config.ADMIN_LOCK_BASE * 2 ** level, config.ADMIN_LOCK_MAX)
set_meta(conn, "admin_fails", 0)
set_meta(conn, "admin_lock_level", level + 1)
set_meta(conn, "admin_lock_until", now + lock)
print(f"[ADMIN] locked for {lock // 60} min", flush=True)
return "too_many_requests"
def issue_session(conn: sqlite3.Connection, response: Response, user: sqlite3.Row) -> dict:
now = clock.ts()
ttl = config.ADMIN_SESSION_TTL if user["uid"] == config.ADMIN_UID else config.SESSION_TTL
token = secrets.token_urlsafe(32)
conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,))
conn.execute(
"INSERT INTO sessions(token_hash, uid, created_at, expires_at) VALUES (?, ?, ?, ?)",
(sha256(token), user["uid"], now, now + ttl),
)
response.set_cookie(
config.COOKIE_NAME, token, max_age=ttl,
httponly=True, secure=config.COOKIE_SECURE, samesite="lax", path="/",
)
# token 也放在 JSON,之後 Android 用 Authorization: Bearer <token>
return {"token": token, "user": profile(conn, user, user["lang"], private=True)}
@router.post("/api/auth/verify")
def verify(body: VerifyRequest, request: Request, response: Response,
conn: sqlite3.Connection = Depends(get_db)):
if is_admin_login(body.email):
err = admin_check(conn, body.code.strip(), client_ip(request))
if err:
fail(429 if err == "too_many_requests" else 400, err)
admin = conn.execute("SELECT * FROM users WHERE uid = ?", (config.ADMIN_UID,)).fetchone()
return issue_session(conn, response, admin)
email = norm_email(body.email)
code = body.code.strip()
now = clock.ts()
row = conn.execute("SELECT * FROM login_codes WHERE email = ?", (email,)).fetchone()
if row is None:
fail(400, "not_requested")
if row["expires_at"] < now:
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(400, "expired")
# 錯太多次直接作廢,防止暴力猜碼
if not secrets.compare_digest(sha256(code), row["code_hash"]):
attempts = row["attempts"] + 1
if attempts >= config.CODE_MAX_ATTEMPTS:
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(400, "expired")
conn.execute("UPDATE login_codes SET attempts = ? WHERE email = ?", (attempts, email))
fail(400, "wrong_code")
# 驗證碼只能用一次
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
user = create_user(conn, email, body.lang)
return issue_session(conn, response, user)
@router.post("/api/auth/logout")
def logout(request: Request, response: Response, user=Depends(current_user),
conn: sqlite3.Connection = Depends(get_db)):
token = session_token(request)
if token:
conn.execute("DELETE FROM sessions WHERE token_hash = ?", (sha256(token),))
response.delete_cookie(config.COOKIE_NAME, path="/")
return {"status": "ok"}
+225
View File
@@ -0,0 +1,225 @@
"""用 Pillow 畫吱吱小卡(1080×1350 PNG),第一次被請求時才畫,之後快取在 /data/cards/<uid>/。
小卡上有吱吱(點擊)次數,所以快取檔名帶次數:<day>.v<版本>.c<次數>.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 badge_colors, fmt_uid
Image.MAX_IMAGE_PIXELS = 40_000_000 # 擋解壓縮炸彈
router = APIRouter()
W, H = 1080, 1350
PAD = 48
ACCENT = (255, 138, 31)
TEXT = (255, 246, 234)
MUTED = (217, 185, 147)
INK = (42, 20, 0)
DEFAULT_MEME = Path(__file__).resolve().parent / "assets" / "default-meme.jpg"
CARD_VERSION = 1 # 版面改了就加 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, clicks: int) -> Image.Image:
lang = norm_lang(user["lang"])
uid = user["uid"]
# 背景:上下漸層
img = Image.new("RGB", (W, H))
top, bottom = (70, 38, 12), (24, 13, 5)
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), (18, 10, 4))
pic = load_image(config.MEME_DIR / meme) if meme else None
pic = pic or load_image(DEFAULT_MEME) # 圖庫是空的(或圖被刪了)就用預設圖
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=INK, 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)}"
colors = badge_colors(user)
uid_y = av_y + 120 # UID 這一行的垂直中心
if colors:
bg, fg = colors
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")
if user["title"]: # 稱號:接在 UID 後面,同樣的顏色
x = tx + tw + 36 + 16
f_title = font(lang, 36, True)
title = fit_text(d, user["title"], f_title, int(W - PAD - x - 36))
ttw = d.textlength(title, font=f_title)
d.rounded_rectangle((x, uid_y - 28, x + ttw + 36, uid_y + 28), 14, fill=bg)
d.text((x + 18, uid_y), title, font=f_title, 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=(110, 72, 36), width=2)
f_num = font("en", 92, True)
num = f"{clicks:,}"
num_w = d.textlength(num, font=f_num)
d.text((W - PAD, line_y + 24), num, font=f_num, fill=ACCENT, anchor="ra")
d.text((W - PAD, line_y + 148), t(lang, "card.clicks"), font=font(lang, 36), fill=MUTED, anchor="ra")
f_day = font(lang, 92, True)
d.text((PAD, line_y + 24), fit_text(d, t(lang, "card.day", n=total), f_day, int(W - 2 * PAD - num_w - 40)),
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
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
folder = card_dir(uid)
path = folder / f"{day}.v{CARD_VERSION}.c{user['clicks']}.png"
if path.exists():
return path
total, streak = stats(conn, uid, day)
img = render(user, day, row["meme"], total, streak, user["clicks"])
folder.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
with os.fdopen(fd, "wb") as f:
img.save(f, "PNG", optimize=True)
os.replace(tmp, path)
# 同一天舊次數的小卡不會再用到
for old in folder.glob(f"{day}.v*.png"):
if old != path:
try:
old.unlink()
except OSError:
pass # Windows 上別的請求正在讀,下次再刪
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=60"})
+133
View File
@@ -0,0 +1,133 @@
import secrets
import sqlite3
import time
from datetime import date, timedelta
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from . import clock, config
from .db import get_db, transaction
from .deps import current_user, fail
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 {
# 前端會自己加 ?c=<吱吱次數>,次數變了就抓新的小卡
"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)
clicks = conn.execute("SELECT clicks FROM users WHERE uid = ?", (user["uid"],)).fetchone()[0]
out = {
"day": day,
"checked_in": checked,
"total_days": total,
"streak": streak,
"clicks": clicks,
"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() # 只取一次,避免剛好跨過換日時前後不一致
with transaction(conn):
# 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()),
)
already = cur.rowcount == 0
if not already:
# 簽到那一下也算一次吱吱
conn.execute("UPDATE users SET clicks = clicks + 1 WHERE uid = ?", (user["uid"],))
return today_payload(conn, user, day, already=already)
# ---------- 繼續吱吱:只加點擊次數,和簽到天數無關 ----------
_now = time.monotonic # 測試會換掉
_buckets: dict[int, tuple[float, float]] = {} # uid -> (剩餘額度, 上次更新時間)
def _take(uid: int, n: int) -> int:
"""token bucket:回傳這次實際可以加幾下(超過速率的部分直接丟掉)。"""
now = _now()
tokens, last = _buckets.get(uid, (float(config.ZHI_BURST), now))
tokens = min(float(config.ZHI_BURST), tokens + (now - last) * config.ZHI_RATE)
ok = min(n, int(tokens))
_buckets[uid] = (tokens - ok, now)
return ok
class ZhiIn(BaseModel):
n: int = 1
@router.post("/api/zhi")
def do_zhi(body: ZhiIn, user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
if not 1 <= body.n <= config.ZHI_BATCH_MAX:
fail(400, "bad_request")
added = _take(user["uid"], body.n)
if added:
conn.execute("UPDATE users SET clicks = clicks + ? WHERE uid = ?", (added, user["uid"]))
clicks = conn.execute("SELECT clicks FROM users WHERE uid = ?", (user["uid"],)).fetchone()[0]
return {"clicks": clicks, "added": added}
@router.get("/api/checkin/today")
def get_today(user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
return today_payload(conn, user, clock.today())
+27
View File
@@ -0,0 +1,27 @@
"""時間集中在這裡,測試只要 monkeypatch `clock.now` 就能模擬換日。"""
from datetime import datetime, timedelta, timezone
from . import config
def now() -> datetime:
return datetime.now(timezone.utc)
def ts() -> int:
return int(now().timestamp())
def today() -> str:
"""簽到日:台灣時間 04:00 換日,格式 YYYY-MM-DD。"""
local = now().astimezone(config.TZ) - timedelta(hours=config.DAY_START_HOUR)
return local.date().isoformat()
def next_reset() -> datetime:
"""下一個台灣時間 04:00(帶時區,前端換算成裝置時間)。"""
local = now().astimezone(config.TZ)
reset = local.replace(hour=config.DAY_START_HOUR, minute=0, second=0, microsecond=0)
if local >= reset:
reset += timedelta(days=1)
return reset
+82
View File
@@ -0,0 +1,82 @@
"""環境變數設定。其他模組一律用 `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", "0") == "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
TITLE_MAX = 16 # 管理員指定的稱號長度上限
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 # 長邊超過就等比例縮小
# 繼續吱吱:一個帳號一秒只能吱一次(token bucket,額度最多存 1 下,所以兩下之間至少隔 1 秒)
ZHI_BATCH_MAX = 200 # 一次請求的 n 上限(超過直接拒絕);實際加幾下由下面兩個值決定
ZHI_RATE = 1 # 每秒補充幾下
ZHI_BURST = 1 # 最多累積幾下
COOKIE_NAME = "zhiwu_session"
+170
View File
@@ -0,0 +1,170 @@
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,
clicks INTEGER NOT NULL DEFAULT 0, -- 吱吱(點擊)總次數,和簽到天數分開算
title TEXT NOT NULL DEFAULT '', -- 管理員指定的稱號(空字串 = 沒有)
title_color TEXT NOT NULL DEFAULT '', -- 管理員指定的 UID 底色 #rrggbb(空字串 = 沒有)
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, -- 同意後的檔名,例如 zhiwu_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 / "zhiwu.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(conn)
_init_admin(conn)
finally:
conn.close()
# 後來才加的 users 欄位:舊的資料庫(CREATE TABLE IF NOT EXISTS 不會補欄位)啟動時自動補上
_USER_COLUMNS = {
"clicks": "INTEGER NOT NULL DEFAULT 0",
"title": "TEXT NOT NULL DEFAULT ''",
"title_color": "TEXT NOT NULL DEFAULT ''",
}
def _migrate(conn: sqlite3.Connection) -> None:
have = {r[1] for r in conn.execute("PRAGMA table_info(users)")}
for name, decl in _USER_COLUMNS.items():
if name not in have:
conn.execute(f"ALTER TABLE users ADD COLUMN {name} {decl}")
def _init_admin(conn: sqlite3.Connection) -> None:
"""建立或更新管理員帳號(uid 0)。改了 ADMIN_LOGIN 重啟就會生效。"""
global admin_ok
from . import totp
admin_ok = False
login, secret = config.ADMIN_LOGIN, config.ADMIN_TOTP
if not login or not secret:
return
try:
if len(totp.decode_secret(secret)) < 10:
raise ValueError("too short")
except Exception:
print("[ERROR] ADMIN_TOTP 不是合法的 base32 密鑰(至少 16 個字元),管理員登入停用", flush=True)
return
clash = conn.execute("SELECT uid FROM users WHERE email = ? AND uid != ?",
(login, config.ADMIN_UID)).fetchone()
if clash:
print(f"[ERROR] ADMIN_LOGIN 和 UID {clash[0]} 的信箱相同,管理員登入停用", flush=True)
return
conn.execute(
"INSERT INTO users(uid, email, display_name, lang, created_at) VALUES (?, ?, ?, ?, ?) "
"ON CONFLICT(uid) DO UPDATE SET email = excluded.email",
(config.ADMIN_UID, login, "管理員", config.DEFAULT_LANG, int(time.time())),
)
admin_ok = True
def get_meta(conn: sqlite3.Connection, key: str, default: int = 0) -> int:
row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
return row[0] if row else default
def set_meta(conn: sqlite3.Connection, key: str, value: int) -> None:
conn.execute("INSERT INTO meta(key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, value))
def get_db():
"""FastAPI dependency:每個請求一條連線。"""
conn = connect()
try:
yield conn
finally:
conn.close()
@contextmanager
def transaction(conn: sqlite3.Connection):
"""BEGIN IMMEDIATE:一開始就拿寫入鎖,避免兩個請求同時給號。"""
conn.execute("BEGIN IMMEDIATE")
try:
yield conn
except BaseException:
conn.execute("ROLLBACK")
raise
else:
conn.execute("COMMIT")
+52
View File
@@ -0,0 +1,52 @@
"""共用的 dependency:錯誤格式、session 驗證、取得使用者 IP。"""
import hashlib
import sqlite3
from fastapi import Depends, HTTPException, Request
from . import clock, config
from .db import get_db
def fail(status: int, code: str):
"""錯誤一律回 {"detail": "<code>"},前端用 err.<code> 翻譯。"""
raise HTTPException(status_code=status, detail=code)
def sha256(s: str) -> str:
return hashlib.sha256(s.encode()).hexdigest()
def client_ip(request: Request) -> str:
# port 只綁 127.0.0.1,外部流量都經過 cloudflared,所以可以信任 CF-Connecting-IP
return request.headers.get("cf-connecting-ip") or (request.client.host if request.client else "?")
def session_token(request: Request) -> str | None:
auth = request.headers.get("authorization", "")
if auth.lower().startswith("bearer "):
return auth[7:].strip() or None
return request.cookies.get(config.COOKIE_NAME)
def optional_user(request: Request, conn: sqlite3.Connection = Depends(get_db)) -> sqlite3.Row | None:
token = session_token(request)
if not token:
return None
return conn.execute(
"SELECT u.* FROM sessions s JOIN users u ON u.uid = s.uid "
"WHERE s.token_hash = ? AND s.expires_at > ?",
(sha256(token), clock.ts()),
).fetchone()
def current_user(user: sqlite3.Row | None = Depends(optional_user)) -> sqlite3.Row:
if user is None:
fail(401, "unauthorized")
return user
def admin_user(user: sqlite3.Row = Depends(current_user)) -> sqlite3.Row:
if user["uid"] != config.ADMIN_UID:
fail(403, "forbidden")
return user
+25
View File
@@ -0,0 +1,25 @@
"""伺服器端文字(信件、小卡、頭銜、分享文字)。前端介面文字在 web/i18n。"""
import json
from functools import lru_cache
from pathlib import Path
from .. import config
_DIR = Path(__file__).resolve().parent
@lru_cache(maxsize=None)
def _load(lang: str) -> dict:
with open(_DIR / f"{lang}.json", encoding="utf-8") as f:
return json.load(f)
def norm_lang(lang) -> str:
return lang if lang in config.LANGS else config.DEFAULT_LANG
def t(lang: str, key: str, **kw) -> str:
text = _load(norm_lang(lang)).get(key)
if text is None:
text = _load("en").get(key, key)
return text.format(**kw) if kw else text
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "Your 吱鼯計畫 code: {code}",
"mail.body": "Your 吱鼯計畫 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 squeaking on 吱鼯計畫. Have you squeaked today?",
"share.title": "{name}'s squeak card",
"share.open": "Let me squeak too",
"card.clicks": "squeaks"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 認証コード:{code}",
"mail.body": "吱鼯計畫 の認証コードは:\n\n{code}\n\n有効期限は 5 分です。お心当たりのない場合は、このメールを破棄してください。\n\n{url}",
"card.day": "ログイン {n} 日目",
"card.streak": "連続 {n} 日",
"card.no_meme": "画像準備中",
"share.text": "吱鼯計畫でチューチュー {n} 日目!今日はもうチューチューした?",
"share.title": "{name} のチューチューカード",
"share.open": "自分もチューチューする",
"card.clicks": "チューチュー回数"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 인증 코드: {code}",
"mail.body": "吱鼯計畫 인증 코드는:\n\n{code}\n\n5분 동안 유효합니다. 본인이 요청하지 않았다면 이 메일을 무시해 주세요.\n\n{url}",
"card.day": "출석 {n}일째",
"card.streak": "연속 {n}일",
"card.no_meme": "이미지 준비 중",
"share.text": "吱鼯計畫에서 찍찍 {n}일째! 오늘 찍찍 했어?",
"share.title": "{name}의 찍찍 카드",
"share.open": "나도 찍찍하기",
"card.clicks": "찍찍 횟수"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 验证码:{code}",
"mail.body": "你的 吱鼯計畫 验证码是:\n\n{code}\n\n5 分钟内有效。如果这不是你本人的操作,请直接忽略这封邮件。\n\n{url}",
"card.day": "签到第 {n} 天",
"card.streak": "连续 {n} 天",
"card.no_meme": "梗图准备中",
"share.text": "我在吱鼯計畫吱吱了 {n} 天,你今天吱吱了吗?",
"share.title": "{name} 的吱吱小卡",
"share.open": "我也要吱吱",
"card.clicks": "吱吱次数"
}
+11
View File
@@ -0,0 +1,11 @@
{
"mail.subject": "吱鼯計畫 驗證碼:{code}",
"mail.body": "你的 吱鼯計畫 驗證碼是:\n\n{code}\n\n5 分鐘內有效。如果這不是你本人的操作,請直接忽略這封信。\n\n{url}",
"card.day": "簽到第 {n} 天",
"card.streak": "連續 {n} 天",
"card.no_meme": "梗圖準備中",
"share.text": "我在吱鼯計畫吱吱了 {n} 天,你今天吱吱了嗎?",
"share.title": "{name} 的吱吱小卡",
"share.open": "我也要吱吱",
"card.clicks": "吱吱次數"
}
+36
View File
@@ -0,0 +1,36 @@
"""寄送驗證碼。改寫自 RhyculatorServer/Verify_email/main.py 的 send_email(),改成通用 SMTP。
寄信是容器主動連出去(smtp.gmail.com:465 等),不經過 cloudflared tunnel,不用額外開 port。
"""
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid
from . import config
from .i18n import t
def send_code(to_email: str, code: str, lang: str) -> None:
# 本地開發沒有設定 SMTP 帳密時,直接把驗證碼印在 log
if not config.SMTP_USER or not config.SMTP_PASSWORD:
print(f"[DEV] verify code for {to_email}: {code}", flush=True)
return
msg = EmailMessage()
msg["Subject"] = t(lang, "mail.subject", code=code)
# Gmail:MAIL_FROM 要先在「以這個地址寄送郵件」加入別名,否則 Gmail 會改回帳號本身
msg["From"] = formataddr(("吱鼯計畫", config.MAIL_FROM))
msg["To"] = to_email
msg["Message-ID"] = make_msgid(domain=config.MAIL_FROM.rpartition("@")[2] or None)
msg.set_content(t(lang, "mail.body", code=code, url=config.PUBLIC_URL))
ctx = ssl.create_default_context()
if config.SMTP_PORT == 465:
smtp = smtplib.SMTP_SSL(config.SMTP_HOST, config.SMTP_PORT, timeout=15, context=ctx)
else:
smtp = smtplib.SMTP(config.SMTP_HOST, config.SMTP_PORT, timeout=15)
smtp.starttls(context=ctx)
with smtp:
smtp.login(config.SMTP_USER, config.SMTP_PASSWORD)
smtp.send_message(msg)
+92
View File
@@ -0,0 +1,92 @@
import hashlib
import mimetypes
from contextlib import asynccontextmanager
from functools import lru_cache
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from . import auth, card, checkin, config, db, share, submissions, users
# python:3.12-slim 沒有 /etc/mime.types,這些副檔名會被當成 text/plain;加上 nosniff 後瀏覽器可能拒絕播放
for _type, _ext in (("image/webp", ".webp"), ("video/mp4", ".mp4"), ("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:; media-src 'self'; 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="吱鼯計畫", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
@app.middleware("http")
async def guard(request: Request, call_next):
# 防 CSRF:會改資料的 /api 請求要帶 X-ZHIWU: 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-zhiwu") != "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")
+73
View File
@@ -0,0 +1,73 @@
"""分享頁 /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: #1a0f06; color: #fff6ea;
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: #ff8a1f; color: #2a1400; 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)
# ?c= 讓吱吱次數變了之後,預覽圖的網址也跟著變(小卡有 10 分鐘快取)
image_path = f"/card/{fmt_uid(uid)}/{day}.png?c={user['clicks']}"
return PAGE.format(
lang=lang,
site="吱鼯計畫 (Beta)" if config.BETA else "吱鼯計畫",
title=escape(t(lang, "share.title", name=user["display_name"])),
desc=escape(t(lang, "share.text", n=total)),
image=escape(config.PUBLIC_URL + image_path),
image_path=image_path,
url=escape(f"{config.PUBLIC_URL}/c/{fmt_uid(uid)}/{day}"),
open=escape(t(lang, "share.open")),
)
+216
View File
@@ -0,0 +1,216 @@
"""使用者投稿迷因圖,管理員審核。
流程:使用者上傳 → 重新編碼後存在 DATA_DIR/submissions/<id>.<ext>(pending)
→ 管理員同意:依 image/ 的命名規則存成 MEME_DIR/zhiwu_<下一號>.<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 badge, fmt_uid
router = APIRouter()
MEME_NAME = re.compile(r"^zhiwu_(\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:
"""迷因資料夾裡 zhiwu_<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, u.title, u.title_color 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"]), **badge(row),
"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"zhiwu_{n}.*")):
n += 1
name = f"zhiwu_{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)}
+58
View File
@@ -0,0 +1,58 @@
"""UID 的底色與稱號。
- 管理員(UID 0)預設黃底
- 管理員可以幫任何 UID 指定一個顏色和一個稱號(users.title / users.title_color),會蓋過預設
都只是顯示用,不帶任何權限。顯示的地方:側欄、個人頁、審核頁、小卡。
"""
import re
import sqlite3
from . import config
# 預設的特殊序號:底色、文字色(網頁的 web/style.css .uid.tier-* 用同樣的顏色)
TIER_COLORS = {
"admin": ((255, 209, 102), (42, 20, 0)), # 黃 #FFD166
}
DEFAULT_TITLE_COLOR = "#ff8a1f" # 只給稱號沒給顏色時用主色
_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
_INK, _WHITE = (42, 20, 0), (255, 255, 255)
def fmt_uid(uid: int) -> str:
return f"{uid:08d}"
def uid_tier(uid: int) -> str | None:
return "admin" if uid == config.ADMIN_UID else None
def valid_color(color: str) -> bool:
return bool(_COLOR_RE.match(color))
def hex_rgb(color: str) -> tuple[int, int, int]:
return tuple(int(color[i:i + 2], 16) for i in (1, 3, 5))
def text_on(rgb: tuple[int, int, int]) -> tuple[int, int, int]:
"""底色上要用深色字還是白字(依亮度)。前端 web/app.js 的 textOn() 用同一條公式。"""
r, g, b = rgb
return _INK if (r * 299 + g * 587 + b * 114) / 1000 >= 150 else _WHITE
def badge(user: sqlite3.Row) -> dict:
"""API 回傳用:uid_tier(預設樣式)、title(稱號)、title_color(指定的顏色,#rrggbb 或 None)。"""
return {
"uid_tier": uid_tier(user["uid"]),
"title": user["title"],
"title_color": user["title_color"] or None,
}
def badge_colors(user: sqlite3.Row) -> tuple[tuple, tuple] | None:
"""小卡用:(底色, 文字色);沒有特殊樣式回 None。指定的顏色優先於預設。"""
if user["title_color"]:
bg = hex_rgb(user["title_color"])
return bg, text_on(bg)
tier = uid_tier(user["uid"])
return TIER_COLORS[tier] if tier else None
+40
View File
@@ -0,0 +1,40 @@
"""RFC 6238 TOTP(SHA1、6 碼、30 秒),和 Aegis / Google Authenticator 預設相同。只用標準函式庫。"""
import base64
import hashlib
import hmac
import struct
from urllib.parse import quote
PERIOD = 30
DIGITS = 6
def decode_secret(secret: str) -> bytes:
s = secret.replace(" ", "").upper()
return base64.b32decode(s + "=" * (-len(s) % 8))
def code_at(key: bytes, step: int) -> str:
digest = hmac.new(key, struct.pack(">Q", step), hashlib.sha1).digest()
offset = digest[-1] & 0x0F
value = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF
return f"{value % 10**DIGITS:0{DIGITS}d}"
def verify(secret: str, code: str, unix_time: int, window: int = 1) -> int | None:
"""比對前後各 window 個時間窗(容忍手機時鐘誤差),成功回傳符合的時間步。"""
if len(code) != DIGITS or not code.isdigit():
return None
key = decode_secret(secret)
current = unix_time // PERIOD
matched = None
for step in range(current - window, current + window + 1):
# 全部比完,不提早結束,避免從回應時間猜出哪個時間窗符合
if hmac.compare_digest(code_at(key, step), code) and matched is None:
matched = step
return matched
def uri(secret: str, account: str, issuer: str = "吱鼯計畫") -> str:
label = quote(f"{issuer}:{account}")
return f"otpauth://totp/{label}?secret={secret.replace(' ', '').upper()}&issuer={quote(issuer)}"
+229
View File
@@ -0,0 +1,229 @@
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 admin_user, current_user, fail
from .i18n import norm_lang
from .titles import DEFAULT_TITLE_COLOR, badge, fmt_uid, valid_color
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"吱鼯_{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"],
**badge(user),
"bio_md": user["bio_md"],
"bio_html": render_md(user["bio_md"]),
"avatar_url": avatar_url(user),
"total_days": total,
"streak": streak,
"clicks": user["clicks"],
"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)
# ---------- 管理員:指定 UID 的顏色與稱號 ----------
class TitleIn(BaseModel):
title: str = ""
color: str = ""
@router.put("/api/admin/users/{uid}/title")
def set_title(uid: int, body: TitleIn, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
"""稱號和顏色都留空 = 清除。只給稱號沒給顏色時用主色;也可以只給顏色不給稱號。"""
title = "".join(ch for ch in body.title if unicodedata.category(ch) != "Cc").strip()
color = body.color.strip().lower()
if len(title) > config.TITLE_MAX:
fail(400, "title_too_long")
if color and not valid_color(color):
fail(400, "invalid_color")
if title and not color:
color = DEFAULT_TITLE_COLOR
cur = conn.execute("UPDATE users SET title = ?, title_color = ? WHERE uid = ?", (title, color, uid))
if cur.rowcount == 0:
fail(404, "user_not_found")
card.invalidate(uid)
print(f"[ADMIN] title uid={fmt_uid(uid)} title={title!r} color={color or '-'}", flush=True)
user = conn.execute("SELECT * FROM users WHERE uid = ?", (uid,)).fetchone()
return profile(conn, user, 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)}
+3
View File
@@ -0,0 +1,3 @@
-r requirements.txt
pytest==8.*
httpx
+6
View File
@@ -0,0 +1,6 @@
fastapi==0.115.*
uvicorn[standard]==0.32.*
pillow==11.*
python-multipart==0.0.*
markdown-it-py==3.*
tzdata
View File
Whitespace-only changes.
+65
View File
@@ -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-ZHIWU": "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)
+129
View File
@@ -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 user["title"] == ""
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/%E5%90%B1%E9%BC%AF%E8%A8%88%E7%95%AB%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])
+241
View File
@@ -0,0 +1,241 @@
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"] == "吱鼯_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-ZHIWU
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-ZHIWU": ""})
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_only_admin_has_uid_tier(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"] is None
assert client.get("/api/users/0").json()["uid_tier"] == "admin"
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 _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"}
+59
View File
@@ -0,0 +1,59 @@
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"), (1, None), (114514, 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="吱鼯計畫 (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("zhiwu.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
+59
View File
@@ -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"] == "吱鼯計畫 <[email protected]>"
assert msg["To"] == "[email protected]"
assert "123456" in msg["Subject"] and "認証コード" in msg["Subject"]
assert msg["Message-ID"].endswith("@zhiwu-project.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
+178
View File
@@ -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 ("zhiwu_0.png", "zhiwu_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"] == "zhiwu_8.jpg" and r.json()["pending"] == 1
assert (config.MEME_DIR / "zhiwu_8.jpg").is_file()
assert not (config.DATA_DIR / "submissions" / f"{first}.jpg").exists()
assert "zhiwu_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"] == "zhiwu_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() == ["zhiwu_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] == "zhiwu_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/zhizhi-poster.webp", "image/webp"), ("/assets/media/zhizhi.mp4", "video/mp4")):
r = client.get(path)
assert r.status_code == 200 and r.headers["content-type"].startswith(ctype)
+116
View File
@@ -0,0 +1,116 @@
"""管理員指定 UID 的顏色與稱號。"""
import sqlite3
from app import admin, config, db
from app.titles import text_on
from .conftest import ADMIN_LOGIN, admin_code, login
def bearer(tok):
return {"Authorization": f"Bearer {tok}"}
def admin_token(client, fake_clock):
client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN, "lang": "zh-TW"})
r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock), "lang": "zh-TW"})
assert r.status_code == 200, r.text
client.cookies.clear()
return r.json()["token"]
def test_default_has_no_title(client, sent):
u = login(client, sent)["user"]
assert u["title"] == "" and u["title_color"] is None and u["uid_tier"] is None
assert client.get("/api/users/0").json()["uid_tier"] == "admin" # 管理員預設樣式還在
def test_admin_sets_and_clears_title(client, sent, fake_clock):
login(client, sent)
card_url = client.post("/api/checkin").json()["card_url"]
plain = client.get(card_url).content
adm = admin_token(client, fake_clock)
r = client.put("/api/admin/users/1/title", json={"title": " 首席鼠黑 ", "color": "#3366FF"}, headers=bearer(adm))
assert r.status_code == 200, r.text
assert r.json()["title"] == "首席鼠黑" and r.json()["title_color"] == "#3366ff"
# 公開資料看得到,小卡也重畫了
u = client.get("/api/users/1").json()
assert u["title"] == "首席鼠黑" and u["title_color"] == "#3366ff"
titled = client.get(card_url).content
assert titled != plain
# 清除
r = client.put("/api/admin/users/1/title", json={"title": "", "color": ""}, headers=bearer(adm))
assert r.json()["title"] == "" and r.json()["title_color"] is None
assert client.get(card_url).content == plain
def test_title_or_color_alone(client, sent, fake_clock):
login(client, sent)
adm = admin_token(client, fake_clock)
# 只給稱號:顏色用主色
r = client.put("/api/admin/users/1/title", json={"title": "吱吱"}, headers=bearer(adm)).json()
assert r["title"] == "吱吱" and r["title_color"] == "#ff8a1f"
# 只給顏色:沒有稱號
r = client.put("/api/admin/users/1/title", json={"color": "#000000"}, headers=bearer(adm)).json()
assert r["title"] == "" and r["title_color"] == "#000000"
# 管理員自己也可以改
r = client.put("/api/admin/users/0/title", json={"title": "鼠王", "color": "#ff0000"}, headers=bearer(adm)).json()
assert r["title"] == "鼠王" and r["uid_tier"] == "admin"
def test_title_validation_and_permission(client, sent, fake_clock):
tok = login(client, sent)["token"]
client.cookies.clear()
# 一般使用者不能設(自己的也不行),沒登入也不行
assert client.put("/api/admin/users/1/title", json={"title": "x"}, headers=bearer(tok)).status_code == 403
assert client.put("/api/admin/users/1/title", json={"title": "x"}).status_code == 401
adm = admin_token(client, fake_clock)
for body, code in (({"title": "字" * (config.TITLE_MAX + 1)}, "title_too_long"),
({"color": "red"}, "invalid_color"), ({"color": "#12345"}, "invalid_color"),
({"color": "#12345g"}, "invalid_color")):
r = client.put("/api/admin/users/1/title", json=body, headers=bearer(adm))
assert r.status_code == 400 and r.json()["detail"] == code, body
r = client.put("/api/admin/users/999/title", json={"title": "x"}, headers=bearer(adm))
assert r.status_code == 404 and r.json()["detail"] == "user_not_found"
assert client.get("/api/users/1").json()["title"] == ""
def test_review_page_shows_uploader_title(client, sent, fake_clock):
from .test_submissions import upload
tok = login(client, sent)["token"]
client.cookies.clear()
upload(client, tok)
adm = admin_token(client, fake_clock)
client.put("/api/admin/users/1/title", json={"title": "投稿王", "color": "#00aa55"}, headers=bearer(adm))
up = client.get("/api/admin/submissions", headers=bearer(adm)).json()["item"]["uploader"]
assert up["title"] == "投稿王" and up["title_color"] == "#00aa55"
def test_set_title_cli(client, sent, capsys):
login(client, sent)
admin.main(["set-title", "1", "--title", "測試", "--color", "#ABCDEF"])
assert client.get("/api/users/1").json()["title_color"] == "#abcdef"
admin.main(["set-title", "1", "--clear"])
u = client.get("/api/users/1").json()
assert u["title"] == "" and u["title_color"] is None
def test_text_colour_follows_brightness():
assert text_on((255, 209, 102)) == (42, 20, 0) # 亮底用深色字
assert text_on((0, 0, 0)) == (255, 255, 255) # 暗底用白字
assert text_on((51, 102, 255)) == (255, 255, 255)
def test_old_database_gets_new_columns(client, sent):
"""已經在跑的資料庫(沒有 title 欄位)重啟後自動補欄位,資料不動。"""
login(client, sent)
conn = sqlite3.connect(db.db_path(), isolation_level=None)
conn.execute("ALTER TABLE users DROP COLUMN title")
conn.execute("ALTER TABLE users DROP COLUMN title_color")
conn.close()
db.init()
u = client.get("/api/me").json()
assert u["title"] == "" and u["title_color"] is None and u["uid_str"] == "00000001"
+129
View File
@@ -0,0 +1,129 @@
"""吱吱(點擊)次數:和簽到天數分開記錄,簽到那一下也算一次。"""
import pytest
from app import checkin, config
from .conftest import login
@pytest.fixture
def frozen(monkeypatch):
"""固定限流用的時鐘,測試自己決定時間前進多少。"""
now = [1000.0]
monkeypatch.setattr(checkin, "_now", lambda: now[0])
checkin._buckets.clear()
return now
def test_checkin_counts_one_click_per_day(client, sent, frozen, fake_clock):
login(client, sent)
assert client.get("/api/checkin/today").json()["clicks"] == 0
r = client.post("/api/checkin").json()
assert r["already"] is False and r["total_days"] == 1 and r["clicks"] == 1
# 同一天再簽到:不會再加
r = client.post("/api/checkin").json()
assert r["already"] is True and r["total_days"] == 1 and r["clicks"] == 1
# 隔天簽到再加一次
fake_clock.set("2026-11-22T12:00:00+08:00")
r = client.post("/api/checkin").json()
assert r["total_days"] == 2 and r["clicks"] == 2
def test_zhi_adds_clicks_but_not_days(client, sent, frozen):
login(client, sent)
client.post("/api/checkin")
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 2, "added": 1}
frozen[0] += 1
assert client.post("/api/zhi", json={}).json()["clicks"] == 3 # 預設一下
today = client.get("/api/checkin/today").json()
assert today["clicks"] == 3 and today["total_days"] == 1 and today["streak"] == 1
me = client.get("/api/me").json()
assert me["clicks"] == 3 and me["total_days"] == 1
assert client.get("/api/users/1").json()["clicks"] == 3
def test_zhi_works_before_checkin(client, sent, frozen):
"""次數和簽到互相獨立:沒簽到也能加(API 不擋,前端只在簽到後才開放)。"""
login(client, sent)
assert client.post("/api/zhi", json={"n": 1}).json()["clicks"] == 1
today = client.get("/api/checkin/today").json()
assert today["checked_in"] is False and today["total_days"] == 0
@pytest.mark.parametrize("n", [0, -1, config.ZHI_BATCH_MAX + 1])
def test_zhi_rejects_bad_batch(client, sent, frozen, n):
login(client, sent)
r = client.post("/api/zhi", json={"n": n})
assert r.status_code == 400 and r.json()["detail"] == "bad_request"
assert client.get("/api/me").json()["clicks"] == 0
def test_zhi_once_per_second(client, sent, frozen):
"""一個帳號一秒只能吱一次:同一秒內多的、一次送很多下的,都只算一下。"""
login(client, sent)
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 1}
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 0}
frozen[0] += 0.9
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 0}
frozen[0] += 0.1
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 2, "added": 1}
# 等再久額度也只存 1 下;一次送 200 下也只加 1
frozen[0] += 3600
assert client.post("/api/zhi", json={"n": 200}).json() == {"clicks": 3, "added": 1}
assert client.post("/api/zhi", json={"n": 200}).json() == {"clicks": 3, "added": 0}
def test_zhi_limit_is_per_account(client, sent, frozen):
login(client, sent, "[email protected]")
assert client.post("/api/zhi", json={"n": 1}).json()["added"] == 1
client.cookies.clear()
login(client, sent, "[email protected]")
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 1}
def test_zhi_requires_login_and_csrf(client, sent, frozen):
assert client.post("/api/zhi", json={"n": 1}).status_code == 401
login(client, sent)
assert client.post("/api/zhi", json={"n": 1}, headers={"X-ZHIWU": ""}).status_code == 403
def test_card_redrawn_when_clicks_change(client, sent, frozen):
login(client, sent)
r = client.post("/api/checkin").json()
cards = config.DATA_DIR / "cards" / "1"
first = client.get(r["card_url"])
assert first.status_code == 200
assert [p.name for p in cards.iterdir()] == [f"{r['day']}.v1.c1.png"]
client.post("/api/zhi", json={"n": 1})
second = client.get(r["card_url"] + "?c=2")
assert second.status_code == 200 and second.content != first.content
# 舊次數的快取會被清掉,只留最新的一張
assert [p.name for p in cards.iterdir()] == [f"{r['day']}.v1.c2.png"]
# 次數沒變就直接用快取
assert client.get(r["card_url"] + "?c=2").content == second.content
def test_card_uses_default_image_when_gallery_empty(client, sent, frozen):
for p in config.MEME_DIR.iterdir():
p.unlink()
login(client, sent)
r = client.post("/api/checkin").json()
assert client.get(r["card_url"]).status_code == 200
def test_reset_progress_clears_clicks(client, sent, frozen):
from app import admin
login(client, sent)
client.post("/api/checkin")
client.post("/api/zhi", json={"n": 1})
admin.main(["reset-progress", "--yes"])
today = client.get("/api/checkin/today").json()
assert today["clicks"] == 0 and today["total_days"] == 0
def test_video_served_with_range(client):
r = client.get("/assets/media/zhizhi.mp4", headers={"Range": "bytes=0-99"})
assert r.status_code == 206 and r.headers["content-type"] == "video/mp4" and len(r.content) == 100
assert "media-src 'self'" in r.headers["content-security-policy"]
+32
View File
@@ -0,0 +1,32 @@
"""從 icon/ 裡的圖片產生網頁用的圖:
server/.venv/Scripts/python tools/make_icons.py # 用 icon/ 裡的第一張圖當圖標
server/.venv/Scripts/python tools/make_icons.py icon/x.png
吱吱影片另外用 tools/make_media.py 轉檔。
"""
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")
# 圖庫(image/)是空的時候,小卡上方用這張
assets = ROOT / "server" / "app" / "assets"
assets.mkdir(exist_ok=True)
im.save(assets / "default-meme.jpg", "JPEG", quality=90)
print(f"{src.name} -> server/app/assets/default-meme.jpg")
+45
View File
@@ -0,0 +1,45 @@
"""把 media-src/zhizhi.mp4(吱吱影片原檔)轉成網頁用的檔案:
server/.venv/Scripts/python -m pip install imageio-ffmpeg # 自帶 ffmpeg,不用另外安裝
server/.venv/Scripts/python tools/make_media.py
輸出:
web/media/zhizhi.mp4 H.264 + AAC、moov 放在檔頭(faststart),手機瀏覽器可以邊載邊播
web/media/zhizhi-poster.webp 第一幀;還沒點擊時顯示的畫面
"""
import subprocess
import sys
from pathlib import Path
import imageio_ffmpeg
from PIL import Image
ROOT = Path(__file__).resolve().parent.parent
SRC = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "media-src" / "zhizhi.mp4"
MEDIA = ROOT / "web" / "media"
FFMPEG = imageio_ffmpeg.get_ffmpeg_exe()
def ffmpeg(*args: str) -> None:
subprocess.run([FFMPEG, "-hide_banner", "-loglevel", "error", "-y", *args], check=True)
MEDIA.mkdir(parents=True, exist_ok=True)
video = MEDIA / "zhizhi.mp4"
ffmpeg("-i", str(SRC),
"-c:v", "libx264", "-profile:v", "main", "-pix_fmt", "yuv420p", "-crf", "23", "-preset", "slow",
"-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
"-c:a", "aac", "-b:a", "128k", "-ac", "2",
"-movflags", "+faststart", str(video))
frame = MEDIA / "_first.png"
ffmpeg("-i", str(SRC), "-frames:v", "1", str(frame))
with Image.open(frame) as im:
im = im.convert("RGB")
im.save(MEDIA / "zhizhi-poster.webp", "WEBP", quality=88, method=6)
size = im.size
frame.unlink()
print(f"{SRC.name} -> web/media/zhizhi.mp4 ({video.stat().st_size // 1024} KB), "
f"zhizhi-poster.webp {size[0]}x{size[1]}")
+931
View File
@@ -0,0 +1,931 @@
// 吱鼯計畫前端:純 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 HOME_TITLE = document.title; // 「吱鼯計畫 — 你今天吱吱了嗎」,伺服器會依 BETA 開關加上 (Beta)
const SITE_TITLE = HOME_TITLE.split(" — ")[0]; // 其他頁面的標題只接站名
// 伺服器填入的檔案版本,語言檔網址也帶上,改版後不會拿到快取的舊檔
const ASSET_V = document.querySelector('meta[name="asset-version"]')?.content || "";
const VIDEO_MAX_MS = 4000; // 吱吱影片約 1.6 秒;ended 沒觸發(例如播放失敗)時的保險時間
const ZHI_GAP_MS = 1100; // 伺服器一個帳號一秒只收一下;補送沒送成功的次數時,每下隔這麼久
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,
zhiMode: null, // null = 沒開 / "checkin" = 簽到那一下 / "more" = 繼續吱吱
zhiBusy: false, // 影片播放中:不接受點擊(簽到和繼續吱吱都一樣)
zhiSkipped: false, // 今天還沒簽到,但使用者按了「等等再吱」
zhiPending: 0, // 還沒送到伺服器的點擊次數
zhiTimer: null,
zhiAuto: false, // 全自動吱吱開著:播完自動接下一次
zhiAutoTimer: null,
zhiLastAt: 0, // 上一次繼續吱吱的時間
zhiPlay: 0, // 第幾次播放;離開再進來時,舊的那次播完不能動到新的
zhiFlush: null, // 正在送次數的 Promise(離開時等它送完)
};
// ---------- 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-ZHIWU": "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);
}
// ---------- 側邊欄:登入 / 個人資訊 ----------
// 底色上要用深色字還是白字(和 server/app/titles.py 的 text_on() 同一條公式)
function textOn(hex) {
const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
return (r * 299 + g * 587 + b * 114) / 1000 >= 150 ? "#2a1400" : "#ffffff";
}
// UID 與稱號。管理員指定的顏色(title_color)優先,其次是預設的特殊序號(uid_tier,目前只有管理員)
function showUid(el, user) {
const uid = document.createElement("span");
uid.textContent = `UID ${user.uid_str}`;
uid.className = "uid";
const parts = [uid];
let title = null;
if (user.title) {
title = document.createElement("span");
title.textContent = user.title;
title.className = "title-badge";
parts.push(title);
}
if (user.title_color) {
for (const p of parts) {
p.classList.add("badge");
p.style.background = user.title_color;
p.style.color = textOn(user.title_color);
}
} else if (user.uid_tier) {
for (const p of parts) p.classList.add("badge", `tier-${user.uid_tier}`);
}
el.className = "uid-wrap";
el.replaceChildren(...parts);
}
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;
state.zhiSkipped = false;
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 }),
t("checkin.clicks", { n: fmtNum(d.clicks ?? 0) }),
].join(" · ");
}
function fmtNum(n) { return Number(n).toLocaleString("en-US"); }
// 小卡上有吱吱次數,網址帶 c=<次數>,次數變了才會重新下載
function cardSrc(d) { return `${d.card_url}?v=${state.cardBust}&c=${d.clicks}`; }
function renderToday(justChecked) {
const d = state.today;
if (!d.checked_in) {
showCheckinPart("checkin-ready");
$("ready-stats").textContent = d.total_days || d.clicks ? statsText(d) : "";
// 還沒簽到:直接蓋上全螢幕的吱吱畫面(除非使用者剛剛選了等等再吱)
if (!state.zhiSkipped && state.zhiMode !== "checkin") openStage("checkin");
} else {
if (state.zhiMode === "checkin") closeStage(); // 例如在另一個分頁簽到了
showCheckinPart("checkin-done");
$("checkin-msg").textContent = justChecked ? t("checkin.success") : t("checkin.done_today");
const src = cardSrc(d);
if ($("card-img").getAttribute("src") !== src) $("card-img").src = src;
$("download-btn").href = src;
$("download-btn").setAttribute("download", `zhiwu-${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);
if (state.zhiMode === "more") return; // 正在繼續吱吱就不打斷,回到小卡時會重新整理
state.zhiSkipped = false;
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;
closeStage();
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], `zhiwu-${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);
}
}
// 從點擊的位置噴出粒子(橘色系,夾幾個「吱」字)
function burst(x, y, count = 28) {
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const spread = Math.min(window.innerWidth, window.innerHeight) * 0.28;
const colors = ["#ff8a1f", "#ffd166", "#ffb347", "#fff6ea", "#ff6a00"];
for (let i = 0; i < count; i++) {
const p = document.createElement("span");
const word = i % 5 === 0;
p.className = word ? "particle digit" : "particle";
if (word) p.textContent = "吱";
const angle = (i / count) * Math.PI * 2 + Math.random() * 0.5;
const dist = spread * 0.5 + Math.random() * spread;
const size = word ? 22 + Math.random() * 18 : 6 + Math.random() * 9;
p.style.cssText = [
`--x:${x}px`, `--y:${y}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 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;
});
}
// ---------- 全螢幕吱吱 ----------
// 還沒點擊時停在影片第一幀,中間寫「點擊吱吱」。
// 簽到模式(checkin):點一下 → 有聲播到完 → 送出簽到 → 亮出小卡
// 繼續吱吱(more):點一下播一次、吱吱次數 +1,播完才能再點(播放中點了沒反應),不會跳去小卡
// 中下方的「全自動吱吱」打開後,播完會自動接著吱下一次,直到關掉或回到小卡
// 影片回到第一幀並暫停,重新顯示「點擊吱吱」
function resetVideo() {
const video = $("zhi-video");
video.pause();
try { video.currentTime = 0; } catch { /* 還沒載入 metadata */ }
$("zhi-stage").classList.remove("playing");
}
// 從頭播放(一定要在點擊事件裡呼叫,瀏覽器才允許有聲播放)
function playVideo() {
const video = $("zhi-video");
$("zhi-stage").classList.add("playing");
try { video.currentTime = 0; } catch { /* 還沒載入 metadata */ }
video.muted = false;
const p = video.play();
if (p) p.catch(() => { /* 真的不能播就只剩粒子 */ });
}
// 等影片播完(或保險時間到)
function waitVideoEnd() {
const video = $("zhi-video");
return new Promise((resolve) => {
const done = () => { clearTimeout(timer); video.removeEventListener("ended", done); resolve(); };
const timer = setTimeout(done, VIDEO_MAX_MS);
video.addEventListener("ended", done);
});
}
function showZhiCount(bump) {
const el = $("zhi-count");
el.textContent = t("zhi.count", { n: fmtNum(state.today?.clicks ?? 0) });
if (bump) { el.classList.remove("bump"); void el.offsetWidth; el.classList.add("bump"); }
}
function openStage(mode) {
state.zhiMode = mode;
state.zhiBusy = false;
state.zhiPlay++;
resetVideo();
$("zhi-exit").textContent = t(mode === "more" ? "zhi.back" : "zhi.later");
$("zhi-exit").disabled = false;
$("zhi-count").hidden = mode !== "more";
$("zhi-auto").hidden = mode !== "more";
setZhiAuto(false);
if (mode === "more") showZhiCount(false);
$("zhi-stage").hidden = false;
document.body.classList.add("zhi-on");
closeMenu();
}
function closeStage() {
if (!state.zhiMode) return;
setZhiAuto(false);
state.zhiMode = null;
state.zhiBusy = false;
resetVideo();
$("zhi-stage").hidden = true;
document.body.classList.remove("zhi-on");
}
// 簽到:播影片、噴粒子,同時送出簽到;影片播完而且小卡下載好才亮出小卡
async function zhiCheckin(x, y) {
if (state.zhiBusy) return;
state.zhiBusy = true;
$("zhi-exit").disabled = true;
playVideo();
burst(x, y);
const ended = waitVideoEnd();
try {
const today = await api("POST", "/api/checkin");
await Promise.all([ended, today.card_url ? preloadImage(cardSrc(today)) : null]);
state.today = today;
state.zhiSkipped = false;
closeStage();
renderToday(!today.already);
loadMe();
} catch (e) {
if (state.zhiMode === "checkin") {
state.zhiBusy = false;
$("zhi-exit").disabled = false;
resetVideo();
}
toast(errText(e));
}
}
// 繼續吱吱:播放中再點沒有反應;播完回到第一幀才能點下一次
function zhiMore(x, y) {
if (state.zhiBusy) return;
// 一個帳號一秒只能吱一次(伺服器也會擋)。影片比 1 秒長,只有離開再馬上進來時會遇到
if (Date.now() - state.zhiLastAt < ZHI_GAP_MS) return;
state.zhiLastAt = Date.now();
state.zhiBusy = true;
const play = ++state.zhiPlay;
playVideo();
burst(x, y, 12);
state.zhiPending++;
state.today.clicks++;
showZhiCount(true);
flushZhi();
waitVideoEnd().then(() => {
if (state.zhiMode !== "more" || state.zhiPlay !== play) return; // 播到一半按了回到小卡(或離開後又進來)
resetVideo();
state.zhiBusy = false;
zhiAutoTick(); // 全自動開著就接著吱下一次
});
}
// ---------- 全自動吱吱 ----------
function setZhiAuto(on) {
state.zhiAuto = on;
clearTimeout(state.zhiAutoTimer);
state.zhiAutoTimer = null;
const btn = $("zhi-auto");
btn.textContent = t(on ? "zhi.auto_on" : "zhi.auto");
btn.classList.toggle("on", on);
btn.setAttribute("aria-pressed", String(on));
if (on) zhiAutoTick();
}
// 可以吱就吱一下(從畫面中央);正在播就等它播完再被叫一次;離上一下不到 1 秒就等滿再吱
function zhiAutoTick() {
if (!state.zhiAuto || state.zhiMode !== "more" || state.zhiBusy) return;
const wait = ZHI_GAP_MS - (Date.now() - state.zhiLastAt);
if (wait > 0) {
clearTimeout(state.zhiAutoTimer);
state.zhiAutoTimer = setTimeout(zhiAutoTick, wait);
return;
}
zhiMore(window.innerWidth / 2, window.innerHeight / 2);
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 把還沒送的次數一下一下送給伺服器(伺服器一個帳號一秒只收一下)
function flushZhi() {
clearTimeout(state.zhiTimer);
state.zhiTimer = null;
if (!state.zhiFlush) state.zhiFlush = sendZhi().finally(() => { state.zhiFlush = null; });
return state.zhiFlush;
}
async function sendZhi() {
while (state.zhiPending > 0) {
try {
const r = await api("POST", "/api/zhi", { n: 1 });
state.zhiPending--;
// 以伺服器的數字為準,再加上還沒送出的
if (state.today) state.today.clicks = r.clicks + state.zhiPending;
} catch (e) {
if (e.status === 401 || e.status === 400) { state.zhiPending = 0; return; } // 登出了:這幾下就不算
state.zhiTimer = setTimeout(flushZhi, ZHI_GAP_MS * 3); // 網路問題:留著等一下再送
return;
}
if (state.zhiPending > 0) await sleep(ZHI_GAP_MS);
}
if (state.zhiMode === "more") showZhiCount(false);
}
// 關掉分頁前把還沒送的那一下送出去(keepalive 讓請求在頁面關閉後繼續完成)
function flushZhiOnLeave() {
if (state.zhiPending <= 0 || state.zhiFlush) return; // 正在送的那個請求會自己完成
state.zhiPending--;
fetch("/api/zhi", {
method: "POST",
headers: { "X-ZHIWU": "1", "Content-Type": "application/json" },
credentials: "same-origin",
keepalive: true,
body: JSON.stringify({ n: 1 }),
}).catch(() => {});
}
async function exitStage() {
const mode = state.zhiMode;
closeStage();
if (mode === "more") {
$("done-stats").textContent = statsText(state.today); // 數字先更新,小卡等伺服器收到次數後再換
await flushZhi();
await refreshToday(); // 小卡換成新的吱吱次數
loadMe();
} else {
state.zhiSkipped = true; // 等等再吱:留在頁面上,可以用側欄
}
}
function bindCheckin() {
const stage = $("zhi-stage");
stage.addEventListener("click", (ev) => {
if (ev.target.closest("#zhi-exit, #zhi-auto")) return;
// 鍵盤觸發的 click 沒有座標,改從畫面中央噴
const x = ev.clientX || window.innerWidth / 2;
const y = ev.clientY || window.innerHeight / 2;
if (state.zhiMode === "checkin") zhiCheckin(x, y);
else if (state.zhiMode === "more") zhiMore(x, y);
});
$("zhi-exit").addEventListener("click", exitStage);
$("zhi-auto").addEventListener("click", () => setZhiAuto(!state.zhiAuto));
$("zhi-open").addEventListener("click", () => { state.zhiSkipped = false; openStage("checkin"); });
$("zhi-more").addEventListener("click", () => openStage("more"));
$("share-btn").addEventListener("click", shareCard);
window.addEventListener("pagehide", flushZhiOnLeave);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") flushZhiOnLeave();
});
}
// ---------- 畫面切換 ----------
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); closeStage(); }
}
// ---------- 投稿迷因圖 ----------
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);
// 管理員:下面多一個設定這個 UID 顏色與稱號的表單
const form = $("title-form");
form.hidden = !state.me?.is_admin;
form.dataset.uid = u.uid;
$("title-text").value = u.title || "";
$("title-color").value = u.title_color || "#ff8a1f";
showError($("title-error"), null);
$("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;
}
}
// ---------- 管理員:指定 UID 的顏色與稱號 ----------
function bindTitle() {
const form = $("title-form");
const save = async (body) => {
try {
const u = await api("PUT", `/api/admin/users/${form.dataset.uid}/title`, body);
state.cardBust = Date.now();
toast(t("title.saved"));
if (state.me && u.uid === state.me.uid) await loadMe();
await showUser(u.uid_str);
} catch (e) {
showError($("title-error"), e);
}
};
form.addEventListener("submit", (ev) => {
ev.preventDefault();
withBusy($("title-save"), () => save({ title: $("title-text").value, color: $("title-color").value }));
});
$("title-clear").addEventListener("click", () => withBusy($("title-clear"), () => save({ title: "", color: "" })));
}
// ---------- 編輯個人資料 ----------
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 = HOME_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();
bindTitle();
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 });
if (state.zhiMode) { // 全螢幕畫面上的按鈕文字不是 data-i18n,換語言時重填
$("zhi-exit").textContent = t(state.zhiMode === "more" ? "zhi.back" : "zhi.later");
$("zhi-auto").textContent = t(state.zhiAuto ? "zhi.auto_on" : "zhi.auto");
showZhiCount(false);
}
await route();
});
await loadMe();
await route();
}
init();
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" fill="#5a3a1c"/><circle cx="32" cy="25" r="12" fill="#d9a066"/><path d="M10 60c2-13 11-20 22-20s20 7 22 20z" fill="#d9a066"/></svg>

After

Width:  |  Height:  |  Size: 221 B

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+99
View File
@@ -0,0 +1,99 @@
{
"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.login_first": "Log in to squeak in once a day and get a squeak card.",
"checkin.ready": "You haven't squeaked today",
"checkin.success": "Squeaked!",
"checkin.done_today": "You've already squeaked 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 a squeak 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",
"site.tagline": "Have you squeaked today?",
"zhi.hint": "Tap to squeak",
"zhi.more": "Keep squeaking",
"zhi.back": "Back to card",
"zhi.later": "Squeak later",
"zhi.count": "{n} squeaks",
"zhi.open": "Go squeak",
"checkin.clicks": "{n} squeaks",
"err.bad_request": "Bad request",
"zhi.auto": "Auto squeak",
"zhi.auto_on": "Auto squeaking (tap to stop)",
"title.heading": "Title & colour (admin)",
"title.name": "Title",
"title.color": "Colour",
"title.hint": "The colour is applied to the UID and the title, shown in the sidebar, profile and card. The title may be left empty.",
"title.save": "Apply",
"title.clear": "Clear",
"title.saved": "Title updated",
"err.title_too_long": "Titles can be up to 16 characters",
"err.invalid_color": "Invalid colour",
"err.user_not_found": "User not found"
}
+99
View File
@@ -0,0 +1,99 @@
{
"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.login_first": "ログインすると毎日 1 回チューチューして、カードがもらえます。",
"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": "見つかりません",
"site.tagline": "今日はもうチューチューした?",
"zhi.hint": "タップしてチューチュー",
"zhi.more": "もっとチューチュー",
"zhi.back": "カードに戻る",
"zhi.later": "あとでチューチュー",
"zhi.count": "チューチュー {n} 回",
"zhi.open": "チューチューしに行く",
"checkin.clicks": "チューチュー {n} 回",
"err.bad_request": "リクエストが正しくありません",
"zhi.auto": "全自動チューチュー",
"zhi.auto_on": "全自動チューチュー中(タップで停止)",
"title.heading": "称号と色(管理者)",
"title.name": "称号",
"title.color": "色",
"title.hint": "色は UID と称号に適用され、サイドバー・プロフィール・カードに表示されます。称号は空欄でも構いません。",
"title.save": "適用",
"title.clear": "クリア",
"title.saved": "称号を更新しました",
"err.title_too_long": "称号は 16 文字までです",
"err.invalid_color": "色の形式が正しくありません",
"err.user_not_found": "ユーザーが見つかりません"
}
+99
View File
@@ -0,0 +1,99 @@
{
"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.login_first": "로그인하면 하루에 한 번 찍찍 출석하고 카드를 받을 수 있습니다.",
"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": "찾을 수 없어요",
"site.tagline": "오늘 찍찍 했어?",
"zhi.hint": "눌러서 찍찍",
"zhi.more": "계속 찍찍",
"zhi.back": "카드로 돌아가기",
"zhi.later": "나중에 찍찍",
"zhi.count": "찍찍 {n}번",
"zhi.open": "찍찍하러 가기",
"checkin.clicks": "찍찍 {n}번",
"err.bad_request": "잘못된 요청입니다",
"zhi.auto": "자동 찍찍",
"zhi.auto_on": "자동 찍찍 중 (눌러서 멈추기)",
"title.heading": "칭호와 색상 (관리자)",
"title.name": "칭호",
"title.color": "색상",
"title.hint": "색상은 UID와 칭호에 적용되어 사이드바, 프로필, 카드에 표시됩니다. 칭호는 비워 둘 수 있습니다.",
"title.save": "적용",
"title.clear": "지우기",
"title.saved": "칭호를 업데이트했습니다",
"err.title_too_long": "칭호는 최대 16자입니다",
"err.invalid_color": "색상 형식이 올바르지 않습니다",
"err.user_not_found": "사용자를 찾을 수 없습니다"
}
+99
View File
@@ -0,0 +1,99 @@
{
"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.login_first": "不是松鼠,是鼯鼠。登录后每天吱吱签到一次,领一张吱吱小卡。",
"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": "找不到",
"site.tagline": "你今天吱吱了吗",
"zhi.hint": "点击吱吱",
"zhi.more": "继续吱吱",
"zhi.back": "回到小卡",
"zhi.later": "等等再吱",
"zhi.count": "吱吱 {n} 次",
"zhi.open": "去吱吱",
"checkin.clicks": "吱吱 {n} 次",
"err.bad_request": "请求格式不正确",
"zhi.auto": "全自动吱吱",
"zhi.auto_on": "全自动吱吱中(点我停止)",
"title.heading": "称号与颜色(管理员)",
"title.name": "称号",
"title.color": "颜色",
"title.hint": "颜色会套在 UID 和称号上,显示在侧栏、个人页和小卡。称号可以留空,只上颜色。",
"title.save": "应用",
"title.clear": "清除",
"title.saved": "已更新称号",
"err.title_too_long": "称号最多 16 个字",
"err.invalid_color": "颜色格式不正确",
"err.user_not_found": "找不到这个用户"
}
+99
View File
@@ -0,0 +1,99 @@
{
"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.login_first": "不是松鼠,是鼯鼠。登入後每天吱吱簽到一次,領一張吱吱小卡。",
"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": "找不到",
"site.tagline": "你今天吱吱了嗎",
"zhi.hint": "點擊吱吱",
"zhi.more": "繼續吱吱",
"zhi.back": "回到小卡",
"zhi.later": "等等再吱",
"zhi.count": "吱吱 {n} 次",
"zhi.open": "去吱吱",
"checkin.clicks": "吱吱 {n} 次",
"err.bad_request": "請求格式不正確",
"zhi.auto": "全自動吱吱",
"zhi.auto_on": "全自動吱吱中(點我停止)",
"title.heading": "稱號與顏色(管理員)",
"title.name": "稱號",
"title.color": "顏色",
"title.hint": "顏色會套在 UID 和稱號上,顯示在側欄、個人頁和小卡。稱號可以留空,只上顏色。",
"title.save": "套用",
"title.clear": "清除",
"title.saved": "已更新稱號",
"err.title_too_long": "稱號最多 16 個字",
"err.invalid_color": "顏色格式不正確",
"err.user_not_found": "找不到這個使用者"
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

+212
View File
@@ -0,0 +1,212 @@
<!DOCTYPE html>
<html lang="zh-Hant-TW">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>吱鼯計畫<!--BETA_TITLE--> — 你今天吱吱了嗎</title>
<meta name="description" content="吱鼯計畫:你今天吱吱了嗎">
<meta name="theme-color" content="#1a0f06">
<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/zhizhi-poster.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 class="brand-text"><b>吱鼯計畫<!--BETA_BADGE--></b><small data-i18n="site.tagline"></small></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>
<img class="big-logo" src="/assets/icon-192.png" alt="" width="120" height="120">
<div class="big-mark">吱鼯計畫</div>
<p class="tagline" data-i18n="site.tagline"></p>
<p class="muted" 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="zhi-open" class="zhi-open" type="button">
<img src="/assets/media/zhizhi-poster.webp?v=__ASSET_VERSION__" alt="" width="1080" height="1920" draggable="false">
<span class="zhi-open-label" data-i18n="zhi.open"></span>
</button>
<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="" 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>
<button id="zhi-more" type="button" data-i18n="zhi.more"></button>
</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>
<!-- 管理員才看得到:指定這個 UID 的顏色與稱號 -->
<form id="title-form" class="title-form" hidden novalidate>
<h2 data-i18n="title.heading"></h2>
<div class="row">
<label class="grow"><span data-i18n="title.name"></span>
<input id="title-text" maxlength="16" autocomplete="off">
</label>
<label><span data-i18n="title.color"></span>
<input id="title-color" type="color" value="#ff8a1f">
</label>
</div>
<p class="hint" data-i18n="title.hint"></p>
<p class="error" id="title-error" hidden></p>
<div class="row">
<span class="spacer"></span>
<button type="button" id="title-clear" data-i18n="title.clear"></button>
<button type="submit" class="primary" id="title-save" data-i18n="title.save"></button>
</div>
</form>
</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="zhi-stage" class="zhi-stage" hidden>
<video id="zhi-video" src="/assets/media/zhizhi.mp4?v=__ASSET_VERSION__" poster="/assets/media/zhizhi-poster.webp?v=__ASSET_VERSION__"
playsinline webkit-playsinline preload="auto" disablepictureinpicture disableremoteplayback></video>
<div id="zhi-hint" class="zhi-hint" data-i18n="zhi.hint"></div>
<div id="zhi-count" class="zhi-count" hidden></div>
<button id="zhi-exit" class="zhi-exit" type="button"></button>
<!-- 繼續吱吱才有:打開後播完自動接著吱下一次 -->
<button id="zhi-auto" class="zhi-auto" type="button" aria-pressed="false" hidden></button>
</div>
<div id="toast" role="status" hidden></div>
</body>
</html>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

+12
View File
@@ -0,0 +1,12 @@
{
"name": "吱鼯計畫",
"short_name": "吱鼯計畫",
"start_url": "/",
"display": "standalone",
"background_color": "#1a0f06",
"theme_color": "#1a0f06",
"icons": [
{ "src": "/assets/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/assets/icon-512.png", "sizes": "512x512", "type": "image/png" }
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.
+381
View File
@@ -0,0 +1,381 @@
:root {
--bg: #1a0f06;
--panel: #27170a;
--panel-2: #35200e;
--line: #5a3a1c;
--text: #fff6ea;
--muted: #d9b993;
--accent: #ff8a1f;
--accent-ink: #2a1400;
--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; }
.brand-text { display: flex; flex-direction: column; line-height: 1.25; }
.brand-text small { font-size: 12px; font-weight: 500; color: var(--accent); }
#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 一致);
管理員指定的顏色由 app.js 直接寫在 style 上 */
.uid-wrap { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.profile .uid-wrap { justify-content: center; }
.uid { color: var(--muted); font-variant-numeric: tabular-nums; }
.uid.badge, .title-badge {
display: inline-block;
font-weight: 700;
padding: 2px 10px;
border-radius: 8px;
margin-top: 2px;
}
.uid.tier-admin, .title-badge.tier-admin { background: #ffd166; color: #2a1400; }
/* 管理員在個人頁設定稱號的表單 */
.title-form {
width: 100%;
text-align: left;
margin-top: 20px;
padding: 16px 20px;
background: var(--panel);
border: 1px dashed var(--accent);
border-radius: var(--radius);
}
.title-form h2 { font-size: 16px; margin: 0; }
.title-form .row { align-items: flex-end; flex-wrap: nowrap; }
.title-form .grow { flex: 1; min-width: 0; }
.title-form input[type=color] { width: 64px; height: 44px; padding: 4px; cursor: pointer; }
.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-logo { width: 120px; height: 120px; border-radius: 28%; margin-top: 8vh; box-shadow: 0 16px 48px #ff8a1f44; }
.big-mark { font-size: 64px; font-weight: 900; letter-spacing: .08em; color: var(--accent); line-height: 1.2; }
.tagline { font-size: 22px; font-weight: 700; margin: 0; }
/* 「等等再吱」之後留在頁面上的入口:影片第一幀的縮圖,點了重新打開全螢幕 */
.zhi-open {
position: relative;
width: 180px;
aspect-ratio: 9 / 16;
margin-top: 4vh;
padding: 0;
overflow: hidden;
border-radius: 24px;
border: 3px solid var(--accent);
background: var(--panel-2);
box-shadow: 0 16px 48px #ff8a1f44;
transition: transform .15s;
}
.zhi-open img { width: 100%; height: 100%; object-fit: cover; display: block; user-select: none; }
.zhi-open-label {
position: absolute;
left: 0; right: 0; bottom: 0;
padding: 24px 0 12px;
background: linear-gradient(transparent, #000c 70%);
color: #fff;
font-size: 22px;
font-weight: 900;
letter-spacing: .1em;
}
.zhi-open:hover { transform: scale(1.04); }
.zhi-open:active { transform: scale(.97); }
/* ---------- 全螢幕吱吱 ---------- */
body.zhi-on { overflow: hidden; }
.zhi-stage {
position: fixed;
inset: 0;
z-index: 30;
overflow: hidden;
background: #1a0f06;
cursor: pointer;
user-select: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: transparent;
touch-action: manipulation; /* 連點時不要觸發雙擊放大 */
}
/* 影片是直式的:寬螢幕上兩側用放大模糊的第一幀填滿 */
.zhi-stage::before {
content: "";
position: absolute;
inset: -40px;
background: url("/assets/media/zhizhi-poster.webp") center / cover;
filter: blur(28px) brightness(.55);
}
.zhi-stage video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
pointer-events: none;
}
@media (min-aspect-ratio: 3/4) {
.zhi-stage video { object-fit: contain; }
}
.zhi-hint {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
white-space: nowrap;
pointer-events: none;
font-size: clamp(40px, 11vw, 96px);
font-weight: 900;
letter-spacing: .08em;
color: #fff;
-webkit-text-stroke: 2px #2a1400;
paint-order: stroke fill;
text-shadow: 0 4px 0 #ff8a1f, 0 10px 32px #000a;
animation: zhi-breathe 1.4s ease-in-out infinite;
}
.zhi-stage.playing .zhi-hint { display: none; }
@keyframes zhi-breathe {
0%, 100% { transform: translate(-50%, -50%) scale(1); }
50% { transform: translate(-50%, -50%) scale(1.08); }
}
.zhi-count, .zhi-exit {
position: absolute;
top: max(16px, env(safe-area-inset-top));
padding: 8px 18px;
border-radius: 999px;
border: 1px solid #ffffff33;
background: #1a0f06cc;
color: #fff;
font-weight: 700;
backdrop-filter: blur(6px);
}
.zhi-count { right: 16px; color: var(--accent); font-size: 18px; font-variant-numeric: tabular-nums; pointer-events: none; }
.zhi-count.bump { animation: zhi-bump .18s ease-out; }
@keyframes zhi-bump { 50% { transform: scale(1.18); } }
.zhi-exit { left: 16px; font-size: 15px; }
/* 全自動吱吱:中下方的開關 */
.zhi-auto {
position: absolute;
left: 50%;
bottom: max(28px, env(safe-area-inset-bottom));
transform: translateX(-50%);
white-space: nowrap;
padding: 12px 28px;
border-radius: 999px;
border: 2px solid var(--accent);
background: #1a0f06cc;
color: #fff;
font-size: 18px;
font-weight: 800;
letter-spacing: .05em;
backdrop-filter: blur(6px);
}
.zhi-auto.on { background: var(--accent); color: var(--accent-ink); box-shadow: 0 0 28px #ff8a1faa; }
/* 粒子:位置、方向、距離、顏色由 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: 40;
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; }
.zhi-hint, .zhi-count.bump { 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: 50;
}
.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; }
.big-logo { margin-top: 4vh; }
.big-mark { font-size: 48px; }
}