8 Commits
Author SHA1 Message Date
Sahik d2bba07749 更新示意圖 2026-12-01 03:55:10 +08:00
Sahik 695e29324e 新增搜尋框,放兩個開源連結 2026-12-01 03:44:06 +08:00
Sahik 61e8580c72 編輯個人資料改地方、圖片自帶出處 2026-11-26 11:45:04 +08:00
Sahik e75f0c95e9 安全性更新 2026-11-25 15:57:10 +08:00
Sahik 5bd77d2599 優化顯示與增強反作弊 2026-11-25 14:28:56 +08:00
Sahik d2be83ee77 update 2026-11-25 11:47:17 +08:00
Sahik 8652f90d50 刪除 zhiwuproject-1.0.0.tar.gz 2026-11-22 19:46:44 +08:00
Sahik f24d6fe0f9 訪客功能、Yuzumi主頁導向 2026-11-22 19:45:40 +08:00
53 changed files with 2950 additions and 414 deletions

No files matched your search

+2
View File
@@ -9,3 +9,5 @@ image
icon
tools
media-src
Version.md
make.md
+2 -3
View File
@@ -2,8 +2,6 @@
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
@@ -21,7 +19,8 @@ SMTP_PASSWORD=
MAIL_FROM=[email protected]
# ---- 管理員(UID 00000000)----
# 登入框的信箱欄輸入 ADMIN_LOGIN,驗證碼用 Aegis 等 TOTP App 算(SHA1、6 位、30 秒)
# 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=
+1
View File
@@ -10,3 +10,4 @@ image/
# 開發筆記(不公開)
dev.md
Version.md
+17 -19
View File
@@ -2,11 +2,11 @@
> 你今天吱吱了嗎
每天來吱一下,領一張吱吱小卡的簽到網站。
每天來吱一下,領一張吱咪小卡的簽到網站。
**https://zhiwu-project.sthkm3.org**
**https://zhiwu-project.sahik.dev**
<img src="png/zhiwu-2026-11-22.png" alt="吱吱小卡:上方是隨機圖片,下方是名稱、UID、簽到天數與吱吱次數" width="360">
<img src="png/zhiwu-sahik-dev.png" alt="吱咪小卡:上方是隨機圖片(右下角是出處),下方是名稱、UID、簽到天數與吱吱次數" width="360">
## 怎麼玩
@@ -16,15 +16,20 @@
每天台灣時間 04:00 換日,換日後可以再簽到一次。
不想登入也可以按「訪客吱吱」直接吱。
## 功能
- **吱吱小卡**:每次簽到從圖庫隨機抽一張圖,加上你的名稱、大頭貼、簽到天數和吱吱次數。分享連結貼到 Discord、X、LINE 會出現小卡預覽
- **繼續吱吱**:簽到完還想吱,可以回去一直吱。每吱完一次才能吱下一次,一秒最多算一次
- **吱咪小卡**:每次簽到從圖庫隨機抽一張圖,加上你的名稱、大頭貼、簽到天數和吱吱次數。分享連結貼到 Discord、X、LINE 會出現小卡預覽
- **繼續吱吱**:簽到完還想吱,可以回去一直吱。每吱完一次才能吱下一次,1.5 秒最多算一次
- **全自動吱吱**:懶得點的話,繼續吱吱畫面下方有開關,打開就會自己一直吱
- **訪客吱吱**:不用登入就能吱,會拿到一張「訪客 #四位亂碼」的小卡。代號和次數只記在你自己的瀏覽器,伺服器不會記;之後登入的話帳號從頭算,訪客的次數不會帶過去
- **兩個數字分開算**:簽到天數一天只加一次;吱吱次數每吱一下加一次
- **投稿圖片**:可以上傳你覺得適合放上小卡的圖,每天最多 5 張,管理員審核通過後加入圖庫
- **個人頁**:名稱、大頭貼、自我介紹(支援 Markdown)
- **投稿圖片**:可以上傳你覺得適合放上小卡的圖,每天最多 5 張,可以附上出處;管理員審核通過後加入圖庫,出處會小小地寫在小卡圖片的右下角
- **個人頁**:名稱、大頭貼、自我介紹(支援 Markdown),在自己的個人頁按「編輯」修改
- **稱號**:管理員可以幫指定的 UID 加上顏色和稱號
- **UID 搜尋**:在選單上方輸入 UID 按 Enter,直接打開那個人的個人頁
- **加到主畫面**:手機上可以安裝到桌面,像 App 一樣打開
- **語言**:繁體中文、简体中文、日本語、한국어、English
## 關於這個網站
@@ -32,22 +37,15 @@
這是粉絲做的玩笑網站,梗來自子午計畫(Meridian Project)的橙 Yuzumi。本站和子午計畫官方沒有任何關係,站上的影片與圖片版權屬於原作者。
- 信箱只用來寄登入驗證碼
- 訪客吱吱不會在伺服器留下任何紀錄
- 上傳的圖片會重新編碼並移除 EXIF(包含 GPS)資訊
## 自己架一個
## 想改一個自己的
需要 Docker。
```
cp .env.example .env
docker network create tunnel
docker compose up -d --build
```
打開 `http://127.0.0.1:2041`。`.env` 裡的寄信帳密留空時不會寄信,驗證碼會印在 `docker compose logs zhiwuproject`。
圖庫放在 `image/`(jpg / png / webp / gif),新增圖片不用重啟。
clone 之後要改哪裡、怎麼部署:[make.md](make.md)
## 技術
FastAPI + SQLite,小卡用 Pillow 在伺服器端畫成 PNG;前端是不用框架的 HTML / CSS / JavaScript。整包跑在一個 Docker 容器裡,透過 Cloudflare Tunnel 對外。
原始碼:[GitHub](https://github.com/Sthkm3/ZhiwuProject)、[Gitea](https://gitea.sthkm3.org/sthkm3/ZhiwuProject)
-1
View File
@@ -14,7 +14,6 @@ services:
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:-}
+98
View File
@@ -0,0 +1,98 @@
# 改一個自己的
clone 之後要改哪些地方、怎麼在自己的電腦跑起來、怎麼部署。
站上的影片、圖片與角色版權屬於原作者,改成自己的站請換成你有權使用的素材。
## 要改的地方
| 想改什麼 | 在哪裡 |
|---|---|
| 站名、標題 | `web/index.html`、`web/manifest.webmanifest`、`server/app/share.py`、`server/app/mailer.py`(寄件人名稱)、`server/app/main.py`、`server/app/totp.py` |
| 介面文字(五種語言) | `web/i18n/*.json`;每個語言的 key 要一樣 |
| 信件、小卡、分享文字 | `server/app/i18n/*.json` |
| 吱吱影片 | 換掉 `media-src/zhizhi.mp4`,執行 `tools/make_media.py` |
| 圖標 | 換掉 `icon/zhiwu.jpg`,執行 `tools/make_icons.py`(也會產生圖庫是空的時候用的預設圖) |
| 圖庫 | 用管理員登入後的「管理圖片」新增、改出處、下架;也可以直接把圖放進 `image/`(jpg / png / webp / gif),不用重啟 |
| 網頁顏色 | `web/style.css` 最上面的 `:root` |
| 小卡版面與顏色 | `server/app/card.py`;改完把 `CARD_VERSION` 加 1,舊的小卡才會重畫 |
| UID 底色 | `server/app/titles.py` 和 `web/style.css` 的 `.uid`,兩邊要一樣 |
| 頁尾連結 | `web/index.html` 的 `.site-footer`、`server/app/share.py` |
| 換日時間、各種上限 | `server/app/config.py` |
| 版本號 | `server/app/__init__.py` |
| 容器名稱、port | `docker-compose.yml` |
兩個 `tools/` 的程式要先裝 Pillow 和 imageio-ffmpeg:
```
pip install pillow imageio-ffmpeg
python tools/make_media.py
python tools/make_icons.py
```
## 在自己的電腦跑
需要 Docker。
```
cp .env.example .env
docker network create tunnel
docker compose up -d --build
```
`.env` 先改成本機用的:
```
PUBLIC_URL=http://localhost:2041
COOKIE_SECURE=0
```
打開 `http://localhost:2041`。`SMTP_PASSWORD` 留空時不會寄信,驗證碼印在 `docker compose logs zhiwuproject`。
跑測試:
```
cd server
python -m venv .venv
.venv/Scripts/python -m pip install -r requirements-dev.txt # macOS / Linux 是 .venv/bin/python
.venv/Scripts/python -m pytest -q
```
## .env
| 名稱 | 用途 |
|---|---|
| `PUBLIC_URL` | 對外網址。分享連結、預覽圖、信件和小卡角落的網域都用它 |
| `COOKIE_SECURE` | 用 https 對外時設 `1` |
| `PORT` | 本機的 port,只綁 127.0.0.1(預設 2041) |
| `TUNNEL_NETWORK` | cloudflared 所在的 Docker 網路 |
| `SMTP_HOST`、`SMTP_PORT`、`SMTP_USER`、`SMTP_PASSWORD` | 寄驗證碼的信箱服務。465 用 SSL,其他用 STARTTLS |
| `MAIL_FROM` | 寄件人,網域要在寄信服務驗證過 |
| `ADMIN_LOGIN`、`ADMIN_TOTP` | 管理員登入用的名稱與 base32 密鑰,兩個都留空就停用。名稱要是信箱格式(不會寄信),前綴用猜不到的字,不要用任何使用者的信箱。登入時在信箱欄輸入它,驗證碼用 Aegis 等 TOTP App 看 |
產生一組 `ADMIN_TOTP`:
```
python -c "import base64, secrets; print(base64.b32encode(secrets.token_bytes(20)).decode())"
```
## 部署
1. 設好 `PUBLIC_URL`、`COOKIE_SECURE=1`、SMTP 和管理員
2. 把 cloudflared 放在同一個 Docker 網路,Public Hostname 指到 `http://zhiwuproject:2040`
3. `docker compose up -d --build`
不要直接把容器的 port 開到外網:限流會信任 `CF-Connecting-IP`,繞過 Cloudflare 就能偽造。
資料在 `/data`(資料庫、大頭貼、投稿、小卡快取),圖庫在 `/memes`,這兩個要掛出來並備份。
容器用 UID/GID **3007:3004** 執行(不是 root),掛進來的資料夾要給它:
```
chown -R 3007:3004 <資料夾>
chmod -R u=rwX,go= <資料夾>
```
也可以用 Docker 的 `user` 設定換成別的 UID,資料夾的擁有者一起換就好。從以 root 執行的舊版升級時也要做一次;資料夾不能讀寫時,啟動的 log 會寫要怎麼改。
程式只能跑一個 worker,限流和冷靜時間都記在記憶體。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 623 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 658 KiB

+5
View File
@@ -18,5 +18,10 @@ COPY web ./web
ENV DATA_DIR=/data MEME_DIR=/memes WEB_DIR=/app/web
EXPOSE 2040
# 不用 root 執行。掛進來的 /data、/memes 要給這個 UID(或用 docker 的 user 設定換成別的 UID)
RUN groupadd -g 3004 zhiwu && useradd -u 3007 -g 3004 -M -s /usr/sbin/nologin zhiwu \
&& mkdir -p /data /memes && chown 3007:3004 /data /memes
USER 3007:3004
# SQLite 與記憶體裡的限流都假設只有一個 worker
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "2040", "--workers", "1"]
+2
View File
@@ -0,0 +1,2 @@
"""版本號只寫在這裡,頁尾會顯示;發布新版本時改這一行。"""
__version__ = "1.2.0"
+2 -2
View File
@@ -104,7 +104,7 @@ def cmd_totp_uri(args):
def cmd_reset_progress(args):
"""清空所有簽到紀錄與小卡(Beta 結束、正式上線時用)。帳號、UID、名稱、大頭貼、自介都保留。"""
"""清空所有簽到紀錄與小卡。帳號、UID、名稱、大頭貼、自介都保留。"""
conn = db.connect()
checkins = conn.execute("SELECT COUNT(*) FROM checkins").fetchone()[0]
users = conn.execute("SELECT COUNT(DISTINCT uid) FROM checkins").fetchone()[0]
@@ -117,7 +117,7 @@ def cmd_reset_progress(args):
conn.backup(dst)
dst.close()
conn.execute("DELETE FROM checkins")
conn.execute("UPDATE users SET clicks = 0")
conn.execute("UPDATE users SET clicks = 0, flagged_at = NULL")
shutil.rmtree(config.DATA_DIR / "cards", ignore_errors=True)
(config.DATA_DIR / "cards").mkdir(exist_ok=True)
print(f"完成。備份在 {backup}")
+45
View File
@@ -0,0 +1,45 @@
"""反作弊:每小時檢查一次有沒有帳號的吱吱次數超過理論上限。
理論上限 = 從最初架設(meta.server_start)到現在的秒數 / ZHI_GAP。
超過就標記(users.flagged_at)並通知管理員;只是標記,不扣次數也不封鎖。
"""
import asyncio
from . import clock, config, db, limits, notices
from .titles import fmt_uid
def click_limit(conn) -> int:
start = db.get_meta(conn, "server_start", clock.ts())
return max(0, int((clock.ts() - start) / config.ZHI_GAP))
def check() -> list[int]:
"""標記超過上限的帳號,回傳這次新標記的 UID。"""
conn = db.connect()
try:
limit = click_limit(conn)
rows = conn.execute("SELECT uid, clicks FROM users WHERE clicks > ? AND uid != ? AND flagged_at IS NULL",
(limit, config.ADMIN_UID)).fetchall()
for r in rows:
conn.execute("UPDATE users SET flagged_at = ? WHERE uid = ?", (clock.ts(), r["uid"]))
notices.add("flagged", r["uid"], f"{r['clicks']:,} > {limit:,}")
print(f"[anticheat] flagged UID {fmt_uid(r['uid'])} clicks={r['clicks']} limit={limit}", flush=True)
return [r["uid"] for r in rows]
finally:
conn.close()
def check_safe() -> None:
try:
check()
except Exception as e:
print(f"[anticheat] check failed: {type(e).__name__}: {e}", flush=True)
notices.add("error", None, f"anticheat: {type(e).__name__}")
async def loop() -> None:
while True:
await asyncio.sleep(config.CHECK_INTERVAL)
await asyncio.to_thread(check_safe)
limits.sweep_all() # 順便清掉過期的限流紀錄
+62 -46
View File
@@ -1,18 +1,18 @@
"""信箱驗證碼登入(沒有密碼):第一次驗證成功就自動建立帳號。
管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 Aegis 算的 TOTP(不寄信)。錯 3 次就全域鎖定,時間逐次加倍。
對外的回應和一般信箱完全相同(包括鎖定時),別人沒辦法從回應試出哪個是管理員。
"""
import re
import random
import secrets
import sqlite3
import threading
import time
from collections import defaultdict, deque
from collections import deque
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel
from . import clock, config, db, mailer, totp
from . import clock, config, db, limits, mailer, notices, 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
@@ -20,36 +20,33 @@ 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()
_ip_mail = limits.Window("IP_LIMIT", "IP_WINDOW") # 同一 IP 的寄信次數
_all_mail = limits.Window("MAIL_LIMIT", "MAIL_WINDOW") # 全站的寄信次數
_day_mail = limits.Window("MAIL_DAY_LIMIT", "MAIL_DAY_WINDOW")
_send_times: deque = deque(maxlen=20) # 最近實際寄信花的秒數;管理員不寄信,用它等差不多久
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 is_admin(conn: sqlite3.Connection, email: str) -> bool:
"""管理員的信箱。就算管理員登入停用了也算:不能寄信給它,也不能用一般流程登入。"""
row = conn.execute("SELECT uid FROM users WHERE email = ?", (email,)).fetchone()
return row is not None and row["uid"] == config.ADMIN_UID
def norm_email(email: str) -> str:
email = email.strip().lower()
if len(email) > 254 or not EMAIL_RE.match(email):
if not limits.valid_email(email):
fail(400, "invalid_email")
return email
def mail_allowed() -> bool:
for window, name in ((_day_mail, "24 h"), (_all_mail, "10 min")):
if not window.allow("all"):
notices.add("mail_limit", None, name)
return False
return True
class CodeRequest(BaseModel):
email: str
lang: str = config.DEFAULT_LANG
@@ -64,12 +61,6 @@ class VerifyRequest(BaseModel):
@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,))
@@ -77,7 +68,7 @@ def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection =
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)):
if not _ip_mail.allow(limits.ip_key(client_ip(request))) or not mail_allowed():
fail(429, "too_many_requests")
# secrets 才是密碼學安全的亂數
@@ -88,11 +79,19 @@ def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection =
"expires_at = excluded.expires_at, last_sent_at = excluded.last_sent_at",
(email, sha256(code), now + config.CODE_TTL, now),
)
if is_admin(conn, email):
# 管理員不寄信,驗證碼看 Aegis。等一段和實際寄信差不多的時間,從快慢也看不出來
if config.SMTP_USER and config.SMTP_PASSWORD:
time.sleep((random.choice(_send_times) if _send_times else 1.5) * random.uniform(0.9, 1.1))
return sent
started = time.monotonic()
try:
mailer.send_code(email, code, norm_lang(body.lang))
_send_times.append(time.monotonic() - started)
except Exception as e:
print("Error sending email:", e, flush=True)
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
notices.add("mail_failed", None, type(e).__name__)
fail(502, "send_failed")
return sent
@@ -126,7 +125,8 @@ def admin_check(conn: sqlite3.Connection, code: str, ip: str) -> str | None:
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"
notices.add("admin_locked", None, f"{lock // 60} min") # 交易結束後才寫
return "too_many_requests"
def issue_session(conn: sqlite3.Connection, response: Response, user: sqlite3.Row) -> dict:
@@ -149,13 +149,6 @@ def issue_session(conn: sqlite3.Connection, response: Response, user: sqlite3.Ro
@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()
@@ -167,18 +160,41 @@ def verify(body: VerifyRequest, request: Request, response: Response,
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
fail(400, "expired")
# 先用掉一次機會再比對(一句 SQL,同時送很多個也不會多猜)。認 code_hash:不會扣到剛重寄的新碼
this_code = (email, row["code_hash"])
used = conn.execute("UPDATE login_codes SET attempts = attempts + 1 "
"WHERE email = ? AND code_hash = ? AND attempts < ? RETURNING attempts",
(*this_code, config.CODE_MAX_ATTEMPTS)).fetchall()
if not used:
fail(400, "expired")
admin = is_admin(conn, email)
if admin:
# 停用時一律不對;鎖定中也只當作碼錯了,不透露這是管理員
err = admin_check(conn, code, client_ip(request)) if db.admin_ok else "wrong_code"
if err == "code_used": # 碼是對的,只是用過了:不算猜錯
conn.execute("UPDATE login_codes SET attempts = attempts - 1 WHERE email = ? AND code_hash = ?", this_code)
fail(400, err)
ok = err is None
else:
ok = code.isascii() and secrets.compare_digest(sha256(code), row["code_hash"])
# 錯太多次直接作廢,防止暴力猜碼
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,))
if not ok:
if used[0]["attempts"] >= config.CODE_MAX_ATTEMPTS:
conn.execute("DELETE FROM login_codes WHERE email = ? AND code_hash = ?", this_code)
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,))
# 驗證碼只能用一次(同時送兩個對的,只有一個成功)
if conn.execute("DELETE FROM login_codes WHERE email = ? AND code_hash = ?", this_code).rowcount == 0:
fail(400, "not_requested")
user = create_user(conn, email, body.lang)
if admin:
agent = "".join(ch for ch in request.headers.get("user-agent", "") if ch.isprintable())[:160]
country = request.headers.get("cf-ipcountry", "")[:8]
notices.add("admin_login", None, " · ".join(x for x in (client_ip(request)[:64], country, agent) if x),
merge=False)
return issue_session(conn, response, user)
+120 -52
View File
@@ -2,28 +2,31 @@
小卡上有吱吱(點擊)次數,所以快取檔名帶次數:<day>.v<版本>.c<次數>.png,次數變了就重畫。
"""
import io
import os
import random
import re
import shutil
import sqlite3
import tempfile
import threading
from collections import OrderedDict
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 fastapi import APIRouter, Depends, Request
from fastapi.responses import FileResponse, Response
from PIL import Image, ImageDraw, ImageFont, ImageOps
from . import config
from . import clock, config, images, limits
from .checkin import stats
from .db import get_db
from .deps import fail
from .deps import client_ip, fail
from .i18n import norm_lang, t
from .memes import list_memes, source_of
from .titles import badge_colors, fmt_uid
Image.MAX_IMAGE_PIXELS = 40_000_000 # 擋解壓縮炸彈
router = APIRouter()
W, H = 1080, 1350
@@ -33,7 +36,7 @@ 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,舊的快取自動作廢
CARD_VERSION = 3 # 版面改了就加 1,舊的快取自動作廢
DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
# Debian 套件 fonts-noto-cjk;同一個 .ttc 裡依序是 JP、KR、SC、TC、HK
@@ -83,20 +86,38 @@ def rounded_mask(size, radius) -> Image.Image:
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
load_image = images.load # RGBA,透明處要自己貼到底色上
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"]
def source_label(panel: Image.Image, lang: str, source: str, pic_box: tuple[int, int, int, int]) -> None:
"""圖的右下角小字寫出處(半透明深色底)。圖比框窄時,字太長就往左延伸到框內。"""
if not source:
return
f = font(lang, 26)
d = ImageDraw.Draw(panel)
text = fit_text(d, t(lang, "card.source", s=source), f, panel.width - 48 - 2 * 14)
tw = int(d.textlength(text, font=f))
left, top, right, bottom = pic_box
right = min(panel.width - 12, max(right - 12, 12 + tw + 28))
bottom = bottom - 12
layer = Image.new("RGBA", panel.size, (0, 0, 0, 0))
ld = ImageDraw.Draw(layer)
ld.rounded_rectangle((right - tw - 28, bottom - 42, right, bottom), 12, fill=(0, 0, 0, 150))
ld.text((right - 14, bottom - 21), text, font=f, fill=(255, 246, 234, 235), anchor="rm")
panel.alpha_composite(layer)
def on_color(im: Image.Image, color) -> Image.Image:
"""透明的圖貼到底色上(不然透明處會露出底下藏的顏色,常常是白色)。"""
base = Image.new("RGBA", im.size, (*color, 255))
base.alpha_composite(im.convert("RGBA"))
return base.convert("RGB")
def draw(lang: str, meme: str | None, name: str, avatar: Image.Image | None, badge: dict | None,
headline: str, sub: str, clicks: int, source: str = "") -> Image.Image:
"""小卡的版面。badge = {"uid": "UID 00000001", "colors": (底色, 文字色), "title": 稱號};
訪客沒有 UID,badge 傳 None,那一行就不畫。source = 圖的出處,空字串不畫。"""
# 背景:上下漸層
img = Image.new("RGB", (W, H))
top, bottom = (70, 38, 12), (24, 13, 5)
@@ -105,62 +126,58 @@ def render(user: sqlite3.Row, day: str, meme: str | None, total: int, streak: in
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))
panel = Image.new("RGBA", (box_w, box_h), (18, 10, 4, 255))
pic = load_image(config.MEME_DIR / meme) if meme else None
pic = pic or load_image(DEFAULT_MEME) # 圖庫是空的(或圖被刪了)就用預設圖
if pic is None:
pic, source = 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))
x, y = (box_w - pic.width) // 2, (box_h - pic.height) // 2
panel.alpha_composite(pic, (x, y)) # 透明處就是框的深色底
source_label(panel, lang, source, (x, y, x + pic.width, y + pic.height))
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))
pd.text((box_w / 2, box_h / 2), t(lang, "card.no_meme"), font=font(lang, 48), fill=MUTED, anchor="mm")
img.paste(panel.convert("RGB"), (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)
avatar = on_color(avatar.resize((av_size, av_size), Image.LANCZOS), ACCENT)
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")
ad.text((av_size / 2, av_size / 2), (name or "?")[0], 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、稱號(管理員指定的顏色或預設的特殊序號用背景色標示)
# 名稱;有 UID 的話下一行是 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
if badge:
d.text((tx, av_y + 14), fit_text(d, name, f_name, max_w), font=f_name, fill=TEXT)
bg, fg = badge["colors"]
uid_y = av_y + 120 # UID 這一行的垂直中心
f_uid = font("en", 36, True)
tw = d.textlength(uid_text, font=f_uid)
tw = d.textlength(badge["uid"], 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 後面,同樣的顏色
d.text((tx + 18, uid_y), badge["uid"], font=f_uid, fill=fg, anchor="lm")
if badge["title"]:
x = tx + tw + 36 + 16
f_title = font(lang, 36, True)
title = fit_text(d, user["title"], f_title, int(W - PAD - x - 36))
title = fit_text(d, badge["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")
# 訪客:只有名稱,垂直置中在大頭貼旁邊
d.text((tx, av_y + av_size / 2), fit_text(d, name, f_name, max_w), font=f_name, fill=TEXT, 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)
@@ -169,17 +186,30 @@ def render(user: sqlite3.Row, day: str, meme: str | None, total: int, streak: in
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 + 24), fit_text(d, headline, f_day, int(W - 2 * PAD - num_w - 40)), font=f_day, fill=TEXT)
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")
d.text((W - PAD, H - PAD), host, font=font("en", 30, True), fill=ACCENT, anchor="rs")
return img
def render(user: sqlite3.Row, day: str, meme: str | None, total: int, streak: int, clicks: int,
source: str = "") -> Image.Image:
"""登入使用者的小卡。"""
lang = norm_lang(user["lang"])
avatar = load_image(config.DATA_DIR / "avatars" / f"{user['uid']}.webp") if user["avatar_ver"] else None
badge = {"uid": f"UID {fmt_uid(user['uid'])}", "colors": badge_colors(user), "title": user["title"]}
return draw(lang, meme, user["display_name"], avatar, badge,
t(lang, "card.day", n=total), f"{t(lang, 'card.streak', n=streak)} · {day}", clicks, source)
def render_guest(lang: str, code: str, day: str, meme: str | None, clicks: int, source: str = "") -> Image.Image:
"""訪客的小卡:名稱是「訪客 #XXXX」,沒有 UID、沒有顏色,也沒有簽到天數。"""
return draw(lang, meme, t(lang, "card.guest_name", code=code), None, None, t(lang, "card.guest"), day, clicks,
source)
def card_dir(uid: int) -> Path:
return config.DATA_DIR / "cards" / str(uid)
@@ -199,7 +229,7 @@ def card_path(conn: sqlite3.Connection, uid: int, day: str) -> Path | None:
if path.exists():
return path
total, streak = stats(conn, uid, day)
img = render(user, day, row["meme"], total, streak, user["clicks"])
img = render(user, day, row["meme"], total, streak, user["clicks"], source_of(row["meme"], conn))
folder.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
with os.fdopen(fd, "wb") as f:
@@ -223,3 +253,41 @@ def get_card(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
if path is None:
fail(404, "not_found")
return FileResponse(path, media_type="image/png", headers={"Cache-Control": "public, max-age=60"})
# ---------- 訪客小卡:伺服器不記任何訪客資料,代號和次數都是瀏覽器自己帶來的 ----------
GUEST_CODE_RE = re.compile(r"^[A-Z0-9]{4}$")
_guest_lock = threading.Lock()
_guest_hits = limits.Window("GUEST_CARD_LIMIT", "GUEST_CARD_WINDOW")
_guest_cache: "OrderedDict[tuple, bytes]" = OrderedDict() # 最近畫過的幾張(PNG)
def guest_meme(code: str, day: str) -> str | None:
"""同一個訪客同一天固定抽到同一張(伺服器沒有地方記,所以用代號 + 日期當亂數種子)。"""
memes = list_memes()
return random.Random(f"{code}:{day}").choice(memes) if memes else None
@router.get("/card/guest.png")
def get_guest_card(request: Request, code: str = "", n: str = "0", lang: str = config.DEFAULT_LANG):
if not GUEST_CODE_RE.match(code) or len(n) > 7 or not n.isascii() or not n.isdigit() or int(n) > config.GUEST_CLICKS_MAX:
fail(404, "not_found")
clicks, lang, day = int(n), norm_lang(lang), clock.today()
meme = guest_meme(code, day)
source = source_of(meme)
key = (code, clicks, lang, day, meme, source, CARD_VERSION)
with _guest_lock:
png = _guest_cache.get(key)
if png is None:
if not _guest_hits.allow(limits.ip_key(client_ip(request))):
fail(429, "too_many_requests")
buf = io.BytesIO()
render_guest(lang, code, day, meme, clicks, source).save(buf, "PNG")
png = buf.getvalue()
_guest_cache[key] = png
while len(_guest_cache) > config.GUEST_CARD_CACHE:
_guest_cache.popitem(last=False)
else:
_guest_cache.move_to_end(key)
return Response(png, media_type="image/png", headers={"Cache-Control": "private, max-age=60"})
+33 -23
View File
@@ -1,12 +1,15 @@
import secrets
import sqlite3
import threading
import time
from collections import deque
from datetime import date, timedelta
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from . import clock, config
from . import clock, config, notices
from .memes import list_memes # noqa: F401 (其他模組和測試也從這裡拿)
from .db import get_db, transaction
from .deps import current_user, fail
from .i18n import t
@@ -14,18 +17,6 @@ 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
@@ -100,17 +91,31 @@ def do_checkin(user=Depends(current_user), conn: sqlite3.Connection = Depends(ge
# ---------- 繼續吱吱:只加點擊次數,和簽到天數無關 ----------
_now = time.monotonic # 測試會換掉
_buckets: dict[int, tuple[float, float]] = {} # uid -> (剩餘額度, 上次更新時間)
_zhi_lock = threading.Lock() # 端點跑在 threadpool,同時送多個請求也不能多算
_next: dict[int, float] = {} # uid -> 下一下的時間
_rejects: dict[int, deque] = {} # uid -> 最近被擋下的時間
_cool: dict[int, 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
def _take(uid: int) -> tuple[str, bool]:
"""回傳 (結果, 是不是剛進入冷靜)。結果:ok = 加 1 下 / early = 太快,這下不算 / cooldown = 冷靜中。"""
with _zhi_lock:
now = _now()
if now < _cool.get(uid, now):
return "cooldown", False
due = _next.get(uid, now)
if now >= due - config.ZHI_JITTER:
_next[uid] = max(now, due) + config.ZHI_GAP
return "ok", False
q = _rejects.setdefault(uid, deque())
while q and q[0] < now - config.COOL_WINDOW:
q.popleft()
q.append(now)
if len(q) < config.COOL_REJECTS:
return "early", False
q.clear()
_cool[uid] = now + config.COOL_SECONDS
return "cooldown", True
class ZhiIn(BaseModel):
@@ -121,7 +126,12 @@ class ZhiIn(BaseModel):
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)
result, started = _take(user["uid"])
if started:
notices.add("cooldown", user["uid"])
if result == "cooldown":
fail(429, "cooldown")
added = int(result == "ok")
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]
+43 -7
View File
@@ -31,8 +31,6 @@ 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"
@@ -53,7 +51,28 @@ IP_WINDOW = 10 * 60
SESSION_TTL = 90 * 24 * 3600
ADMIN_SESSION_TTL = 7 * 24 * 3600
# 管理員:信箱欄輸入 ADMIN_LOGIN,驗證碼是 ADMIN_TOTP(base32 密鑰)算出的 TOTP。兩個都設定才啟用
# 全站寄信上限:擋轟炸別人信箱,也避免把寄信服務的額度用光
MAIL_LIMIT = 40
MAIL_WINDOW = 10 * 60
MAIL_DAY_LIMIT = 400
MAIL_DAY_WINDOW = 24 * 3600
# 請求大小上限
BODY_MAX = 64 * 1024
UPLOAD_BODY_MAX = 6 * 1024 * 1024 # 圖片上限 5MB,加上表單的部分
UPLOAD_PATHS = ("/api/me/avatar", "/api/submissions", "/api/admin/memes")
# 上傳的圖:像素上限(2400 萬像素的手機照片可以過)、等前一張處理完最多幾秒
IMAGE_MAX_PIXELS = 30_000_000
IMAGE_WAIT = 10
# 每個帳號每分鐘最多處理幾次(失敗也算)
AVATAR_LIMIT = 3
SUBMIT_LIMIT = 10
ADMIN_ADD_LIMIT = 60 # 管理員在管理圖片新增
SOURCE_MAX = 40 # 圖片出處的長度上限
UPLOAD_WINDOW = 60
# 管理員: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
@@ -74,9 +93,26 @@ 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 # 最多累積幾下
# 繼續吱吱:一個帳號平均每 1.5 秒只能吱一次
ZHI_BATCH_MAX = 200 # 一次請求的 n 上限(超過直接拒絕);不管 n 是多少,一次請求最多加 1 下
ZHI_GAP = 1.5
ZHI_JITTER = 0.3 # 網路抖動時最多可以提早這麼多秒到,提早的會從下一下扣回來
# 太頻繁:COOL_WINDOW 秒內被上面的限制擋下 COOL_REJECTS 次,就冷靜 COOL_SECONDS 秒
COOL_REJECTS = 5
COOL_WINDOW = 10
COOL_SECONDS = 10
# 反作弊:多久檢查一次吱吱次數有沒有超過理論上限(見 anticheat.py)
CHECK_INTERVAL = 3600
# 管理員通知匣:同樣的通知 NOTICE_MERGE 秒內併成一則,最多留 NOTICE_KEEP 則
NOTICE_MERGE = 3600
NOTICE_KEEP = 500
# 訪客小卡:伺服器不存任何訪客資料,每次請求即時畫。畫一張要一點 CPU,所以依 IP 限流
GUEST_CARD_LIMIT = 30 # 同一 IP 每分鐘最多畫幾張(從快取拿的不算)
GUEST_CARD_WINDOW = 60
GUEST_CARD_CACHE = 32 # 記憶體裡留最近幾張(一張約 0.6 MB)
GUEST_CLICKS_MAX = 9_999_999
COOKIE_NAME = "zhiwu_session"
+46 -11
View File
@@ -2,7 +2,7 @@ import sqlite3
import time
from contextlib import contextmanager
from . import config
from . import clock, config
# init() 檢查管理員設定後填入;False 時管理員登入完全停用
admin_ok = False
@@ -23,6 +23,7 @@ CREATE TABLE IF NOT EXISTS users (
clicks INTEGER NOT NULL DEFAULT 0, -- 吱吱(點擊)總次數,和簽到天數分開算
title TEXT NOT NULL DEFAULT '', -- 管理員指定的稱號(空字串 = 沒有)
title_color TEXT NOT NULL DEFAULT '', -- 管理員指定的 UID 底色 #rrggbb(空字串 = 沒有)
flagged_at INTEGER, -- 吱吱次數超過理論上限,被標記的時間(NULL = 沒有)
created_at INTEGER NOT NULL
);
@@ -58,11 +59,32 @@ CREATE TABLE IF NOT EXISTS submissions (
ext TEXT NOT NULL, -- jpg / png
status TEXT NOT NULL DEFAULT 'pending', -- pending / approved / rejected
meme TEXT, -- 同意後的檔名,例如 zhiwu_14.jpg
source TEXT NOT NULL DEFAULT '', -- 投稿者填的出處
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);
-- 圖庫裡設定過出處或下架的圖(memes.py)。沒有資料列 = 沒出處、上架中
CREATE TABLE IF NOT EXISTS memes (
name TEXT PRIMARY KEY,
source TEXT NOT NULL DEFAULT '',
hidden_at INTEGER
);
-- 管理員通知匣(notices.py)
CREATE TABLE IF NOT EXISTS notices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL,
uid INTEGER REFERENCES users(uid) ON DELETE SET NULL ON UPDATE CASCADE,
detail TEXT NOT NULL DEFAULT '',
count INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
read_at INTEGER
);
CREATE INDEX IF NOT EXISTS notices_updated ON notices(updated_at);
"""
@@ -90,35 +112,48 @@ def init():
conn.executescript(SCHEMA)
conn.execute("INSERT OR IGNORE INTO meta(key, value) VALUES ('next_uid', 1)")
_migrate(conn)
# 最初架設時間:只在第一次寫入。1.0.1 以前的資料庫沒有記,用最早的帳號建立時間補
conn.execute("INSERT OR IGNORE INTO meta(key, value) "
"SELECT 'server_start', COALESCE(MIN(created_at), ?) FROM users", (clock.ts(),))
_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 ''",
# 後來才加的欄位:舊的資料庫(CREATE TABLE IF NOT EXISTS 不會補欄位)啟動時自動補上
_COLUMNS = {
"users": {
"clicks": "INTEGER NOT NULL DEFAULT 0",
"title": "TEXT NOT NULL DEFAULT ''",
"title_color": "TEXT NOT NULL DEFAULT ''",
"flagged_at": "INTEGER",
},
"submissions": {
"source": "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}")
for table, columns in _COLUMNS.items():
have = {r[1] for r in conn.execute(f"PRAGMA table_info({table})")}
for name, decl in columns.items():
if name not in have:
conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {decl}")
def _init_admin(conn: sqlite3.Connection) -> None:
"""建立或更新管理員帳號(uid 0)。改了 ADMIN_LOGIN 重啟就會生效。"""
global admin_ok
from . import totp
from . import limits, totp
admin_ok = False
login, secret = config.ADMIN_LOGIN, config.ADMIN_TOTP
if not login or not secret:
return
if not limits.valid_email(login):
print("[ERROR] ADMIN_LOGIN 要是信箱格式(例如 [email protected],不會真的寄信),管理員登入停用", flush=True)
return
try:
if len(totp.decode_secret(secret)) < 10:
raise ValueError("too short")
+5 -1
View File
@@ -7,5 +7,9 @@
"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"
"card.clicks": "squeaks",
"card.guest_name": "Guest #{code}",
"card.guest": "Guest squeak",
"about.yuzumi": "About Yuzumi",
"card.source": "Source: {s}"
}
+5 -1
View File
@@ -7,5 +7,9 @@
"share.text": "吱鼯計畫でチューチュー {n} 日目!今日はもうチューチューした?",
"share.title": "{name} のチューチューカード",
"share.open": "自分もチューチューする",
"card.clicks": "チューチュー回数"
"card.clicks": "チューチュー回数",
"card.guest_name": "ゲスト #{code}",
"card.guest": "ゲストチューチュー",
"about.yuzumi": "Yuzumi について",
"card.source": "出典:{s}"
}
+5 -1
View File
@@ -7,5 +7,9 @@
"share.text": "吱鼯計畫에서 찍찍 {n}일째! 오늘 찍찍 했어?",
"share.title": "{name}의 찍찍 카드",
"share.open": "나도 찍찍하기",
"card.clicks": "찍찍 횟수"
"card.clicks": "찍찍 횟수",
"card.guest_name": "게스트 #{code}",
"card.guest": "게스트 찍찍",
"about.yuzumi": "Yuzumi 소개",
"card.source": "출처: {s}"
}
+6 -2
View File
@@ -5,7 +5,11 @@
"card.streak": "连续 {n} 天",
"card.no_meme": "梗图准备中",
"share.text": "我在吱鼯計畫吱吱了 {n} 天,你今天吱吱了吗?",
"share.title": "{name} 的吱吱小卡",
"share.title": "{name} 的吱咪小卡",
"share.open": "我也要吱吱",
"card.clicks": "吱吱次数"
"card.clicks": "吱吱次数",
"card.guest_name": "访客 #{code}",
"card.guest": "访客吱吱",
"about.yuzumi": "关于Yuzumi",
"card.source": "来源:{s}"
}
+6 -2
View File
@@ -5,7 +5,11 @@
"card.streak": "連續 {n} 天",
"card.no_meme": "梗圖準備中",
"share.text": "我在吱鼯計畫吱吱了 {n} 天,你今天吱吱了嗎?",
"share.title": "{name} 的吱吱小卡",
"share.title": "{name} 的吱咪小卡",
"share.open": "我也要吱吱",
"card.clicks": "吱吱次數"
"card.clicks": "吱吱次數",
"card.guest_name": "訪客 #{code}",
"card.guest": "訪客吱吱",
"about.yuzumi": "關於Yuzumi",
"card.source": "來源:{s}"
}
+62
View File
@@ -0,0 +1,62 @@
"""讀使用者上傳的圖:限制格式、限制像素、同時只處理一張。"""
import io
import threading
import warnings
from contextlib import contextmanager
from fastapi import HTTPException
from PIL import Image, ImageOps
from . import config
from .deps import fail
# 只開這幾種。Pillow 還能讀 PSD、FITS、TIFF 等幾十種,漏洞多半出在那些格式
FORMATS = ("JPEG", "PNG", "WEBP", "GIF") # 讀圖庫裡已經有的圖(以前放進去的 GIF 照樣能畫第一格)
UPLOAD_FORMATS = ("JPEG", "PNG", "WEBP") # 使用者上傳:不收 GIF。動態的 WEBP / PNG 只取第一格
# 第二道保險:Pillow 自己在超過這個值的兩倍時會拒絕(例如檔頭和實際內容不一樣大)
Image.MAX_IMAGE_PIXELS = config.IMAGE_MAX_PIXELS // 2
warnings.simplefilter("ignore", Image.DecompressionBombWarning)
_slot = threading.Lock()
@contextmanager
def slot():
"""解碼很吃記憶體,全站同時只處理一張;等太久就請使用者稍後再試。"""
if not _slot.acquire(timeout=config.IMAGE_WAIT):
fail(429, "too_frequent")
try:
yield
finally:
_slot.release()
def load(path) -> Image.Image | None:
"""讀圖庫或大頭貼的檔案(不是使用者剛上傳的):保留透明度,回傳 RGBA。壞掉或不支援的格式回傳 None。"""
try:
with Image.open(path, formats=FORMATS) as im:
im.seek(0) # GIF 只取第一格
ImageOps.exif_transpose(im, in_place=True)
return im.convert("RGBA")
except Exception:
return None
def decode(data: bytes) -> tuple[Image.Image, bool]:
"""回傳 (RGB 或 RGBA 的圖, 有沒有透明度)。GIF 只取第一格;方向依 EXIF 轉正。"""
try:
if data[:6] in (b"GIF87a", b"GIF89a"):
fail(400, "unsupported_format")
with Image.open(io.BytesIO(data), formats=UPLOAD_FORMATS) as im:
if im.width * im.height > config.IMAGE_MAX_PIXELS: # 只讀了檔頭,還沒解碼
raise ValueError("too many pixels")
im.seek(0)
im.load()
ImageOps.exif_transpose(im, in_place=True)
alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info)
return im.convert("RGBA" if alpha else "RGB"), alpha
except HTTPException:
raise
except Exception:
fail(400, "invalid_image")
+107
View File
@@ -0,0 +1,107 @@
"""限流(放記憶體,只有一個 worker)、IP 分組、信箱格式、請求大小上限。"""
import ipaddress
import re
import threading
import time
from collections import deque
from fastapi import HTTPException
from starlette.responses import JSONResponse
from . import config
# 只收一個單純的 ASCII 地址。<[email protected]>、x,[email protected] 這類寫法會寄到同一個人,卻被當成不同信箱
EMAIL_RE = re.compile(
r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}"
r"@(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])")
def valid_email(email: str) -> bool:
return len(email) <= 254 and EMAIL_RE.fullmatch(email) is not None
def ip_key(ip: str) -> str:
"""限流用的 IP。IPv6 的使用者手上通常有一整段 /64 可以換,所以算同一個。"""
try:
addr = ipaddress.ip_address(ip.strip())
except ValueError:
return ip[:64]
if addr.version == 6:
if addr.ipv4_mapped:
return str(addr.ipv4_mapped)
return str(ipaddress.ip_network((int(addr), 64), strict=False))
return str(addr)
class Window:
"""同一個 key 在 window 秒內最多 limit 次。傳 config 的名稱,測試改值才會生效。"""
_all: list["Window"] = []
def __init__(self, limit: str, window: str):
self._limit, self._window = limit, window
self._hits: dict = {}
self._lock = threading.Lock()
Window._all.append(self)
def allow(self, key) -> bool:
now = time.monotonic()
with self._lock:
q = self._hits.setdefault(key, deque())
while q and q[0] < now - getattr(config, self._window):
q.popleft()
if len(q) >= getattr(config, self._limit):
return False
q.append(now)
return True
def clear(self) -> None:
with self._lock:
self._hits.clear()
def sweep(self) -> None:
"""丟掉已經過期的 key,不然來過的 IP 會一直佔著記憶體。"""
old = time.monotonic() - getattr(config, self._window)
with self._lock:
for key in [k for k, q in self._hits.items() if not q or q[-1] < old]:
del self._hits[key]
def sweep_all() -> None:
for w in Window._all:
w.sweep()
class BodyLimit:
"""擋太大的請求。沒有這個的話,還沒檢查登入就會先把整個請求收完。"""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
limit = config.UPLOAD_BODY_MAX if scope["path"] in config.UPLOAD_PATHS else config.BODY_MAX
too_big = JSONResponse({"detail": "file_too_large"}, status_code=413)
length = dict(scope["headers"]).get(b"content-length", b"")
if length.isdigit() and int(length[:20]) > limit:
return await too_big(scope, receive, send)
got, replaced = 0, False
async def limited(): # chunked 沒有 Content-Length,邊收邊算
nonlocal got
message = await receive()
if message["type"] == "http.request":
got += len(message.get("body", b""))
if got > limit:
raise HTTPException(413, "file_too_large")
return message
async def answer(message): # 裡面會把上面的例外變成 400,統一換成 413
nonlocal replaced
if got <= limit:
await send(message)
elif not replaced:
replaced = True
await too_big(scope, receive, send)
await self.app(scope, limited, answer)
+45 -8
View File
@@ -1,5 +1,7 @@
import asyncio
import hashlib
import mimetypes
import os
from contextlib import asynccontextmanager
from functools import lru_cache
@@ -7,7 +9,7 @@ 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
from . import __version__, anticheat, auth, card, checkin, config, db, limits, memes, notices, 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"),
@@ -18,15 +20,35 @@ CSP = ("default-src 'self'; img-src 'self' data: blob:; media-src 'self'; style-
"script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
def check_storage() -> None:
"""容器不是用 root 跑:資料夾的擁有者不對時,啟動就講清楚。"""
who = f"{os.geteuid()}:{os.getegid()}" if hasattr(os, "geteuid") else "?"
def bad(path):
return path.exists() and not os.access(path, os.R_OK | os.W_OK | (os.X_OK if path.is_dir() else 0))
data = config.DATA_DIR
paths = (data, *(data / n for n in ("zhiwu.db", "zhiwu.db-wal", "zhiwu.db-shm", "avatars", "cards", "submissions")))
for p in paths:
if bad(p):
raise RuntimeError(f"{p} 不能讀寫。目前用 UID:GID {who} 執行,請先 chown -R {who} 掛到 /data 的資料夾")
if bad(config.MEME_DIR):
print(f"[WARN] {config.MEME_DIR} 不能讀寫,圖庫或投稿會失敗。請 chown -R {who} 掛到 /memes 的資料夾", flush=True)
@asynccontextmanager
async def lifespan(app: FastAPI):
check_storage()
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)
await asyncio.to_thread(anticheat.check_safe)
task = asyncio.create_task(anticheat.loop())
yield
task.cancel()
app = FastAPI(title="吱鼯計畫", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
@@ -37,25 +59,39 @@ 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.scope["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)
try:
response = await call_next(request)
except Exception as e:
# 未處理的錯誤(500):記到管理員通知匣。只留路由和例外類型,不留參數內容
route = getattr(request.scope.get("route"), "path", "?")
await asyncio.to_thread(notices.add, "error", None, f"{request.method} {route}: {type(e).__name__}")
raise
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/"):
if request.scope["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.add_middleware(limits.BodyLimit) # 最後加的在最外層
for module in (auth, users, checkin, card, share, submissions, memes, notices):
app.include_router(module.router)
@app.exception_handler(OverflowError)
def too_big(request: Request, exc: OverflowError):
# UID 或編號超過 SQLite 整數範圍:一定不存在
return JSONResponse({"detail": "not_found"}, status_code=404)
@app.get("/healthz")
def healthz():
return {"status": "ok"}
@@ -75,8 +111,7 @@ def asset_version() -> str:
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 "")
html = html.replace("<!--APP_VERSION-->", __version__)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
@@ -88,5 +123,7 @@ def favicon():
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.add_api_route("/review", index, methods=["GET", "HEAD"], include_in_schema=False) # 1.0 的網址,前端會轉到 /images
app.add_api_route("/images", index, methods=["GET", "HEAD"], include_in_schema=False)
app.add_api_route("/notices", index, methods=["GET", "HEAD"], include_in_schema=False)
app.mount("/assets", StaticFiles(directory=config.WEB_DIR, check_dir=False), name="assets")
+235
View File
@@ -0,0 +1,235 @@
"""圖庫:抽卡用的圖、管理員管理圖片(新增、改出處、下架)。
- 圖檔在 MEME_DIR,檔名存進簽到紀錄,所以圖不刪只下架:不再被抽到,舊小卡照舊畫得出來
- memes 表只記有設定過出處或下架的圖;直接放進資料夾的圖照樣會被抽到
"""
import io
import os
import re
import sqlite3
import tempfile
import unicodedata
from pathlib import Path
from fastapi import APIRouter, Depends, File, Form, UploadFile
from fastapi.responses import FileResponse
from PIL import Image
from pydantic import BaseModel
from . import clock, config, db, images, limits
from .db import get_db, transaction
from .deps import admin_user, fail
router = APIRouter()
MEME_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
MEME_NAME = re.compile(r"^zhiwu_(\d+)\.[A-Za-z0-9]+$")
THUMB_SIZE = 320
# ---------- 圖庫清單 ----------
def all_files() -> 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 _hidden(conn: sqlite3.Connection) -> set[str]:
return {r[0] for r in conn.execute("SELECT name FROM memes WHERE hidden_at IS NOT NULL")}
def list_memes() -> list[str]:
"""會被抽到的圖(上架中)。"""
files = all_files()
if not files:
return []
conn = db.connect()
try:
hidden = _hidden(conn)
finally:
conn.close()
return [f for f in files if f not in hidden]
def source_of(name: str | None, conn: sqlite3.Connection | None = None) -> str:
if not name:
return ""
own = conn is None
conn = conn or db.connect()
try:
row = conn.execute("SELECT source FROM memes WHERE name = ?", (name,)).fetchone()
return row[0] if row else ""
finally:
if own:
conn.close()
def clean_source(text: str | None) -> str:
"""出處只當純文字顯示:去掉控制字元,最多 SOURCE_MAX 字。"""
text = "".join(ch for ch in (text or "") if unicodedata.category(ch) not in ("Cc", "Cf", "Cs")).strip()
if len(text) > config.SOURCE_MAX:
fail(400, "source_too_long")
return text
# ---------- 存圖 ----------
def process_meme(data: bytes) -> tuple[bytes, str]:
"""重新編碼成 JPEG(有透明度就用 PNG):去掉 EXIF(含 GPS)和偽裝成圖片的內容,GIF 只取第一格。"""
im, has_alpha = images.decode(data)
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.chmod(tmp, 0o644) # mkstemp 是 0600
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 store_meme(conn: sqlite3.Connection, data: bytes, ext: str, source: str) -> str:
"""存成 zhiwu_<下一號>.<ext> 並記下出處,回傳檔名。要在 transaction(conn) 裡呼叫,兩張同時存才不會拿到同一號。"""
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}.{ext}"
write_atomic(config.MEME_DIR / name, data)
if source:
set_meme(conn, name, source=source)
return name
def set_meme(conn: sqlite3.Connection, name: str, *, source: str | None = None, hidden: bool | None = None) -> None:
conn.execute("INSERT OR IGNORE INTO memes(name) VALUES (?)", (name,))
if source is not None:
conn.execute("UPDATE memes SET source = ? WHERE name = ?", (source, name))
if hidden is not None:
conn.execute("UPDATE memes SET hidden_at = ? WHERE name = ?", (clock.ts() if hidden else None, name))
def forget_cards(conn: sqlite3.Connection, name: str) -> None:
"""出處改了:用到這張圖的小卡快取都要重畫。"""
from .card import card_dir # card 也會用到這個模組,放這裡避免循環匯入
for uid, day in conn.execute("SELECT uid, day FROM checkins WHERE meme = ?", (name,)):
for p in card_dir(uid).glob(f"{day}.v*.png"):
p.unlink(missing_ok=True)
# ---------- 管理員 ----------
def _check_name(name: str) -> str:
"""只接受圖庫裡真的有的檔名,不拼使用者給的路徑。"""
if name not in all_files():
fail(404, "not_found")
return name
def _item(name: str, row: sqlite3.Row | None, used: int) -> dict:
mtime = int((config.MEME_DIR / name).stat().st_mtime)
return {
"name": name,
"source": row["source"] if row else "",
"hidden": bool(row and row["hidden_at"]),
"used": used,
"thumb_url": f"/api/admin/memes/{name}/thumb?v={mtime}",
}
def _one(conn: sqlite3.Connection, name: str) -> dict:
row = conn.execute("SELECT * FROM memes WHERE name = ?", (name,)).fetchone()
used = conn.execute("SELECT COUNT(*) FROM checkins WHERE meme = ?", (name,)).fetchone()[0]
return _item(name, row, used)
@router.get("/api/admin/memes")
def list_all(admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
rows = {r["name"]: r for r in conn.execute("SELECT * FROM memes")}
used = dict(conn.execute("SELECT meme, COUNT(*) FROM checkins WHERE meme IS NOT NULL GROUP BY meme").fetchall())
# 新的在前面:zhiwu_<n> 依編號,其他檔名排在後面
files = sorted(all_files(), key=lambda f: (-(int(m.group(1)) if (m := MEME_NAME.match(f)) else -1), f))
return {"items": [_item(f, rows.get(f), used.get(f, 0)) for f in files]}
_add_hits = limits.Window("ADMIN_ADD_LIMIT", "UPLOAD_WINDOW")
@router.post("/api/admin/memes")
def add(file: UploadFile = File(...), source: str = Form(""), admin=Depends(admin_user),
conn: sqlite3.Connection = Depends(get_db)):
"""管理員直接上架:和投稿一樣重新編碼,但不用審核。"""
source = clean_source(source)
if not _add_hits.allow(admin["uid"]):
fail(429, "too_frequent")
data = file.file.read(config.SUBMIT_MAX_BYTES + 1)
if len(data) > config.SUBMIT_MAX_BYTES:
fail(413, "file_too_large")
with images.slot():
body, ext = process_meme(data)
with transaction(conn):
name = store_meme(conn, body, ext, source)
print(f"[images] added {name}", flush=True)
return _one(conn, name)
class MemeIn(BaseModel):
source: str | None = None
hidden: bool | None = None
@router.put("/api/admin/memes/{name}")
def update(name: str, body: MemeIn, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
name = _check_name(name)
source = None if body.source is None else clean_source(body.source)
with transaction(conn):
old = source_of(name, conn)
set_meme(conn, name, source=source, hidden=body.hidden)
if source is not None and source != old:
forget_cards(conn, name)
if body.hidden is not None:
print(f"[images] {'hide' if body.hidden else 'show'} {name}", flush=True)
return _one(conn, name)
@router.get("/api/admin/memes/{name}/thumb")
def thumb(name: str, admin=Depends(admin_user)):
name = _check_name(name)
src = config.MEME_DIR / name
folder = config.DATA_DIR / "thumbs"
path = folder / f"{name}.webp"
if not path.exists() or path.stat().st_mtime < src.stat().st_mtime:
with images.slot():
im = images.load(src)
if im is None:
fail(404, "not_found")
im.thumbnail((THUMB_SIZE, THUMB_SIZE), Image.LANCZOS)
out = io.BytesIO()
im.save(out, "WEBP", quality=80)
folder.mkdir(parents=True, exist_ok=True)
write_atomic(path, out.getvalue())
return FileResponse(path, media_type="image/webp", headers={"Cache-Control": "private, max-age=86400"})
+81
View File
@@ -0,0 +1,81 @@
"""管理員通知匣:被標記的帳號、太頻繁、伺服器錯誤等重要訊息。
不記信箱、驗證碼、token。寫通知失敗只印 log,不影響原本的請求。
"""
import sqlite3
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, Query
from pydantic import BaseModel
from . import clock, config, db
from .db import get_db
from .deps import admin_user
from .titles import fmt_uid
router = APIRouter()
PAGE_SIZE = 50
def add(kind: str, uid: int | None = None, detail: str = "", merge: bool = True) -> None:
"""自己開一條連線;不要在交易裡呼叫(會等自己的寫入鎖)。merge=False = 每次都是新的一則。"""
try:
conn = db.connect()
try:
now = clock.ts()
with db.transaction(conn):
cur = conn.execute(
"UPDATE notices SET count = count + 1, updated_at = ?, read_at = NULL "
"WHERE kind = ? AND uid IS ? AND detail = ? AND updated_at > ?",
(now, kind, uid, detail, now - config.NOTICE_MERGE)) if merge else None
if cur is None or cur.rowcount == 0:
conn.execute(
"INSERT INTO notices(kind, uid, detail, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
(kind, uid, detail, now, now))
conn.execute(
"DELETE FROM notices WHERE id NOT IN "
"(SELECT id FROM notices ORDER BY updated_at DESC, id DESC LIMIT ?)", (config.NOTICE_KEEP,))
finally:
conn.close()
except Exception as e:
print(f"[notice] {kind} failed: {type(e).__name__}: {e}", flush=True)
def unread_count(conn: sqlite3.Connection) -> int:
return conn.execute("SELECT COUNT(*) FROM notices WHERE read_at IS NULL").fetchone()[0]
def iso(ts: int) -> str:
return datetime.fromtimestamp(ts, timezone.utc).isoformat()
@router.get("/api/admin/notices")
def list_notices(offset: int = Query(0, ge=0), admin=Depends(admin_user),
conn: sqlite3.Connection = Depends(get_db)):
rows = conn.execute(
"SELECT n.*, u.display_name FROM notices n LEFT JOIN users u ON u.uid = n.uid "
"ORDER BY n.updated_at DESC, n.id DESC LIMIT ? OFFSET ?", (PAGE_SIZE, offset)).fetchall()
total = conn.execute("SELECT COUNT(*) FROM notices").fetchone()[0]
return {
"items": [{
"id": r["id"], "kind": r["kind"], "detail": r["detail"], "count": r["count"],
"uid_str": None if r["uid"] is None else fmt_uid(r["uid"]), "display_name": r["display_name"],
"created_at": iso(r["created_at"]), "updated_at": iso(r["updated_at"]),
"unread": r["read_at"] is None,
} for r in rows],
"total": total,
"upto": max((r["updated_at"] for r in rows), default=0),
}
class ReadIn(BaseModel):
upto: int
@router.post("/api/admin/notices/read")
def mark_read(body: ReadIn, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
"""只標到畫面上最新的那一則為止,之後才進來的維持未讀。"""
conn.execute("UPDATE notices SET read_at = ? WHERE read_at IS NULL AND updated_at <= ?",
(clock.ts(), body.upto))
return {"unread": unread_count(conn)}
+10 -5
View File
@@ -5,7 +5,7 @@ from html import escape
from fastapi import APIRouter, Depends
from fastapi.responses import HTMLResponse
from . import config
from . import __version__, config
from .card import DAY_RE
from .checkin import stats
from .db import get_db
@@ -38,13 +38,16 @@ PAGE = """<!DOCTYPE html>
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; }}
a.open {{ background: #ff8a1f; color: #2a1400; padding: 12px 28px; border-radius: 999px;
text-decoration: none; font-weight: 700; }}
footer {{ font-size: 13px; color: #d9b993; text-align: center; line-height: 1.7; }}
footer a {{ color: #ff8a1f; }}
</style>
</head>
<body>
<img src="{image_path}" alt="{title}">
<a href="/">{open}</a>
<a class="open" href="/">{open}</a>
<footer>{about}<br><a href="https://official-website.meridianproject.tw/talents/yuzumi" target="_blank" rel="noopener noreferrer">official-website.meridianproject.tw/talents/yuzumi</a><br>v{version}</footer>
</body>
</html>"""
@@ -63,11 +66,13 @@ def share_page(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
image_path = f"/card/{fmt_uid(uid)}/{day}.png?c={user['clicks']}"
return PAGE.format(
lang=lang,
site="吱鼯計畫 (Beta)" if config.BETA else "吱鼯計畫",
site="吱鼯計畫",
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")),
about=escape(t(lang, "about.yuzumi")),
version=__version__,
)
+28 -71
View File
@@ -1,30 +1,25 @@
"""使用者投稿迷因圖,管理員審核。
流程:使用者上傳 → 重新編碼後存在 DATA_DIR/submissions/<id>.<ext>(pending)
→ 管理員同意:依 image/ 的命名規則存成 MEME_DIR/zhiwu_<下一號>.<ext>,之後的小卡就可能抽到
→ 管理員同意:依 image/ 的命名規則存成 MEME_DIR/zhiwu_<下一號>.<ext>(memes.store_meme),之後的小卡就可能抽到
→ 管理員拒絕:刪掉檔案,紀錄保留(每日額度要算)
"""
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 import APIRouter, Depends, File, Form, UploadFile
from fastapi.responses import FileResponse
from PIL import Image, ImageOps
from pydantic import BaseModel
from . import clock, config
from . import clock, config, images, limits
from .memes import clean_source, process_meme, store_meme, write_atomic
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"}
@@ -37,45 +32,6 @@ 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
@@ -95,7 +51,7 @@ def quota(conn: sqlite3.Connection, uid: int) -> dict:
def item(row: sqlite3.Row) -> dict:
return {"id": row["id"], "status": row["status"], "created_at": iso(row["created_at"]),
"image_url": image_url(row)}
"image_url": image_url(row), "source": row["source"]}
def pending_count(conn: sqlite3.Connection) -> int:
@@ -104,20 +60,28 @@ def pending_count(conn: sqlite3.Connection) -> int:
# ---------- 使用者 ----------
_upload_hits = limits.Window("SUBMIT_LIMIT", "UPLOAD_WINDOW")
@router.post("/api/submissions")
def upload(file: UploadFile = File(...), user=Depends(current_user), conn: sqlite3.Connection = Depends(get_db)):
def upload(file: UploadFile = File(...), source: str = Form(""), user=Depends(current_user),
conn: sqlite3.Connection = Depends(get_db)):
source = clean_source(source)
if not _upload_hits.allow(user["uid"]):
fail(429, "too_frequent")
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) # 先處理圖片,不佔用寫入鎖
with images.slot():
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()))
cur = conn.execute("INSERT INTO submissions(uid, day, ext, source, created_at) VALUES (?, ?, ?, ?, ?)",
(user["uid"], day, ext, source, 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"])}
@@ -178,29 +142,22 @@ def _load_pending(conn: sqlite3.Connection, sid: int) -> sqlite3.Row:
return row
class ApproveIn(BaseModel):
source: str | None = None # 沒給 = 用投稿者填的
@router.post("/api/admin/submissions/{sid}/approve")
def approve(sid: int, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
def approve(sid: int, body: ApproveIn | None = None, 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))
source = clean_source(row["source"] if body is None or body.source is None else body.source)
name = store_meme(conn, src.read_bytes(), row["ext"], source)
conn.execute("UPDATE submissions SET status = 'approved', meme = ?, source = ?, reviewed_at = ? WHERE id = ?",
(name, source, 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)}
+5 -4
View File
@@ -1,5 +1,6 @@
"""UID 的底色與稱號。
- 一般使用者:淺咖啡底
- 管理員(UID 0)預設黃底
- 管理員可以幫任何 UID 指定一個顏色和一個稱號(users.title / users.title_color),會蓋過預設
都只是顯示用,不帶任何權限。顯示的地方:側欄、個人頁、審核頁、小卡。
@@ -11,6 +12,7 @@ from . import config
# 預設的特殊序號:底色、文字色(網頁的 web/style.css .uid.tier-* 用同樣的顏色)
TIER_COLORS = {
"default": ((201, 162, 122), (42, 20, 0)), # 淺咖啡 #C9A27A:所有 UID 的預設底色
"admin": ((255, 209, 102), (42, 20, 0)), # 黃 #FFD166
}
DEFAULT_TITLE_COLOR = "#ff8a1f" # 只給稱號沒給顏色時用主色
@@ -49,10 +51,9 @@ def badge(user: sqlite3.Row) -> dict:
}
def badge_colors(user: sqlite3.Row) -> tuple[tuple, tuple] | None:
"""小卡用:(底色, 文字色);沒有特殊樣式回 None。指定的顏色優先於預設。"""
def badge_colors(user: sqlite3.Row) -> tuple[tuple, tuple]:
"""小卡用:(底色, 文字色)。管理員指定的顏色 > 管理員預設黃 > 一般使用者淺咖啡。"""
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
return TIER_COLORS[uid_tier(user["uid"]) or "default"]
+1 -1
View File
@@ -23,7 +23,7 @@ def code_at(key: bytes, step: int) -> str:
def verify(secret: str, code: str, unix_time: int, window: int = 1) -> int | None:
"""比對前後各 window 個時間窗(容忍手機時鐘誤差),成功回傳符合的時間步。"""
if len(code) != DIGITS or not code.isdigit():
if len(code) != DIGITS or not code.isascii() or not code.isdigit():
return None
key = decode_secret(secret)
current = unix_time // PERIOD
+28 -14
View File
@@ -11,10 +11,10 @@ from markdown_it import MarkdownIt
from PIL import Image, ImageOps
from pydantic import BaseModel
from . import card, clock, config
from . import card, clock, config, images, limits, notices
from .checkin import stats
from .db import get_db, transaction
from .deps import admin_user, current_user, fail
from .deps import admin_user, current_user, fail, optional_user
from .i18n import norm_lang
from .titles import DEFAULT_TITLE_COLOR, badge, fmt_uid, valid_color
@@ -89,6 +89,7 @@ def profile(conn: sqlite3.Connection, user: sqlite3.Row, lang: str, private: boo
if out["is_admin"]:
out["pending_reviews"] = conn.execute(
"SELECT COUNT(*) FROM submissions WHERE status = 'pending'").fetchone()[0]
out["unread_notices"] = notices.unread_count(conn)
return out
@@ -138,15 +139,7 @@ def patch_me(body: ProfilePatch, user=Depends(current_user), conn: sqlite3.Conne
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")
im, _ = images.decode(data)
size = config.AVATAR_SIZE
im = ImageOps.fit(im, (size, size), Image.LANCZOS)
out = io.BytesIO()
@@ -154,13 +147,19 @@ def process_avatar(data: bytes) -> bytes:
return out.getvalue()
_avatar_hits = limits.Window("AVATAR_LIMIT", "UPLOAD_WINDOW")
@router.put("/api/me/avatar")
def put_avatar(file: UploadFile = File(...), user=Depends(current_user),
conn: sqlite3.Connection = Depends(get_db)):
if not _avatar_hits.allow(user["uid"]):
fail(429, "too_frequent")
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)
with images.slot():
webp = process_avatar(data)
folder = config.DATA_DIR / "avatars"
folder.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
@@ -175,6 +174,8 @@ def put_avatar(file: UploadFile = File(...), user=Depends(current_user),
@router.get("/avatars/{uid}.webp")
def get_avatar(uid: int):
if not 0 <= uid <= config.UID_MAX:
fail(404, "not_found")
path = config.DATA_DIR / "avatars" / f"{uid}.webp"
if not path.exists():
fail(404, "not_found")
@@ -184,11 +185,24 @@ def get_avatar(uid: int):
# ---------- 公開資料 ----------
@router.get("/api/users/{uid}")
def get_user(uid: int, lang: str = Query(config.DEFAULT_LANG), conn: sqlite3.Connection = Depends(get_db)):
def get_user(uid: int, lang: str = Query(config.DEFAULT_LANG), viewer=Depends(optional_user),
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)
out = profile(conn, user, lang)
if viewer is not None and viewer["uid"] == config.ADMIN_UID:
out["flagged"] = user["flagged_at"] is not None # 只有管理員看得到
return out
@router.delete("/api/admin/users/{uid}/flag")
def clear_flag(uid: int, admin=Depends(admin_user), conn: sqlite3.Connection = Depends(get_db)):
"""解除標記。次數仍超過上限的話,下次檢查會再標記。"""
if conn.execute("UPDATE users SET flagged_at = NULL WHERE uid = ?", (uid,)).rowcount == 0:
fail(404, "user_not_found")
print(f"[ADMIN] unflag uid={fmt_uid(uid)}", flush=True)
return {"status": "ok"}
# ---------- 管理員:指定 UID 的顏色與稱號 ----------
+2 -2
View File
@@ -1,3 +1,3 @@
-r requirements.txt
pytest==8.*
httpx
pytest==9.2.0
httpx==0.28.1
+7 -6
View File
@@ -1,6 +1,7 @@
fastapi==0.115.*
uvicorn[standard]==0.32.*
pillow==11.*
python-multipart==0.0.*
markdown-it-py==3.*
tzdata
fastapi==0.165.0
starlette==1.10.0
uvicorn[standard]==0.54.0
pillow==13.0.0
python-multipart==0.0.34
markdown-it-py==4.3.0
tzdata==2026.6
+17 -3
View File
@@ -4,9 +4,9 @@ import pytest
from fastapi.testclient import TestClient
from PIL import Image
from app import auth, clock, config, mailer, totp
from app import auth, checkin, clock, config, db, limits, mailer, totp
ADMIN_LOGIN = "sthkm3"
ADMIN_LOGIN = "[email protected]"
ADMIN_TOTP = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" # 測試用密鑰
@@ -45,7 +45,10 @@ def client(tmp_path, monkeypatch, fake_clock, sent):
monkeypatch.setattr(config, "MEME_DIR", memes)
monkeypatch.setattr(config, "ADMIN_LOGIN", ADMIN_LOGIN)
monkeypatch.setattr(config, "ADMIN_TOTP", ADMIN_TOTP)
auth._ip_hits.clear()
for w in limits.Window._all:
w.clear()
for d in (checkin._next, checkin._rejects, checkin._cool):
d.clear()
from app.main import app
with TestClient(app, headers={"X-ZHIWU": "1"}) as c:
yield c
@@ -59,6 +62,17 @@ def login(client, sent, email="[email protected]", lang="zh-TW"):
return r.json()
def admin_verify(client, code, email=ADMIN_LOGIN, headers=None):
"""管理員登入:和一般人一樣要先要驗證碼(這裡略過 60 秒限制),再輸入 TOTP。"""
conn = db.connect()
conn.execute("DELETE FROM login_codes WHERE email = ?", (email,))
conn.close()
auth._ip_mail.clear()
r = client.post("/api/auth/request-code", json={"email": email})
assert r.status_code == 200, r.text
return client.post("/api/auth/verify", json={"email": email, "code": code}, headers=headers)
def admin_code(fake_clock, offset_steps=0):
"""用假時鐘算出管理員的 TOTP。"""
step = int(fake_clock.value.timestamp()) // totp.PERIOD + offset_steps
+14 -15
View File
@@ -4,11 +4,11 @@ import pytest
from app import admin, config, db, totp
from .conftest import ADMIN_LOGIN, admin_code, login
from .conftest import ADMIN_LOGIN, admin_code, admin_verify, login
def admin_login(client, code, login_name=ADMIN_LOGIN):
return client.post("/api/auth/verify", json={"email": login_name, "code": code})
return admin_verify(client, code, login_name)
def test_totp_rfc6238_vector():
@@ -23,7 +23,7 @@ def test_totp_rfc6238_vector():
def test_admin_request_code_does_not_send(client, sent):
r = client.post("/api/auth/request-code", json={"email": "STHKM3"})
r = client.post("/api/auth/request-code", json={"email": ADMIN_LOGIN.upper()})
assert r.status_code == 200 and r.json()["status"] == "sent"
assert sent == {}
@@ -64,10 +64,10 @@ def test_admin_lockout(client, 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, wrong).json()["detail"] == "wrong_code"
assert db.get_meta(db.connect(), "admin_lock_level") == 1 # 第 3 次就鎖,但回應看不出來
# 鎖定中,正確的碼也不行
assert admin_login(client, good).status_code == 429
assert admin_login(client, good).json()["detail"] == "wrong_code"
# 15 分鐘後解鎖
fake_clock.value += timedelta(minutes=15)
@@ -79,7 +79,7 @@ def test_admin_lock_doubles(client, fake_clock):
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
assert admin_login(client, admin_code(fake_clock)).status_code == 400
fake_clock.value += timedelta(seconds=1)
conn = db.connect()
assert db.get_meta(conn, "admin_lock_level") == 3
@@ -88,7 +88,7 @@ def test_admin_lock_doubles(client, fake_clock):
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
assert admin_login(client, admin_code(fake_clock)).status_code == 400
admin.main(["unlock"])
assert admin_login(client, admin_code(fake_clock)).status_code == 200
@@ -96,16 +96,15 @@ def test_admin_unlock_command(client, fake_clock):
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"
assert admin_login(client, admin_code(fake_clock)).json()["detail"] == "wrong_code"
assert sent == {}
def test_admin_login_renamed(client, fake_clock, monkeypatch):
monkeypatch.setattr(config, "ADMIN_LOGIN", "boss")
monkeypatch.setattr(config, "ADMIN_LOGIN", "[email protected]")
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 admin_login(client, admin_code(fake_clock)).json()["detail"] == "wrong_code" # 舊的變成一般信箱
r = admin_login(client, admin_code(fake_clock), "[email protected]")
assert r.status_code == 200 and r.json()["user"]["uid"] == 0
@@ -119,7 +118,7 @@ def test_admin_login_clash_disables(client, sent, fake_clock, monkeypatch):
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=")
assert last.startswith("otpauth://totp/%E5%90%B1%E9%BC%AF%E8%A8%88%E7%95%AB%3Aboss-7f3a%40admin.invalid?secret=")
@pytest.mark.parametrize("uid", ["0", "-1"])
+206
View File
@@ -0,0 +1,206 @@
"""1.0.2:1.5 秒限制、冷靜時間、理論上限標記、管理員通知匣、版本顯示。"""
import os
import sqlite3
from concurrent.futures import ThreadPoolExecutor
import pytest
from app import __version__, anticheat, card, checkin, config, db, mailer, notices, users
from .conftest import admin_code, admin_verify, login
from .test_zhi import frozen # noqa: F401 (fixture)
def as_admin(client, fake_clock):
client.cookies.clear()
r = admin_verify(client, admin_code(fake_clock))
assert r.status_code == 200, r.text
forget_login()
def zhi(client):
return client.post("/api/zhi", json={"n": 1})
def forget_login():
"""管理員登入本身也會發一則通知,測其他通知時先拿掉。"""
conn = db.connect()
conn.execute("DELETE FROM notices WHERE kind = 'admin_login'")
conn.close()
# ---------- 冷靜時間 ----------
def test_cooldown_after_too_many_rejects(client, sent, frozen, fake_clock): # noqa: F811
login(client, sent)
assert zhi(client).json()["added"] == 1
for _ in range(config.COOL_REJECTS - 1):
assert zhi(client).json()["added"] == 0
r = zhi(client)
assert r.status_code == 429 and r.json()["detail"] == "cooldown"
frozen[0] += config.COOL_SECONDS - 0.1 # 冷靜期間怎麼送都不算,也不會延長
assert zhi(client).status_code == 429
frozen[0] += 0.2
assert zhi(client).json() == {"clicks": 2, "added": 1}
as_admin(client, fake_clock)
items = client.get("/api/admin/notices").json()["items"]
assert [(n["kind"], n["uid_str"], n["count"]) for n in items] == [("cooldown", "00000001", 1)]
def test_normal_pace_never_cools_down(client, sent, frozen): # noqa: F811
login(client, sent)
for i in range(60):
frozen[0] += 1.6 + (0.25 if i % 2 else -0.25) # 網路抖動:一下慢一下快
assert zhi(client).json()["added"] == 1
# ---------- 理論上限 ----------
def set_clicks(uid, n):
conn = db.connect()
conn.execute("UPDATE users SET clicks = ? WHERE uid = ?", (n, uid))
conn.close()
def test_flag_over_limit(client, sent, fake_clock):
login(client, sent)
fake_clock.set("2026-11-21T12:00:00+08:00") # 架設後 1 小時:上限 2400
set_clicks(1, 2400)
set_clicks(0, 999999) # 管理員不檢查
assert anticheat.check() == []
set_clicks(1, 2401)
assert anticheat.check() == [1]
assert anticheat.check() == [] # 已標記的不重複通知
assert "flagged" not in client.get("/api/users/1").json() # 本人和其他人看不到
assert "flagged_at" not in client.get("/api/me").json()
assert client.delete("/api/admin/users/1/flag").status_code == 403
as_admin(client, fake_clock)
assert client.get("/api/users/1").json()["flagged"] is True
assert client.get("/api/me").json()["unread_notices"] == 1
r = client.get("/api/admin/notices").json()
assert r["items"][0]["kind"] == "flagged" and r["items"][0]["detail"] == "2,401 > 2,400"
assert client.delete("/api/admin/users/1/flag").status_code == 200
assert client.get("/api/users/1").json()["flagged"] is False
assert client.delete("/api/admin/users/99/flag").status_code == 404
assert anticheat.check() == [1] # 仍超過就再標記
def test_upgrade_from_101(tmp_path, monkeypatch):
"""1.0.1 的資料庫:補欄位與表,最初架設時間用最早的帳號。"""
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
monkeypatch.setattr(config, "ADMIN_LOGIN", "")
conn = sqlite3.connect(tmp_path / "zhiwu.db")
conn.execute("CREATE TABLE 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 '', created_at INTEGER NOT NULL)")
for uid, at in ((1, 2000), (2, 1000)):
conn.execute("INSERT INTO users(uid, email, display_name, lang, clicks, created_at) VALUES (?, ?, 'x', 'en', 7, ?)",
(uid, f"{uid}@example.com", at))
conn.commit()
conn.close()
db.init()
db.init() # 再啟動一次也不會變
conn = db.connect()
assert db.get_meta(conn, "server_start") == 1000
row = conn.execute("SELECT clicks, flagged_at FROM users WHERE uid = 1").fetchone()
assert row["clicks"] == 7 and row["flagged_at"] is None
assert conn.execute("SELECT COUNT(*) FROM notices").fetchone()[0] == 0
conn.close()
# ---------- 通知匣 ----------
def test_notices_admin_only(client, sent):
assert client.get("/api/admin/notices").status_code == 401
login(client, sent)
assert client.get("/api/admin/notices").status_code == 403
assert client.post("/api/admin/notices/read", json={"upto": 1}).status_code == 403
assert "unread_notices" not in client.get("/api/me").json()
def test_notices_merge_read_and_keep(client, sent, fake_clock, monkeypatch):
as_admin(client, fake_clock)
notices.add("error", None, "a")
notices.add("error", None, "a")
notices.add("error", None, "b")
r = client.get("/api/admin/notices").json()
assert [(n["detail"], n["count"]) for n in r["items"]] == [("b", 1), ("a", 2)]
assert client.post("/api/admin/notices/read", json={"upto": r["upto"]}).json() == {"unread": 0}
fake_clock.set("2026-11-21T11:30:00+08:00")
notices.add("error", None, "a") # 一小時內:併進去,變回未讀
assert client.get("/api/me").json()["unread_notices"] == 1
assert client.post("/api/admin/notices/read", json={"upto": r["upto"]}).json() == {"unread": 1} # 之後才進來的不算看過
fake_clock.set("2026-11-21T13:00:00+08:00")
notices.add("error", None, "a") # 超過一小時:新的一則
assert client.get("/api/admin/notices").json()["total"] == 3
monkeypatch.setattr(config, "NOTICE_KEEP", 2)
notices.add("error", None, "c")
r = client.get("/api/admin/notices").json()
assert r["total"] == 2 and r["items"][0]["detail"] == "c"
assert client.get("/api/admin/notices?offset=1").json()["items"][0]["detail"] == "a"
def test_notice_failure_is_swallowed(monkeypatch):
def boom():
raise sqlite3.OperationalError("locked")
monkeypatch.setattr(db, "connect", boom)
notices.add("error")
def test_error_mail_and_lock_notices(client, sent, fake_clock, monkeypatch):
def boom(*a, **k):
raise RuntimeError("secret [email protected]")
monkeypatch.setattr(mailer, "send_code", boom)
assert client.post("/api/auth/request-code", json={"email": "[email protected]"}).status_code == 502
for _ in range(config.ADMIN_MAX_FAILS):
admin_verify(client, "abc")
monkeypatch.setattr(users, "render_md", boom)
with pytest.raises(RuntimeError):
client.get("/api/users/0")
conn = db.connect()
rows = [(r["kind"], r["detail"]) for r in conn.execute("SELECT * FROM notices ORDER BY id")]
conn.close()
assert rows == [("mail_failed", "RuntimeError"), ("admin_locked", "15 min"),
("error", "GET /api/users/{uid}: RuntimeError")]
# ---------- 其他 ----------
def test_version_shown(client, sent):
for path in ("/", "/notices"):
html = client.get(path).text
assert f"v{__version__}</span>" in html and "<!--" + "APP_VERSION" not in html
login(client, sent)
r = client.post("/api/checkin").json()
assert f"v{__version__}</footer>" in client.get(f"/c/1/{r['day']}").text
@pytest.mark.parametrize("path", [
f"/api/users/{10**30}", f"/c/{10**30}/2026-11-21", f"/card/{10**30}/2026-11-21.png",
f"/avatars/{10**30}.webp", f"/avatars/{'9' * 400}.webp", f"/card/guest.png?code=AB12&n={'9' * 5000}",
])
def test_huge_numbers_are_404(client, path):
assert client.get(path).status_code == 404
@pytest.mark.skipif(os.name == "nt", reason="Windows 沒有 POSIX 權限")
def test_approved_meme_is_world_readable(client, sent, fake_clock):
from .test_submissions import _img
login(client, sent)
sid = client.post("/api/submissions", files={"file": ("a.png", _img(), "image/png")}).json()["item"]["id"]
as_admin(client, fake_clock)
name = client.post(f"/api/admin/submissions/{sid}/approve").json()["meme"]
assert (config.MEME_DIR / name).stat().st_mode & 0o777 == 0o644
def test_parallel_requests_count_once(frozen): # noqa: F811
with ThreadPoolExecutor(16) as ex:
results = [r for r, _ in ex.map(lambda _: checkin._take(1), range(64))]
assert results.count("ok") == 1
def test_no_beta_left(client):
assert not hasattr(config, "BETA") and "beta" not in client.get("/").text.lower()
assert card.CARD_VERSION == 3
+143
View File
@@ -0,0 +1,143 @@
"""訪客吱吱:伺服器不記任何訪客資料,小卡照網址上的代號和次數即時畫。另外:每個 UID 都有底色、頁尾連結。"""
import io
import pytest
from PIL import Image
from app import card, config, db
from app.titles import TIER_COLORS, badge_colors
from .conftest import login
YUZUMI = "official-website.meridianproject.tw/talents/yuzumi"
@pytest.fixture(autouse=True)
def fresh_guest_state():
card._guest_hits.clear()
card._guest_cache.clear()
def test_guest_card_renders_without_login(client):
r = client.get("/card/guest.png", params={"code": "AB12", "n": 67})
assert r.status_code == 200 and r.headers["content-type"] == "image/png"
assert r.headers["cache-control"] == "private, max-age=60"
assert Image.open(io.BytesIO(r.content)).size == (1080, 1350)
# 次數不同、代號不同、語言不同,畫出來都不一樣
assert client.get("/card/guest.png", params={"code": "AB12", "n": 68}).content != r.content
assert client.get("/card/guest.png", params={"code": "CD34", "n": 67}).content != r.content
assert client.get("/card/guest.png", params={"code": "AB12", "n": 67, "lang": "en"}).content != r.content
# 同樣的參數是同一張(從快取拿)
assert client.get("/card/guest.png", params={"code": "AB12", "n": 67}).content == r.content
def test_guest_leaves_nothing_on_server(client):
conn = db.connect()
counts = lambda: [conn.execute(f"SELECT COUNT(*) FROM {tbl}").fetchone()[0]
for tbl in ("users", "sessions", "checkins", "login_codes")]
before = counts()
assert client.get("/card/guest.png", params={"code": "AB12", "n": 5}).status_code == 200
assert counts() == before
assert not any((config.DATA_DIR / "cards").iterdir()) # 也不寫硬碟
assert "set-cookie" not in client.get("/card/guest.png", params={"code": "AB12", "n": 5}).headers
@pytest.mark.parametrize("params", [
{}, {"code": "ab12"}, {"code": "ABC"}, {"code": "ABCDE"}, {"code": "AB-2"}, {"code": "../x"},
{"code": "AB12", "n": "-1"}, {"code": "AB12", "n": "abc"}, {"code": "AB12", "n": "1.5"},
{"code": "AB12", "n": str(config.GUEST_CLICKS_MAX + 1)}, {"code": "AB12", "n": "9"},
])
def test_guest_card_rejects_bad_params(client, params):
assert client.get("/card/guest.png", params=params).status_code == 404
def test_guest_card_unknown_lang_falls_back(client):
a = client.get("/card/guest.png", params={"code": "AB12", "n": 1, "lang": "xx"})
b = client.get("/card/guest.png", params={"code": "AB12", "n": 1, "lang": "zh-TW"})
assert a.status_code == 200 and a.content == b.content
def test_guest_meme_is_stable_per_day(client, fake_clock):
for i in range(6):
Image.new("RGB", (64, 64), (i * 40, 80, 80)).save(config.MEME_DIR / f"m{i}.png")
day = "2026-11-21"
assert card.guest_meme("AB12", day) == card.guest_meme("AB12", day)
picks = {card.guest_meme(code, day) for code in ("AB12", "CD34", "EF56", "GH78", "JK90", "LM23", "NP45", "QR67")}
assert len(picks) > 1 # 不同訪客會抽到不同的圖
assert len({card.guest_meme("AB12", f"2026-11-{d:02d}") for d in range(1, 29)}) > 1 # 換日會換圖
def test_guest_card_rate_limited_per_ip(client, monkeypatch):
monkeypatch.setattr(config, "GUEST_CARD_LIMIT", 3)
for n in range(3):
assert client.get("/card/guest.png", params={"code": "AB12", "n": n}).status_code == 200
r = client.get("/card/guest.png", params={"code": "AB12", "n": 99})
assert r.status_code == 429 and r.json()["detail"] == "too_many_requests"
# 已經畫過的從快取拿,不算次數
assert client.get("/card/guest.png", params={"code": "AB12", "n": 0}).status_code == 200
# 別的 IP 不受影響
other = client.get("/card/guest.png", params={"code": "AB12", "n": 99}, headers={"CF-Connecting-IP": "203.0.113.9"})
assert other.status_code == 200
def test_guest_cache_is_bounded(client, monkeypatch):
monkeypatch.setattr(config, "GUEST_CARD_CACHE", 2)
for n in range(4):
client.get("/card/guest.png", params={"code": "AB12", "n": n})
assert len(card._guest_cache) == 2
def test_guest_route_does_not_shadow_user_cards(client, sent):
login(client, sent)
r = client.post("/api/checkin").json()
assert client.get(r["card_url"]).status_code == 200
assert client.get("/card/guest/2026-11-21.png").status_code == 422 # uid 必須是數字
def test_every_uid_has_a_background(client, sent):
u = login(client, sent)["user"]
assert u["uid_tier"] is None and u["title_color"] is None # API 不變:前端自己套預設底色
conn = db.connect()
conn.row_factory = db.sqlite3.Row
row = conn.execute("SELECT * FROM users WHERE uid = 1").fetchone()
assert badge_colors(row) == TIER_COLORS["default"] == ((201, 162, 122), (42, 20, 0))
admin = conn.execute("SELECT * FROM users WHERE uid = 0").fetchone()
assert badge_colors(admin) == TIER_COLORS["admin"]
conn.execute("UPDATE users SET title_color = '#000000' WHERE uid = 1")
row = conn.execute("SELECT * FROM users WHERE uid = 1").fetchone()
assert badge_colors(row) == ((0, 0, 0), (255, 255, 255)) # 指定的顏色優先
css = client.get("/assets/style.css").text
assert "#c9a27a" in css
def test_footer_links_to_yuzumi(client, sent):
for path in ("/", "/upload", "/u/00000001"):
html = client.get(path).text
assert f'href="https://{YUZUMI}"' in html and 'class="site-footer"' in html
login(client, sent)
r = client.post("/api/checkin").json()
share = client.get(f"/c/00000001/{r['day']}").text
assert f'href="https://{YUZUMI}"' in share and "關於Yuzumi" in share
def test_new_copy(client):
zh = client.get("/assets/i18n/zh-TW.json").json()
assert zh["checkin.login_first"] == "不是老鼠,是鼯鼠。每天吱吱後領一張吱咪小卡。"
assert zh["guest.button"] == "訪客吱吱" and zh["about.yuzumi"] == "關於Yuzumi"
for lang in config.LANGS: # 每個語系都要有新加的字
d = client.get(f"/assets/i18n/{lang}.json").json()
assert set(zh) == set(d), (lang, set(zh) ^ set(d))
def test_uid_search_and_oss_links(client):
html = client.get("/").text
assert 'id="uid-input"' in html
start = html.index('id="uid-search"')
assert start < html.index('id="menu-toggle"') # 在 ☰ 左邊
form = html[start:html.index("</form>", start)]
assert "<button" not in form # 只有輸入框,按 Enter 送出
assert 'href="https://github.com/Sthkm3/ZhiwuProject"' in html
assert 'href="https://gitea.sthkm3.org/sthkm3/ZhiwuProject"' in html
zh = client.get("/assets/i18n/zh-TW.json").json()
assert zh["oss.label"] == "開源連結" and "search.go" not in zh
assert client.get("/u/00000001").status_code == 200
+250
View File
@@ -0,0 +1,250 @@
"""1.1.0:管理圖片(新增、出處、下架)、小卡上的出處、透明圖、個人頁編輯按鈕。"""
import io
import sqlite3
import pytest
from PIL import Image
from app import card, checkin, config, db, memes
from .conftest import admin_code, admin_verify, login
from .test_submissions import _img, bearer, upload
@pytest.fixture
def adm(client, fake_clock):
r = admin_verify(client, admin_code(fake_clock))
assert r.status_code == 200
client.cookies.clear()
return bearer(r.json()["token"])
def png(color=(200, 80, 80, 255), size=(64, 48)):
buf = io.BytesIO()
Image.new("RGBA", size, color).save(buf, "PNG")
return buf.getvalue()
def add(client, adm, data=None, source=""):
return client.post("/api/admin/memes", headers=adm, data={"source": source},
files={"file": ("a.png", data or _img(), "image/png")})
def put(client, adm, name, **body):
return client.put(f"/api/admin/memes/{name}", headers=adm, json=body)
def card_png(client, url):
r = client.get(url)
assert r.status_code == 200
return Image.open(io.BytesIO(r.content)).convert("RGB")
# ---------- 新增 ----------
def test_add_publishes_right_away(client, adm):
r = add(client, adm, source=" x@sthkm3 ")
assert r.status_code == 200, r.text
m = r.json()
assert m["name"] == "zhiwu_0.jpg" and m["source"] == "x@sthkm3" and m["hidden"] is False and m["used"] == 0
assert "zhiwu_0.jpg" in checkin.list_memes()
assert add(client, adm).json()["name"] == "zhiwu_1.jpg" # 取號不重複
assert add(client, adm, png((0, 0, 0, 0))).json()["name"] == "zhiwu_2.png" # 透明的存成 PNG
with Image.open(config.MEME_DIR / "zhiwu_0.jpg") as im:
assert len(im.getexif()) == 0
def test_add_validation_and_limits(client, adm, monkeypatch):
assert add(client, adm, b"not an image").json()["detail"] == "invalid_image"
assert add(client, adm, source="x" * 41).json()["detail"] == "source_too_long"
assert add(client, adm, b"\0" * (config.SUBMIT_MAX_BYTES + 1)).status_code == 413
monkeypatch.setattr(config, "ADMIN_ADD_LIMIT", 2)
from app import limits
for w in limits.Window._all:
w.clear()
assert [add(client, adm).status_code for _ in range(3)] == [200, 200, 429]
def test_admin_only(client, sent):
tok = bearer(login(client, sent)["token"])
client.cookies.clear()
for method, path, kw in (("get", "/api/admin/memes", {}), ("put", "/api/admin/memes/test.png", {"json": {}}),
("get", "/api/admin/memes/test.png/thumb", {}),
("post", "/api/admin/memes", {"files": {"file": ("a.png", _img(), "image/png")}})):
assert getattr(client, method)(path, headers=tok, **kw).status_code == 403
assert getattr(client, method)(path, **kw).status_code == 401
# ---------- 清單、下架、出處 ----------
def test_list_newest_first(client, adm):
for _ in range(3):
add(client, adm)
names = [m["name"] for m in client.get("/api/admin/memes", headers=adm).json()["items"]]
assert names == ["zhiwu_2.jpg", "zhiwu_1.jpg", "zhiwu_0.jpg", "test.png"]
def test_hidden_is_never_drawn(client, sent, adm, monkeypatch):
add(client, adm)
assert put(client, adm, "test.png", hidden=True).json()["hidden"] is True
assert checkin.list_memes() == ["zhiwu_0.jpg"]
assert all(checkin.pick_meme() == "zhiwu_0.jpg" for _ in range(20))
assert {card.guest_meme(c, "2026-11-21") for c in ("AB12", "CD34", "EF56", "GH78")} == {"zhiwu_0.jpg"}
put(client, adm, "zhiwu_0.jpg", hidden=True)
assert checkin.list_memes() == [] and checkin.pick_meme() is None
assert put(client, adm, "test.png", hidden=False).json()["hidden"] is False
assert checkin.list_memes() == ["test.png"]
assert len(client.get("/api/admin/memes", headers=adm).json()["items"]) == 2 # 管理頁兩張都看得到
def test_hidden_meme_keeps_old_cards(client, sent, adm):
tok = bearer(login(client, sent)["token"])
client.cookies.clear()
r = client.post("/api/checkin", headers=tok).json()
before = card_png(client, r["card_url"])
put(client, adm, "test.png", hidden=True)
for p in (config.DATA_DIR / "cards").rglob("*.png"):
p.unlink()
assert card_png(client, r["card_url"]).tobytes() == before.tobytes() # 重畫還是同一張圖
assert client.get("/api/admin/memes", headers=adm).json()["items"][0]["used"] == 1
def test_source_is_cleaned(client, adm):
assert put(client, adm, "test.png", source="‮x@​sthkm3\n").json()["source"] == "x@sthkm3"
assert put(client, adm, "test.png", source="a" * 41).json()["detail"] == "source_too_long"
assert put(client, adm, "test.png", source="").json()["source"] == ""
@pytest.mark.parametrize("name", ["../zhiwu.db", "..%2Fzhiwu.db", "nope.png", ".hidden.png", "a/b.png", "test.png.webp"])
def test_bad_names(client, adm, name):
assert client.put(f"/api/admin/memes/{name}", headers=adm, json={"hidden": True}).status_code == 404
assert client.get(f"/api/admin/memes/{name}/thumb", headers=adm).status_code == 404
def test_thumb(client, adm):
Image.new("RGBA", (2000, 1000), (0, 0, 0, 0)).save(config.MEME_DIR / "big.png")
url = next(m["thumb_url"] for m in client.get("/api/admin/memes", headers=adm).json()["items"] if m["name"] == "big.png")
r = client.get(url, headers=adm)
assert r.status_code == 200 and r.headers["content-type"] == "image/webp"
im = Image.open(io.BytesIO(r.content))
assert im.size == (320, 160) and im.mode == "RGBA" # 縮圖保留透明
put(client, adm, "big.png", hidden=True)
assert client.get(url, headers=adm).status_code == 200 # 下架的也看得到縮圖
# ---------- 投稿的出處 ----------
def test_submission_source_flows_to_gallery(client, sent, adm):
tok = login(client, sent)["token"]
client.cookies.clear()
r = client.post("/api/submissions", headers=bearer(tok), data={"source": "youtube@p2p2p"},
files={"file": ("a.png", _img(), "image/png")})
assert r.json()["item"]["source"] == "youtube@p2p2p"
assert client.post("/api/submissions", headers=bearer(tok), data={"source": "x" * 41},
files={"file": ("a.png", _img(), "image/png")}).json()["detail"] == "source_too_long"
item = client.get("/api/admin/submissions", headers=adm).json()["item"]
assert item["source"] == "youtube@p2p2p"
name = client.post(f"/api/admin/submissions/{item['id']}/approve", headers=adm).json()["meme"]
assert memes.source_of(name) == "youtube@p2p2p"
def test_admin_can_change_source_when_approving(client, sent, adm):
tok = login(client, sent)["token"]
client.cookies.clear()
ids = [upload(client, tok).json()["item"]["id"] for _ in range(2)]
a = client.post(f"/api/admin/submissions/{ids[0]}/approve", headers=adm, json={"source": "x@fixed"}).json()["meme"]
b = client.post(f"/api/admin/submissions/{ids[1]}/approve", headers=adm, json={}).json()["meme"]
assert memes.source_of(a) == "x@fixed" and memes.source_of(b) == ""
conn = db.connect()
assert conn.execute("SELECT COUNT(*) FROM memes WHERE name = ?", (b,)).fetchone()[0] == 0 # 沒出處就不建資料列
conn.close()
# ---------- 小卡 ----------
def source_area(img):
"""出處畫在圖的右下角。"""
return img.crop((card.W - card.PAD - 500, card.PAD + 700, card.W - card.PAD - 10, card.PAD + 750))
def test_source_drawn_on_card_and_redrawn_on_change(client, sent, adm):
tok = bearer(login(client, sent)["token"])
client.cookies.clear()
r = client.post("/api/checkin", headers=tok).json()
plain = card_png(client, r["card_url"])
put(client, adm, "test.png", source="x@sthkm3")
with_source = card_png(client, r["card_url"]) # 改出處後快取被清掉,重畫
assert source_area(plain).tobytes() != source_area(with_source).tobytes()
assert plain.crop((0, 0, 1080, 600)).tobytes() == with_source.crop((0, 0, 1080, 600)).tobytes() # 其他地方不變
put(client, adm, "test.png", source="")
assert card_png(client, r["card_url"]).tobytes() == plain.tobytes()
def test_guest_card_shows_source(client, adm):
params = {"code": "AB12", "n": 1}
plain = client.get("/card/guest.png", params=params).content
put(client, adm, "test.png", source="x@sthkm3")
assert client.get("/card/guest.png", params=params).content != plain
@pytest.mark.parametrize("lang", ["zh-TW", "zh-CN", "ja", "ko", "en"])
def test_long_source_fits(lang):
img = card.draw(lang, "test.png", "名稱", None, None, "x", "y", 1, source="あ" * 40)
assert img.size == (card.W, card.H)
# ---------- 透明 ----------
@pytest.mark.parametrize("fmt", ["PNG", "WEBP", "GIF"])
def test_transparent_meme_uses_panel_colour(fmt, tmp_path, monkeypatch):
monkeypatch.setattr(config, "MEME_DIR", tmp_path)
im = Image.new("RGBA", (400, 400), (255, 255, 255, 0)) # 透明處底下藏的是白色
im.paste((255, 0, 0, 255), (150, 150, 250, 250))
if fmt == "GIF": # 調色盤透明:0 號色(白)是透明的
gif = Image.new("P", (400, 400), 0)
gif.putpalette([255, 255, 255, 255, 0, 0])
gif.paste(1, (150, 150, 250, 250))
gif.save(tmp_path / "t.gif", transparency=0)
else:
im.save(tmp_path / f"t.{fmt.lower()}", fmt, lossless=True) if fmt == "WEBP" else im.save(tmp_path / "t.png")
out = card.draw("en", f"t.{fmt.lower()}", "n", None, None, "x", "y", 1)
corner = out.getpixel((card.PAD + 400, card.PAD + 60)) # 圖的透明處
assert max(corner) < 40, corner # 是框的深色底,不是白
center = out.getpixel((card.W // 2, card.PAD + 380))
assert center[0] > 200 and center[1] < 60 # 不透明的部分照常
def test_transparent_avatar_uses_accent():
av = Image.new("RGBA", (200, 200), (255, 255, 255, 0))
out = card.draw("en", None, "n", av, None, "x", "y", 1)
px = out.getpixel((card.PAD + 84, card.PAD + 760 + 40 + 84))
assert abs(px[0] - card.ACCENT[0]) < 10 and abs(px[1] - card.ACCENT[1]) < 10
# ---------- 其他 ----------
def test_pages_served(client):
for path in ("/images", "/review", "/upload"):
assert client.get(path).status_code == 200
def test_edit_button_moved_to_profile(client):
html = client.get("/").text
assert 'id="edit-profile"' not in html and 'id="user-edit"' in html
def test_upgrade_from_102(tmp_path, monkeypatch):
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
monkeypatch.setattr(config, "ADMIN_LOGIN", "")
conn = sqlite3.connect(tmp_path / "zhiwu.db")
conn.execute("CREATE TABLE submissions (id INTEGER PRIMARY KEY AUTOINCREMENT, uid INTEGER NOT NULL, day TEXT NOT NULL, "
"ext TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', meme TEXT, created_at INTEGER NOT NULL, "
"reviewed_at INTEGER)")
conn.execute("INSERT INTO submissions(uid, day, ext, created_at) VALUES (1, '2026-11-21', 'jpg', 1)")
conn.commit()
conn.close()
db.init()
conn = db.connect()
assert conn.execute("SELECT source FROM submissions").fetchone()[0] == ""
assert conn.execute("SELECT COUNT(*) FROM memes").fetchone()[0] == 0
conn.close()
@@ -13,22 +13,9 @@ 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"})
client.patch("/api/me", json={"display_name": "Tester"})
first = client.post("/api/checkin").json()
assert client.get(first["card_url"]).status_code == 200
@@ -40,7 +27,7 @@ def test_reset_progress(client, sent, capsys):
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 me["display_name"] == "Tester" and me["uid_str"] == "00000001"
assert list(config.DATA_DIR.glob("zhiwu.db.bak-*"))
assert not any((config.DATA_DIR / "cards").iterdir())
# 同一天可以重新簽到
+356
View File
@@ -0,0 +1,356 @@
"""1.0.2 發版前的漏洞修補:寄信限制、管理員不可探測、圖片、請求大小、儲存權限。"""
import io
import os
import struct
import zlib
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
import pytest
from PIL import Image
from app import anticheat, auth, config, db, images, limits, main, users
from .conftest import ADMIN_LOGIN, admin_code, admin_verify, login
def ask(client, email, ip="198.51.100.1"):
return client.post("/api/auth/request-code", json={"email": email}, headers={"CF-Connecting-IP": ip})
def verify(client, email, code):
return client.post("/api/auth/verify", json={"email": email, "code": code})
def bomb(w, h):
"""檔頭寫很大、內容很小的 PNG。"""
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(b"\0" * 1000)) + chunk(b"IEND", b""))
def img(fmt, size=(40, 30), **kw):
buf = io.BytesIO()
Image.new("RGB", size, (9, 99, 200)).save(buf, fmt, **kw)
return buf.getvalue()
def put_avatar(client, data):
return client.put("/api/me/avatar", files={"file": ("a", data, "image/png")})
# ---------- 寄信 ----------
@pytest.mark.parametrize("email", [
"<[email protected]>", "a<[email protected]>", "z,[email protected]", "(c)[email protected]", '"x"<[email protected]>', "v@example",
"[email protected]", "[email protected]", "v [email protected]", "[email protected]\nBcc: [email protected]", "v@example.com", "\ud800@a.co", "[email protected]", "",
"a" * 65 + "@example.com", "v@" + "a." * 130 + "com",
])
def test_odd_emails_rejected(client, sent, email):
import json
r = client.post("/api/auth/request-code", content=json.dumps({"email": email}),
headers={"Content-Type": "application/json"})
assert r.status_code == 400 and r.json()["detail"] == "invalid_email" and sent == {}
@pytest.mark.parametrize("email", ["[email protected]", "[email protected]", "[email protected]", "o'[email protected]"])
def test_normal_emails_accepted(email):
assert limits.valid_email(email)
def test_ip_key():
assert limits.ip_key("2001:db8:1:1::5") == limits.ip_key("2001:db8:1:1:ffff::9")
assert limits.ip_key("2001:db8:1:1::5") != limits.ip_key("2001:db8:1:2::5")
assert limits.ip_key("::ffff:203.0.113.9") == limits.ip_key("203.0.113.9") == "203.0.113.9"
assert limits.ip_key("203.0.113.9") != limits.ip_key("203.0.113.10")
assert limits.ip_key("testclient") == "testclient"
def test_ipv6_64_shares_limit(client, sent):
codes = [ask(client, f"u{i}@example.com", f"2001:db8:1:1::{i:x}").status_code for i in range(12)]
assert codes == [200] * config.IP_LIMIT + [429] * 2
@pytest.mark.parametrize("name", ["MAIL_LIMIT", "MAIL_DAY_LIMIT"])
def test_site_wide_mail_limit(client, sent, monkeypatch, name):
monkeypatch.setattr(config, name, 3)
codes = [ask(client, f"u{i}@example.com", f"203.0.113.{i}").status_code for i in range(5)]
assert codes == [200, 200, 200, 429, 429] and len(sent) == 3
conn = db.connect()
assert [(r["kind"], r["count"]) for r in conn.execute("SELECT * FROM notices")] == [("mail_limit", 2)]
conn.close()
def test_sweep_drops_expired_only(monkeypatch):
auth._ip_mail.clear()
now = [1000.0]
monkeypatch.setattr(limits.time, "monotonic", lambda: now[0])
auth._ip_mail.allow("old")
now[0] += config.IP_WINDOW - 1
auth._ip_mail.allow("new")
now[0] += 2
limits.sweep_all()
assert list(auth._ip_mail._hits) == ["new"]
def test_hourly_loop_sweeps(monkeypatch):
import asyncio
called = []
async def fake_sleep(_):
if called:
raise asyncio.CancelledError
monkeypatch.setattr(anticheat.asyncio, "sleep", fake_sleep)
monkeypatch.setattr(anticheat, "check_safe", lambda: None)
monkeypatch.setattr(limits, "sweep_all", lambda: called.append(1))
with pytest.raises(asyncio.CancelledError):
asyncio.run(anticheat.loop())
assert called == [1]
# ---------- 驗證碼:同時送也不能多猜、不能重複用 ----------
def test_parallel_guesses_are_capped(client, sent, monkeypatch):
ask(client, "[email protected]")
compared = []
real = auth.secrets.compare_digest
monkeypatch.setattr(auth.secrets, "compare_digest", lambda a, b: compared.append(1) or real(a, b))
with ThreadPoolExecutor(30) as ex:
codes = list(ex.map(lambda i: verify(client, "[email protected]", f"x{i}").json()["detail"], range(150)))
assert len(compared) == config.CODE_MAX_ATTEMPTS
assert codes.count("wrong_code") == config.CODE_MAX_ATTEMPTS - 1
def test_parallel_right_code_works_once(client, sent):
ask(client, "[email protected]")
with ThreadPoolExecutor(10) as ex:
codes = list(ex.map(lambda _: verify(client, "[email protected]", sent["[email protected]"]).status_code, range(30)))
assert codes.count(200) == 1
def test_fifth_try_can_still_succeed(client, sent):
ask(client, "[email protected]")
for _ in range(config.CODE_MAX_ATTEMPTS - 1):
assert verify(client, "[email protected]", "x").json()["detail"] == "wrong_code"
assert verify(client, "[email protected]", sent["[email protected]"]).status_code == 200
def test_used_admin_code_does_not_burn_attempts(client, fake_clock):
assert admin_verify(client, admin_code(fake_clock)).status_code == 200
ask(client, ADMIN_LOGIN)
for _ in range(config.CODE_MAX_ATTEMPTS + 2):
assert verify(client, ADMIN_LOGIN, admin_code(fake_clock)).json()["detail"] == "code_used"
# ---------- 管理員和一般信箱的回應要完全一樣 ----------
def walk(client, email, fake_clock):
"""把外人能做的事走一遍,記下每一步的回應。"""
out = []
def rec(r):
out.append((r.status_code, r.text, sorted(k for k in r.headers if k not in ("date", "content-length"))))
rec(verify(client, email, "999999")) # 還沒要驗證碼
rec(ask(client, email))
rec(ask(client, email)) # 60 秒內重寄
for code in ("999999", "123456", "", "abc", "é"):
rec(verify(client, email, code)) # 第 5 次作廢(管理員第 3 次已鎖定)
rec(verify(client, email, "999999"))
fake_clock.value += timedelta(seconds=61)
rec(ask(client, email))
rec(verify(client, email, "999999")) # 管理員鎖定中
fake_clock.value += timedelta(minutes=6)
rec(verify(client, email, "999999")) # 過期
return out
def test_admin_is_indistinguishable(client, sent, fake_clock, monkeypatch):
monkeypatch.setattr(auth.secrets, "randbelow", lambda n: 123457)
start = fake_clock.value
normal = walk(client, "[email protected]", fake_clock)
fake_clock.value = start
auth._ip_mail.clear()
assert walk(client, ADMIN_LOGIN, fake_clock) == normal
assert ADMIN_LOGIN not in sent
conn = db.connect()
assert db.get_meta(conn, "admin_lock_level") == 1 # 裡面還是有鎖
conn.close()
def test_surrogate_code_is_same_for_everyone(client, sent):
for email in ("[email protected]", ADMIN_LOGIN):
ask(client, email)
r = client.post("/api/auth/verify", content='{"email":"%s","code":"\\ud800"}' % email,
headers={"Content-Type": "application/json"})
assert r.status_code == 400 and r.json()["detail"] == "wrong_code"
def test_admin_waits_like_real_mail(client, sent, monkeypatch):
slept = []
monkeypatch.setattr(auth.time, "sleep", slept.append)
ask(client, ADMIN_LOGIN)
assert slept == [] # 沒設 SMTP:一般信箱也是立刻回
db.connect().execute("DELETE FROM login_codes")
monkeypatch.setattr(config, "SMTP_USER", "u")
monkeypatch.setattr(config, "SMTP_PASSWORD", "p")
auth._send_times.clear()
auth._send_times.append(2.0)
ask(client, ADMIN_LOGIN)
assert len(slept) == 1 and 1.8 <= slept[0] <= 2.2
@pytest.mark.parametrize("how", ["no_totp", "bad_totp", "not_email", "no_login"])
def test_disabled_admin_cannot_be_taken_over_by_mail(client, sent, fake_clock, monkeypatch, how):
"""管理員停用後,就算那個信箱真的存在,也不能用寄信的驗證碼登入成管理員。"""
key, value = {"no_totp": ("ADMIN_TOTP", ""), "bad_totp": ("ADMIN_TOTP", "!!"),
"not_email": ("ADMIN_LOGIN", "boss"), "no_login": ("ADMIN_LOGIN", "")}[how]
monkeypatch.setattr(config, key, value)
db.init()
assert db.admin_ok is False
monkeypatch.setattr(auth.secrets, "randbelow", lambda n: 123456)
assert ask(client, ADMIN_LOGIN).status_code == 200 and sent == {}
assert verify(client, ADMIN_LOGIN, "123456").json()["detail"] == "wrong_code"
assert verify(client, ADMIN_LOGIN, admin_code(fake_clock)).json()["detail"] == "wrong_code"
def test_admin_login_is_recorded(client, fake_clock):
for _ in range(2):
r = admin_verify(client, admin_code(fake_clock), headers={
"CF-Connecting-IP": "203.0.113.7", "CF-IPCountry": "TW", "User-Agent": "Test/1.0 " + "x" * 300})
assert r.status_code == 200
fake_clock.value += timedelta(seconds=30)
r = client.get("/api/admin/notices").json()
assert [(n["kind"], n["count"], n["unread"]) for n in r["items"]] == [("admin_login", 1, True)] * 2
assert r["items"][0]["detail"].startswith("203.0.113.7 · TW · Test/1.0 xxx") and len(r["items"][0]["detail"]) < 200
def test_normal_login_is_not_recorded(client, sent):
login(client, sent)
assert db.connect().execute("SELECT COUNT(*) FROM notices").fetchone()[0] == 0
# ---------- 圖片 ----------
def test_bomb_rejected_before_decode(client, sent, monkeypatch):
login(client, sent)
monkeypatch.setattr(Image.Image, "load", lambda self: pytest.fail("不該解碼"))
r = put_avatar(client, bomb(8900, 8900))
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
@pytest.mark.parametrize("fmt,ok", [("PNG", 1), ("JPEG", 1), ("WEBP", 1), ("GIF", 0),
("TIFF", 0), ("BMP", 0), ("ICO", 0), ("TGA", 0), ("PPM", 0), ("PCX", 0)])
def test_only_four_formats(client, sent, fmt, ok):
login(client, sent)
assert put_avatar(client, img(fmt)).status_code == (200 if ok else 400)
r = client.post("/api/submissions", files={"file": ("a.png", img(fmt), "image/png")})
assert r.status_code == (200 if ok else 400)
def test_gif_upload_rejected(client, sent):
login(client, sent)
for data in (img("GIF"), img("GIF") + b"x" * 10):
r = put_avatar(client, data)
assert r.status_code == 400 and r.json()["detail"] == "unsupported_format"
frames = [Image.new("RGB", (40, 30), c) for c in ((255, 0, 0), (0, 0, 255))]
buf = io.BytesIO()
frames[0].save(buf, "WEBP", save_all=True, append_images=frames[1:], lossless=True)
im, _ = images.decode(buf.getvalue()) # 動態 WEBP:只取第一格,存成靜態
assert im.getpixel((5, 5))[:3] == (255, 0, 0) and getattr(im, "n_frames", 1) == 1
def test_psd_rejected(client, sent):
login(client, sent)
psd = b"8BPS" + struct.pack(">H6xHIIHH", 1, 3, 4, 4, 8, 3) + b"\0" * 14 + b"\0" * 48
with Image.open(io.BytesIO(psd)) as im:
assert im.format == "PSD" # 這個檔本身是讀得到的
assert put_avatar(client, psd).status_code == 400
def test_exif_rotation_kept(client, sent):
exif = Image.Exif()
exif[0x0112] = 6
im, alpha = images.decode(img("JPEG", (40, 30), exif=exif))
assert im.size == (30, 40) and alpha is False
def test_avatar_three_per_minute(client, sent):
login(client, sent)
codes = [put_avatar(client, d).status_code for d in (img("PNG"), b"bad", img("PNG"), img("PNG"))]
assert codes == [200, 400, 200, 429] # 失敗也算
assert put_avatar(client, img("PNG")).json()["detail"] == "too_frequent"
client.cookies.clear()
login(client, sent, "[email protected]")
assert put_avatar(client, img("PNG")).status_code == 200
def test_one_image_at_a_time(client, sent, monkeypatch):
login(client, sent)
monkeypatch.setattr(config, "IMAGE_WAIT", 0.05)
with images.slot():
r = put_avatar(client, img("PNG"))
assert r.status_code == 429 and r.json()["detail"] == "too_frequent"
assert put_avatar(client, img("PNG")).status_code == 200 # 失敗後鎖有放開
assert put_avatar(client, b"bad").status_code == 400
assert images._slot.acquire(timeout=0) and images._slot.release() is None
# ---------- 請求大小、路徑 ----------
def test_body_limit_by_length(client):
r = client.post("/api/auth/request-code", json={"email": "a" * config.BODY_MAX})
assert r.status_code == 413 and r.json()["detail"] == "file_too_large"
r = client.post("/api/submissions", files={"file": ("a", b"\0" * config.UPLOAD_BODY_MAX)})
assert r.status_code == 413
@pytest.mark.parametrize("path,ctype,limit", [
("/api/auth/request-code", "application/json", config.BODY_MAX),
("/api/submissions", "multipart/form-data; boundary=b", config.UPLOAD_BODY_MAX),
])
def test_body_limit_chunked(client, path, ctype, limit):
got = [0]
def body():
yield b'--b\r\nContent-Disposition: form-data; name="file"; filename="a"\r\n\r\n' if "multi" in ctype else b'{"email":"'
for _ in range(limit // 32768 + 40):
got[0] += 1
yield b"a" * 32768
r = client.post(path, content=body(), headers={"Content-Type": ctype})
assert r.status_code == 413 and r.json()["detail"] == "file_too_large"
def test_five_mb_file_still_allowed(client, sent):
login(client, sent)
data = img("PNG")
assert put_avatar(client, data + b"\0" * (config.AVATAR_MAX_BYTES - len(data))).status_code == 200
def test_csrf_not_bypassed_by_host(client, sent):
login(client, sent)
r = client.post("/api/checkin", headers={"X-ZHIWU": "", "Host": "x/y?"})
assert r.status_code in (400, 403)
# ---------- 儲存權限 ----------
@pytest.mark.skipif(os.name == "nt" or os.geteuid() == 0, reason="要在非 root 的 Linux 上測")
def test_storage_check(tmp_path, monkeypatch, capsys):
data, memes = tmp_path / "d", tmp_path / "m"
data.mkdir(), memes.mkdir()
monkeypatch.setattr(config, "DATA_DIR", data)
monkeypatch.setattr(config, "MEME_DIR", memes)
main.check_storage()
memes.chmod(0o500)
main.check_storage()
assert "[WARN]" in capsys.readouterr().out
(data / "zhiwu.db").touch(0o400)
with pytest.raises(RuntimeError, match="zhiwu.db"):
main.check_storage()
memes.chmod(0o700)
def test_users_module_has_no_direct_open():
assert not hasattr(users, "Image") or "Image.open" not in open(users.__file__, encoding="utf-8").read()
+2 -2
View File
@@ -4,7 +4,7 @@ from PIL import Image
from app import admin, checkin, config, db
from .conftest import ADMIN_LOGIN, admin_code, login
from .conftest import admin_code, admin_verify, login
def _img(fmt="PNG", color=(10, 200, 30), size=(300, 200), **kw):
@@ -23,7 +23,7 @@ def upload(client, token, data=None, name="a.png"):
def admin_token(client, fake_clock):
r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock)})
r = admin_verify(client, admin_code(fake_clock))
assert r.status_code == 200, r.text
return r.json()["token"]
+2 -3
View File
@@ -4,7 +4,7 @@ import sqlite3
from app import admin, config, db
from app.titles import text_on
from .conftest import ADMIN_LOGIN, admin_code, login
from .conftest import admin_code, admin_verify, login
def bearer(tok):
@@ -12,8 +12,7 @@ def 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"})
r = admin_verify(client, admin_code(fake_clock))
assert r.status_code == 200, r.text
client.cookies.clear()
return r.json()["token"]
+20 -10
View File
@@ -1,7 +1,7 @@
"""吱吱(點擊)次數:和簽到天數分開記錄,簽到那一下也算一次。"""
import pytest
from app import checkin, config
from app import card, checkin, config
from .conftest import login
@@ -11,7 +11,8 @@ def frozen(monkeypatch):
"""固定限流用的時鐘,測試自己決定時間前進多少。"""
now = [1000.0]
monkeypatch.setattr(checkin, "_now", lambda: now[0])
checkin._buckets.clear()
for d in (checkin._next, checkin._rejects, checkin._cool):
d.clear()
return now
@@ -33,7 +34,7 @@ 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
frozen[0] += config.ZHI_GAP
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
@@ -58,21 +59,30 @@ def test_zhi_rejects_bad_batch(client, sent, frozen, n):
assert client.get("/api/me").json()["clicks"] == 0
def test_zhi_once_per_second(client, sent, frozen):
"""一個帳號一秒只能吱一次:同一秒內多的、一次送很多下的,都只算一下。"""
def test_zhi_once_per_gap(client, sent, frozen):
"""一個帳號 1.5 秒只能吱一次:太快的、一次送很多下的,都只算一下。"""
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
frozen[0] += 1.1
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 1, "added": 0}
frozen[0] += 0.1
frozen[0] += 0.4
assert client.post("/api/zhi", json={"n": 1}).json() == {"clicks": 2, "added": 1}
# 等再久額度也只存 1 下;一次送 200 下也只加 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_jitter_does_not_raise_average(frozen):
"""可以提早 0.3 秒,但提早的會扣回來:長期平均還是 1.5 秒一下。"""
ok = 0
for _ in range(1000):
frozen[0] += 1.25
ok += checkin._take(1)[0] == "ok"
assert ok <= 1250 / config.ZHI_GAP + 1
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
@@ -93,13 +103,13 @@ def test_card_redrawn_when_clicks_change(client, sent, frozen):
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"]
assert [p.name for p in cards.iterdir()] == [f"{r['day']}.v{card.CARD_VERSION}.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 [p.name for p in cards.iterdir()] == [f"{r['day']}.v{card.CARD_VERSION}.c2.png"]
# 次數沒變就直接用快取
assert client.get(r["card_url"] + "?c=2").content == second.content
+385 -30
View File
@@ -4,12 +4,13 @@ const HTML_LANG = { "zh-TW": "zh-Hant-TW", "zh-CN": "zh-Hans-CN", ja: "ja", ko:
const DEFAULT_AVATAR = "/assets/avatar.svg";
const $ = (id) => document.getElementById(id);
const HOME_TITLE = document.title; // 「吱鼯計畫 — 你今天吱吱了嗎」,伺服器會依 BETA 開關加上 (Beta)
const HOME_TITLE = document.title; // 「吱鼯計畫 — 你今天吱吱了嗎」
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 ZHI_GAP_MS = 1550; // 伺服器一個帳號 1.5 秒只收一下;補送沒送成功的次數時,每下隔這麼久
const ZHI_COOL_MS = 10000; // 太頻繁被伺服器要求冷靜的時間
const SUBMIT_MAX_BYTES = 5 * 1024 * 1024;
const state = {
@@ -21,13 +22,20 @@ const state = {
cardBust: Date.now(),
resendTimer: null,
resetTimer: null,
zhiMode: null, // null = 沒開 / "checkin" = 簽到那一下 / "more" = 繼續吱吱
guest: null, // 訪客紀錄 {code, clicks},只存在這個瀏覽器(localStorage),伺服器不記
guestOn: false, // 現在是訪客吱吱的畫面(沒登入)
installPrompt: null, // Android Chrome 的安裝事件
zhiMode: null, // null = 沒開 / "checkin" = 簽到那一下 / "guest" = 訪客那一下 / "more" = 繼續吱吱
zhiBusy: false, // 影片播放中:不接受點擊(簽到和繼續吱吱都一樣)
zhiSkipped: false, // 今天還沒簽到,但使用者按了「等等再吱」
zhiPending: 0, // 還沒送到伺服器的點擊次數
zhiTimer: null,
zhiAuto: false, // 全自動吱吱開著:播完自動接下一次
zhiAutoTimer: null,
zhiCoolUntil: 0, // 冷靜到什麼時候
noticeCount: 0, // 通知匣已經載入幾則
gallery: [], // 管理圖片:圖庫清單
galleryHidden: false, // 管理圖片:現在看的是已下架的
zhiLastAt: 0, // 上一次繼續吱吱的時間
zhiPlay: 0, // 第幾次播放;離開再進來時,舊的那次播完不能動到新的
zhiFlush: null, // 正在送次數的 Promise(離開時等它送完)
@@ -57,6 +65,9 @@ async function loadLang(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-placeholder]").forEach((el) => {
el.placeholder = t(el.dataset.i18nPlaceholder);
});
document.querySelectorAll("[data-i18n-aria]").forEach((el) => {
el.setAttribute("aria-label", t(el.dataset.i18nAria));
});
@@ -154,7 +165,11 @@ function renderSidebar() {
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 });
$("notices-link").hidden = !me.is_admin;
if (me.is_admin) {
$("review-link").textContent = t("nav.review", { n: me.pending_reviews ?? 0 });
$("notices-link").textContent = t("nav.notices", { n: me.unread_notices ?? 0 });
}
}
function showCodeStep(show) {
@@ -208,6 +223,7 @@ function bindAuth() {
try {
const r = await api("POST", "/api/auth/verify", { email: state.email, code, lang: state.lang });
state.me = r.user;
state.guestOn = false;
clearInterval(state.resendTimer);
showCodeStep(false);
$("email").value = "";
@@ -241,10 +257,12 @@ function bindAuth() {
await route();
});
$("guest-login").addEventListener("click", () => {
openMenu();
$("email").focus();
});
for (const id of ["guest-login", "done-login"]) {
$(id).addEventListener("click", () => {
openMenu();
$("email").focus();
});
}
}
// ---------- 簽到 ----------
@@ -268,6 +286,9 @@ function cardSrc(d) { return `${d.card_url}?v=${state.cardBust}&c=${d.clicks}`;
function renderToday(justChecked) {
const d = state.today;
state.guestOn = false;
$("share-btn").hidden = false;
$("done-login").hidden = true;
if (!d.checked_in) {
showCheckinPart("checkin-ready");
$("ready-stats").textContent = d.total_days || d.clicks ? statsText(d) : "";
@@ -282,6 +303,7 @@ function renderToday(justChecked) {
$("download-btn").href = src;
$("download-btn").setAttribute("download", `zhiwu-${d.day}.png`);
$("done-stats").textContent = statsText(d);
updateInstallHint();
}
startResetCountdown();
}
@@ -328,8 +350,129 @@ async function refreshToday() {
function showGuest() {
clearInterval(state.resetTimer);
$("next-reset").hidden = true;
if (state.guestOn) { // 正在看訪客小卡(例如換了語言)
if (state.zhiMode !== "more") renderGuestCard(false);
return;
}
closeStage();
showCheckinPart("checkin-guest");
const g = loadGuest();
$("guest-stats").hidden = !g;
if (g) $("guest-stats").textContent = guestStatsText(g);
}
// ---------- 訪客吱吱 ----------
// 不用登入。代號(訪客 #XXXX)和吱吱次數只存在這個瀏覽器,伺服器什麼都不記;
// 小卡由伺服器照網址上的代號和次數即時畫出來,沒有 UID、沒有分享連結。
const GUEST_KEY = "zhiwu_guest";
const GUEST_CHARS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // 去掉容易看錯的 0 O 1 I
function loadGuest() {
if (state.guest) return state.guest;
try {
const g = JSON.parse(localStorage.getItem(GUEST_KEY));
if (g && /^[A-Z0-9]{4}$/.test(g.code) && Number.isInteger(g.clicks) && g.clicks >= 0) state.guest = g;
} catch { /* 沒有紀錄或壞掉了:當作新訪客 */ }
return state.guest;
}
function ensureGuest() {
if (loadGuest()) return state.guest;
const rnd = crypto.getRandomValues(new Uint8Array(4));
state.guest = { code: [...rnd].map((b) => GUEST_CHARS[b % GUEST_CHARS.length]).join(""), clicks: 0 };
saveGuest();
return state.guest;
}
function saveGuest() {
try { localStorage.setItem(GUEST_KEY, JSON.stringify(state.guest)); } catch { /* 無痕模式存不了就只留在這次 */ }
}
function addGuestClick() {
state.guest.clicks = Math.min(state.guest.clicks + 1, 9999999);
saveGuest();
}
function guestStatsText(g) {
return `${t("guest.name", { code: g.code })} · ${t("checkin.clicks", { n: fmtNum(g.clicks) })}`;
}
function guestCardSrc(g) {
return `/card/guest.png?code=${g.code}&n=${g.clicks}&lang=${state.lang}`;
}
function renderGuestCard(just) {
const g = state.guest;
showCheckinPart("checkin-done");
$("checkin-msg").textContent = t(just ? "guest.success" : "guest.card");
const src = guestCardSrc(g);
if ($("card-img").getAttribute("src") !== src) $("card-img").src = src;
$("download-btn").href = src;
$("download-btn").setAttribute("download", `zhiwu-guest-${g.code}.png`);
$("share-btn").hidden = true; // 伺服器沒有訪客紀錄,沒有可以分享的連結
$("done-login").hidden = false;
$("done-stats").textContent = guestStatsText(g);
updateInstallHint();
}
// 訪客的那一下:播影片、次數 +1(存在本機),播完而且小卡下載好才亮出小卡
async function zhiGuest(x, y) {
if (state.zhiBusy) return;
state.zhiBusy = true;
$("zhi-exit").disabled = true;
playVideo();
burst(x, y);
const ended = waitVideoEnd();
addGuestClick();
state.zhiLastAt = Date.now();
await Promise.all([ended, preloadImage(guestCardSrc(state.guest))]);
if (state.zhiMode !== "guest") return;
closeStage();
renderGuestCard(true);
}
// ---------- 手機:提示安裝到桌面 ----------
const INSTALL_KEY = "zhiwu_install_dismissed";
function canHintInstall() {
const mobile = window.matchMedia("(pointer: coarse)").matches && window.matchMedia("(max-width: 760px)").matches;
const installed = window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
let dismissed = false;
try { dismissed = localStorage.getItem(INSTALL_KEY) === "1"; } catch { /* 讀不到就當作沒關過 */ }
return mobile && !installed && !dismissed;
}
// 小卡下方的提示:Android Chrome 有安裝按鈕;iPhone 只能教他從分享選單加入主畫面
function updateInstallHint() {
const el = $("install-hint");
if (!canHintInstall()) { el.hidden = true; return; }
const ios = /iphone|ipad|ipod/i.test(navigator.userAgent);
$("install-text").textContent = t(ios ? "install.ios" : state.installPrompt ? "install.android" : "install.generic");
$("install-btn").hidden = !state.installPrompt;
el.hidden = false;
}
function bindInstall() {
window.addEventListener("beforeinstallprompt", (ev) => {
ev.preventDefault(); // 不要讓瀏覽器自己跳橫幅,改由提示上的按鈕觸發
state.installPrompt = ev;
if (!$("checkin-done").hidden) updateInstallHint();
});
window.addEventListener("appinstalled", () => { state.installPrompt = null; $("install-hint").hidden = true; });
$("install-btn").addEventListener("click", async () => {
const ev = state.installPrompt;
if (!ev) return;
state.installPrompt = null;
ev.prompt();
await ev.userChoice.catch(() => {});
$("install-hint").hidden = true;
});
$("install-close").addEventListener("click", () => {
try { localStorage.setItem(INSTALL_KEY, "1"); } catch { /* 存不了就只關這次 */ }
$("install-hint").hidden = true;
});
}
async function showCheckin() {
@@ -433,7 +576,8 @@ function waitVideoEnd() {
function showZhiCount(bump) {
const el = $("zhi-count");
el.textContent = t("zhi.count", { n: fmtNum(state.today?.clicks ?? 0) });
const n = state.guestOn ? state.guest.clicks : state.today?.clicks ?? 0;
el.textContent = t("zhi.count", { n: fmtNum(n) });
if (bump) { el.classList.remove("bump"); void el.offsetWidth; el.classList.add("bump"); }
}
@@ -492,17 +636,22 @@ async function zhiCheckin(x, y) {
// 繼續吱吱:播放中再點沒有反應;播完回到第一幀才能點下一次
function zhiMore(x, y) {
if (state.zhiBusy) return;
// 一個帳號一秒只能吱一次(伺服器也會擋)。影片比 1 秒長,只有離開再馬上進來時會遇到
if (Date.now() < state.zhiCoolUntil) { toast(t("err.cooldown")); return; }
// 一個帳號 1.5 秒只能吱一次(伺服器也會擋)。影片比 1.5 秒長,只有離開再馬上進來時會遇到
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++;
if (state.guestOn) {
addGuestClick(); // 訪客:只記在本機,不送伺服器
} else {
state.zhiPending++;
state.today.clicks++;
flushZhi();
}
showZhiCount(true);
flushZhi();
waitVideoEnd().then(() => {
if (state.zhiMode !== "more" || state.zhiPlay !== play) return; // 播到一半按了回到小卡(或離開後又進來)
resetVideo();
@@ -524,7 +673,7 @@ function setZhiAuto(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);
@@ -538,7 +687,7 @@ function zhiAutoTick() {
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 把還沒送的次數一下一下送給伺服器(伺服器一個帳號一秒只收一下)
// 把還沒送的次數一下一下送給伺服器(伺服器一個帳號 1.5 秒只收一下)
function flushZhi() {
clearTimeout(state.zhiTimer);
state.zhiTimer = null;
@@ -547,22 +696,36 @@ function flushZhi() {
}
async function sendZhi() {
let retried = false;
while (state.zhiPending > 0) {
const sentAt = Date.now();
try {
const r = await api("POST", "/api/zhi", { n: 1 });
state.zhiPending--;
// 網路抖動讓兩下太近、伺服器沒算到:重送一次。再失敗或已經積了幾下就放棄(例如兩台裝置同時在吱)
if (r.added || retried || state.zhiPending > 2) { state.zhiPending--; retried = false; } else retried = true;
// 以伺服器的數字為準,再加上還沒送出的
if (state.today) state.today.clicks = r.clicks + state.zhiPending;
} catch (e) {
if (e.status === 401 || e.status === 400) { state.zhiPending = 0; return; } // 登出了:這幾下就不算
if (e.code === "cooldown") return coolDown();
state.zhiTimer = setTimeout(flushZhi, ZHI_GAP_MS * 3); // 網路問題:留著等一下再送
return;
}
if (state.zhiPending > 0) await sleep(ZHI_GAP_MS);
if (state.zhiPending > 0) await sleep(Math.max(0, ZHI_GAP_MS - (Date.now() - sentAt)));
}
if (state.zhiMode === "more") showZhiCount(false);
}
// 太頻繁:伺服器要求冷靜 10 秒。沒送出的不算,畫面上的次數改回伺服器的數字
async function coolDown() {
state.zhiPending = 0;
state.zhiCoolUntil = Date.now() + ZHI_COOL_MS;
setZhiAuto(false);
toast(t("err.cooldown"));
try { state.today = await api("GET", "/api/checkin/today"); } catch { /* 下次重新整理會更新 */ }
if (state.zhiMode === "more") showZhiCount(false);
}
// 關掉分頁前把還沒送的那一下送出去(keepalive 讓請求在頁面關閉後繼續完成)
function flushZhiOnLeave() {
if (state.zhiPending <= 0 || state.zhiFlush) return; // 正在送的那個請求會自己完成
@@ -579,7 +742,12 @@ function flushZhiOnLeave() {
async function exitStage() {
const mode = state.zhiMode;
closeStage();
if (mode === "more") {
if (mode === "guest") {
state.guestOn = false; // 訪客按了等等再吱:回到首頁
showGuest();
} else if (mode === "more" && state.guestOn) {
renderGuestCard(false); // 小卡換成新的吱吱次數
} else if (mode === "more") {
$("done-stats").textContent = statsText(state.today); // 數字先更新,小卡等伺服器收到次數後再換
await flushZhi();
await refreshToday(); // 小卡換成新的吱吱次數
@@ -598,12 +766,14 @@ function bindCheckin() {
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 === "guest") zhiGuest(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"));
$("guest-zhi").addEventListener("click", () => { ensureGuest(); state.guestOn = true; openStage("guest"); });
$("share-btn").addEventListener("click", shareCard);
window.addEventListener("pagehide", flushZhiOnLeave);
@@ -615,8 +785,8 @@ function bindCheckin() {
// ---------- 畫面切換 ----------
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(); }
for (const v of ["view-checkin", "view-user", "view-upload", "view-images", "view-notices"]) $(v).hidden = v !== id;
if (id !== "view-checkin") { clearInterval(state.resetTimer); closeStage(); state.guestOn = false; }
}
// ---------- 投稿迷因圖 ----------
@@ -674,20 +844,21 @@ function bindUpload() {
if (file.size > SUBMIT_MAX_BYTES) { showError($("upload-error"), { code: "file_too_large" }); continue; }
const fd = new FormData();
fd.append("file", file);
fd.append("source", $("upload-source").value);
try {
await api("POST", "/api/submissions", fd);
ok++;
} catch (e) {
showError($("upload-error"), e);
if (e.code === "quota_exceeded") break;
if (e.code === "quota_exceeded" || e.code === "too_frequent") break;
}
}
if (ok) toast(t("upload.done", { n: ok }));
if (ok) { toast(t("upload.done", { n: ok })); $("upload-source").value = ""; }
await refreshUploads();
});
}
// ---------- 管理員審核(一張一張) ----------
// ---------- 管理圖片:審核投稿(一張一張)、新增、圖庫 ----------
async function loadReview() {
try {
@@ -705,17 +876,108 @@ async function loadReview() {
$("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]);
$("review-source").value = it.source || "";
} 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}`;
async function showImages() {
if (location.pathname !== "/images") history.replaceState(null, "", "/images"); // 1.0 的 /review
showView("view-images");
document.title = `${t("images.heading")} · ${SITE_TITLE}`;
if (!state.me?.is_admin) { location.replace("/"); return; }
await loadReview();
await Promise.all([loadReview(), loadGallery()]);
}
async function loadGallery() {
try {
state.gallery = (await api("GET", "/api/admin/memes")).items;
renderGallery();
} catch (e) {
if (e.status === 401 || e.status === 403) { location.replace("/"); return; }
toast(errText(e));
}
}
function renderGallery() {
const hidden = state.galleryHidden;
const shown = state.gallery.filter((m) => !m.hidden);
$("gallery-shown").textContent = t("images.shown", { n: shown.length });
$("gallery-hidden").textContent = t("images.hidden", { n: state.gallery.length - shown.length });
for (const [id, on] of [["gallery-shown", !hidden], ["gallery-hidden", hidden]]) {
$(id).classList.toggle("on", on);
$(id).setAttribute("aria-pressed", String(on));
}
const items = state.gallery.filter((m) => m.hidden === hidden);
$("gallery-empty").hidden = items.length > 0;
$("gallery").replaceChildren(...items.map(galleryItem));
}
function galleryItem(m) {
const box = document.createElement("div");
box.className = "meme-item";
const img = document.createElement("img");
img.src = m.thumb_url;
img.alt = m.name;
img.loading = "lazy";
img.title = m.name;
const used = document.createElement("span");
used.className = "hint";
used.textContent = t("images.used", { n: fmtNum(m.used) });
const source = document.createElement("input");
source.maxLength = 40;
source.value = m.source;
source.placeholder = t("source.placeholder");
source.setAttribute("aria-label", t("source.label"));
source.addEventListener("change", () => updateMeme(m.name, { source: source.value }, source));
const toggle = document.createElement("button");
toggle.type = "button";
toggle.textContent = t(m.hidden ? "images.show" : "images.hide");
toggle.addEventListener("click", () => updateMeme(m.name, { hidden: !m.hidden }, toggle));
box.append(img, used, source, toggle);
return box;
}
async function updateMeme(name, body, el) {
el.disabled = true;
try {
const m = await api("PUT", `/api/admin/memes/${encodeURIComponent(name)}`, body);
state.gallery = state.gallery.map((x) => (x.name === name ? m : x));
toast(t("images.saved"));
if ("hidden" in body) renderGallery();
} catch (e) {
toast(errText(e));
} finally {
el.disabled = false;
}
}
async function addImages(files) {
const total = files.length;
$("add-pick").classList.add("busy");
showError($("add-error"), null);
let ok = 0;
for (const [i, file] of files.entries()) { // 一張一張傳
$("add-progress").textContent = t("images.progress", { i: i + 1, n: total });
if (file.size > SUBMIT_MAX_BYTES) { showError($("add-error"), { code: "file_too_large" }); continue; }
const fd = new FormData();
fd.append("file", file);
fd.append("source", $("add-source").value);
try {
await api("POST", "/api/admin/memes", fd);
ok++;
} catch (e) {
showError($("add-error"), e);
if (e.code === "too_frequent" || e.code === "source_too_long") break;
}
}
$("add-progress").textContent = "";
$("add-pick").classList.remove("busy");
if (ok) { toast(t("images.added", { n: ok })); $("add-source").value = ""; }
state.galleryHidden = false;
await loadGallery();
}
function bindReview() {
@@ -724,8 +986,10 @@ function bindReview() {
const sid = $("review-item").dataset.id;
buttons.forEach((b) => { b.disabled = true; });
try {
await api("POST", `/api/admin/submissions/${sid}/${action}`);
const body = action === "approve" ? { source: $("review-source").value } : undefined;
await api("POST", `/api/admin/submissions/${sid}/${action}`, body);
toast(t(`review.${action}d`));
if (action === "approve") loadGallery();
} catch (e) {
// 已經審過(例如另一個分頁)就直接跳下一張
if (e.code !== "already_reviewed" && e.code !== "not_found") toast(errText(e));
@@ -736,6 +1000,79 @@ function bindReview() {
};
$("review-approve").addEventListener("click", () => decide("approve"));
$("review-reject").addEventListener("click", () => decide("reject"));
$("add-file").addEventListener("change", (ev) => {
const files = [...ev.target.files];
ev.target.value = "";
if (files.length) addImages(files);
});
for (const [id, hidden] of [["gallery-shown", false], ["gallery-hidden", true]]) {
$(id).addEventListener("click", () => { state.galleryHidden = hidden; renderGallery(); });
}
}
// ---------- 管理員通知匣 ----------
function noticeItem(n) {
const li = document.createElement("li");
li.classList.toggle("unread", n.unread);
const title = document.createElement("b");
title.textContent = t(`notice.${n.kind}`);
li.append(title);
if (n.count > 1) li.append(` ×${fmtNum(n.count)}`);
if (n.uid_str) {
const a = document.createElement("a");
a.href = `/u/${n.uid_str}`;
a.textContent = `${n.display_name} (UID ${n.uid_str})`;
li.append(" ", a);
}
if (n.detail) {
const d = document.createElement("div");
d.textContent = n.detail;
li.append(d);
}
const time = document.createElement("div");
time.className = "hint";
time.textContent = new Date(n.updated_at).toLocaleString(HTML_LANG[state.lang]);
li.append(time);
return li;
}
async function loadNotices(reset) {
try {
if (reset) state.noticeCount = 0;
const r = await api("GET", `/api/admin/notices?offset=${state.noticeCount}`);
if (reset) $("notices-list").replaceChildren();
$("notices-list").append(...r.items.map(noticeItem));
state.noticeCount += r.items.length;
$("notices-empty").hidden = state.noticeCount > 0;
$("notices-more").hidden = !r.items.length || state.noticeCount >= r.total;
if (reset && r.items.length) { // 打開就算看過了
state.me.unread_notices = (await api("POST", "/api/admin/notices/read", { upto: r.upto })).unread;
renderSidebar();
}
} catch (e) {
if (e.status === 401 || e.status === 403) { location.replace("/"); return; }
toast(errText(e));
}
}
async function showNotices() {
showView("view-notices");
document.title = `${t("notices.heading")} · ${SITE_TITLE}`;
if (!state.me?.is_admin) { location.replace("/"); return; }
await loadNotices(true);
}
function bindNotices() {
$("notices-more").addEventListener("click", () => withBusy($("notices-more"), () => loadNotices(false)));
$("flag-clear").addEventListener("click", () => withBusy($("flag-clear"), async () => {
try {
const uid = $("flag-box").dataset.uid;
await api("DELETE", `/api/admin/users/${uid}/flag`);
toast(t("flag.cleared"));
await showUser(uid);
} catch (e) { toast(errText(e)); }
}));
}
// ---------- 個人頁 ----------
@@ -752,6 +1089,9 @@ async function showUser(uid) {
// 管理員:下面多一個設定這個 UID 顏色與稱號的表單
const form = $("title-form");
form.hidden = !state.me?.is_admin;
$("user-edit").hidden = state.me?.uid !== u.uid; // 只能改自己的
$("flag-box").hidden = !u.flagged;
$("flag-box").dataset.uid = u.uid;
form.dataset.uid = u.uid;
$("title-text").value = u.title || "";
$("title-color").value = u.title_color || "#ff8a1f";
@@ -801,7 +1141,7 @@ function bindTitle() {
function bindProfile() {
const dialog = $("profile-dialog");
$("edit-profile").addEventListener("click", () => {
$("user-edit").addEventListener("click", () => {
const me = state.me;
$("edit-avatar").src = me.avatar_url || DEFAULT_AVATAR;
$("edit-name").value = me.display_name;
@@ -869,6 +1209,17 @@ function setPreview(on) {
$("preview-toggle").textContent = on ? t("profile.edit_back") : t("profile.preview");
}
// ---------- UID 搜尋 ----------
function bindSearch() {
$("uid-search").addEventListener("submit", (ev) => {
ev.preventDefault();
const n = $("uid-input").value.trim();
if (!/^\d{1,8}$/.test(n)) return toast(t("search.invalid"));
location.href = `/u/${n.padStart(8, "0")}`;
});
}
// ---------- 手機選單 ----------
function openMenu() { $("sidebar").classList.add("open"); }
@@ -890,7 +1241,8 @@ async function route() {
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();
if (location.pathname === "/images" || location.pathname === "/review") return showImages();
if (location.pathname === "/notices") return showNotices();
return showCheckin();
}
@@ -900,8 +1252,11 @@ async function init() {
bindCheckin();
bindProfile();
bindTitle();
bindInstall();
bindUpload();
bindReview();
bindNotices();
bindSearch();
$("menu-toggle").addEventListener("click", () => $("sidebar").classList.toggle("open"));
+53 -4
View File
@@ -1,5 +1,9 @@
{
"lang.label": "Language",
"search.label": "Search by UID",
"search.placeholder": "Enter UID",
"search.invalid": "Enter a UID of 1–8 digits",
"oss.label": "Source code",
"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.",
@@ -24,7 +28,7 @@
"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.login_first": "Not a mouse. A flying squirrel. Squeak every day and get a card.",
"checkin.ready": "You haven't squeaked today",
"checkin.success": "Squeaked!",
"checkin.done_today": "You've already squeaked today",
@@ -53,7 +57,7 @@
"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})",
"nav.review": "Manage images ({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",
@@ -64,7 +68,7 @@
"upload.status.pending": "Pending",
"upload.status.approved": "Added",
"upload.status.rejected": "Not accepted",
"review.heading": "Review submissions",
"review.heading": "Pending submissions",
"review.left": "{n} waiting",
"review.approve": "Approve",
"review.reject": "Reject",
@@ -95,5 +99,50 @@
"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"
"err.user_not_found": "User not found",
"guest.button": "Squeak as guest",
"guest.name": "Guest #{code}",
"guest.success": "Guest squeak done!",
"guest.card": "Guest card",
"about.yuzumi": "About Yuzumi",
"install.ios": "Add to your Home Screen for easier daily squeaks: tap Share, then Add to Home Screen",
"install.android": "Install the app for easier daily squeaks",
"install.generic": "Add to your home screen: browser menu, then Add to Home screen",
"install.button": "Install",
"install.close": "Close",
"nav.notices": "Notifications ({n})",
"notices.heading": "Notifications",
"notices.empty": "No notifications",
"notices.more": "Load more",
"notice.flagged": "Account flagged: click count is above the theoretical limit",
"notice.cooldown": "Too frequent, cooling down",
"notice.error": "Server error",
"notice.mail_failed": "Failed to send verification email",
"notice.admin_locked": "Admin sign-in locked",
"flag.text": "This account is flagged: its click count is above the theoretical limit.",
"flag.clear": "Remove flag",
"flag.cleared": "Flag removed",
"err.cooldown": "Too fast. Take a 10 second break",
"err.too_frequent": "Too many attempts. Please try again later",
"notice.admin_login": "Admin signed in",
"notice.mail_limit": "Site-wide email limit reached",
"user.edit": "Edit",
"images.heading": "Manage images",
"images.add": "Add images",
"images.add_hint": "Selected images are re-encoded and published right away, without review. The source applies to the whole batch. Up to 5MB each.",
"images.choose": "Choose images",
"images.progress": "Uploading {i} / {n}",
"images.added": "Added {n}",
"images.gallery": "Gallery",
"images.shown": "Published ({n})",
"images.hidden": "Unpublished ({n})",
"images.hide": "Unpublish",
"images.show": "Publish",
"images.used": "Drawn {n} times",
"images.empty": "No images",
"images.saved": "Updated",
"source.label": "Source (optional)",
"source.placeholder": "e.g. x@sthkm3",
"err.source_too_long": "Source can be up to 40 characters",
"err.unsupported_format": "Only JPG, PNG and WEBP are supported (no GIF)"
}
+53 -4
View File
@@ -1,5 +1,9 @@
{
"lang.label": "言語",
"search.label": "UID で検索",
"search.placeholder": "UID を入力",
"search.invalid": "1〜8 桁の数字で UID を入力してください",
"oss.label": "ソースコード",
"menu": "メニュー",
"auth.heading": "ログイン / 登録",
"auth.hint": "メールアドレスに認証コードを送ります。初回ログイン時にアカウントが作成されます。",
@@ -24,7 +28,7 @@
"profile.save": "保存",
"profile.cancel": "キャンセル",
"profile.saved": "保存しました",
"checkin.login_first": "ログインすると毎日 1 回チューチューして、カードがもらえます。",
"checkin.login_first": "ネズミじゃなくて、モモンガです。毎日チューチューしてカードをもらおう。",
"checkin.ready": "今日はまだチューチューしていません",
"checkin.success": "チューチュー成功!",
"checkin.done_today": "今日はもうチューチュー済みです",
@@ -53,7 +57,7 @@
"err.unknown": "エラーが発生しました",
"err.code_used": "この認証コードは使用済みです。しばらくしてから新しいコードをお使いください",
"nav.upload": "画像を投稿",
"nav.review": "投稿の審査({n})",
"nav.review": "画像の管理({n})",
"upload.heading": "画像を投稿",
"upload.hint": "カードに載せたい画像をアップロードしてください。審査に通るとガチャに追加されます。1日5枚まで(台湾時間 04:00 にリセット)、5MBまで。",
"upload.choose": "画像を選ぶ",
@@ -64,7 +68,7 @@
"upload.status.pending": "審査中",
"upload.status.approved": "採用",
"upload.status.rejected": "不採用",
"review.heading": "投稿の審査",
"review.heading": "審査待ちの投稿",
"review.left": "審査待ち {n} 枚",
"review.approve": "採用",
"review.reject": "却下",
@@ -95,5 +99,50 @@
"title.saved": "称号を更新しました",
"err.title_too_long": "称号は 16 文字までです",
"err.invalid_color": "色の形式が正しくありません",
"err.user_not_found": "ユーザーが見つかりません"
"err.user_not_found": "ユーザーが見つかりません",
"guest.button": "ゲストでチューチュー",
"guest.name": "ゲスト #{code}",
"guest.success": "ゲストチューチュー成功!",
"guest.card": "ゲストのカード",
"about.yuzumi": "Yuzumi について",
"install.ios": "ホーム画面に追加すると毎日チューチューしやすくなります:「共有」→「ホーム画面に追加」",
"install.android": "インストールすると毎日チューチューしやすくなります",
"install.generic": "ホーム画面に追加すると便利です:ブラウザのメニュー →「ホーム画面に追加」",
"install.button": "インストール",
"install.close": "閉じる",
"nav.notices": "通知({n})",
"notices.heading": "通知",
"notices.empty": "通知はありません",
"notices.more": "もっと読み込む",
"notice.flagged": "アカウントをマーク:チューチューの回数が理論上の上限を超えています",
"notice.cooldown": "チューチューが頻繁すぎるためクールダウン中",
"notice.error": "サーバーエラー",
"notice.mail_failed": "確認メールの送信に失敗",
"notice.admin_locked": "管理者ログインがロックされました",
"flag.text": "このアカウントはマークされています:チューチューの回数が理論上の上限を超えています。",
"flag.clear": "マークを解除",
"flag.cleared": "マークを解除しました",
"err.cooldown": "速すぎます。10 秒待ってからどうぞ",
"err.too_frequent": "操作が頻繁すぎます。しばらくしてからお試しください",
"notice.admin_login": "管理者がログインしました",
"notice.mail_limit": "メール送信数がサイト全体の上限に達しました",
"user.edit": "編集",
"images.heading": "画像の管理",
"images.add": "画像を追加",
"images.add_hint": "選んだ画像は再エンコードしてそのまま公開します(審査なし)。出典はこのまとめて全部に付きます。1 枚 5MB まで。",
"images.choose": "画像を選ぶ",
"images.progress": "アップロード中 {i} / {n}",
"images.added": "{n} 枚追加しました",
"images.gallery": "画像一覧",
"images.shown": "公開中({n})",
"images.hidden": "非公開({n})",
"images.hide": "非公開にする",
"images.show": "公開する",
"images.used": "{n} 回使用",
"images.empty": "画像がありません",
"images.saved": "更新しました",
"source.label": "出典(任意)",
"source.placeholder": "例:x@sthkm3",
"err.source_too_long": "出典は 40 文字までです",
"err.unsupported_format": "JPG・PNG・WEBP のみ対応しています(GIF は不可)"
}
+53 -4
View File
@@ -1,5 +1,9 @@
{
"lang.label": "언어",
"search.label": "UID로 검색",
"search.placeholder": "UID 입력",
"search.invalid": "1~8자리 숫자 UID를 입력해 주세요",
"oss.label": "오픈 소스 링크",
"menu": "메뉴",
"auth.heading": "로그인 / 가입",
"auth.hint": "이메일로 인증 코드를 보내드립니다. 처음 로그인하면 계정이 자동으로 만들어집니다.",
@@ -24,7 +28,7 @@
"profile.save": "저장",
"profile.cancel": "취소",
"profile.saved": "저장했습니다",
"checkin.login_first": "로그인하면 하루에 한 번 찍찍 출석하고 카드를 받을 수 있습니다.",
"checkin.login_first": "쥐가 아니라 날다람쥐예요. 매일 찍찍하고 카드를 받으세요.",
"checkin.ready": "오늘은 아직 찍찍하지 않았어요",
"checkin.success": "찍찍 성공!",
"checkin.done_today": "오늘은 이미 찍찍했어요",
@@ -53,7 +57,7 @@
"err.unknown": "오류가 발생했습니다",
"err.code_used": "이미 사용한 인증 코드입니다. 잠시 후 새 코드를 사용해 주세요",
"nav.upload": "이미지 투고",
"nav.review": "투고 심사 ({n})",
"nav.review": "이미지 관리 ({n})",
"upload.heading": "이미지 투고",
"upload.hint": "카드에 넣고 싶은 이미지를 올려 주세요. 심사를 통과하면 뽑기에 추가됩니다. 하루 최대 5장(대만 시간 04:00 초기화), 5MB까지.",
"upload.choose": "이미지 선택",
@@ -64,7 +68,7 @@
"upload.status.pending": "심사 중",
"upload.status.approved": "채택",
"upload.status.rejected": "미채택",
"review.heading": "투고 심사",
"review.heading": "심사 대기 투고",
"review.left": "심사 대기 {n}장",
"review.approve": "승인",
"review.reject": "거절",
@@ -95,5 +99,50 @@
"title.saved": "칭호를 업데이트했습니다",
"err.title_too_long": "칭호는 최대 16자입니다",
"err.invalid_color": "색상 형식이 올바르지 않습니다",
"err.user_not_found": "사용자를 찾을 수 없습니다"
"err.user_not_found": "사용자를 찾을 수 없습니다",
"guest.button": "게스트 찍찍",
"guest.name": "게스트 #{code}",
"guest.success": "게스트 찍찍 성공!",
"guest.card": "게스트 카드",
"about.yuzumi": "Yuzumi 소개",
"install.ios": "홈 화면에 추가하면 매일 찍찍하기 편해요: 「공유」→「홈 화면에 추가」",
"install.android": "설치하면 매일 찍찍하기 편해요",
"install.generic": "홈 화면에 추가하면 편해요: 브라우저 메뉴 →「홈 화면에 추가」",
"install.button": "설치",
"install.close": "닫기",
"nav.notices": "알림함 ({n})",
"notices.heading": "알림함",
"notices.empty": "알림이 없어요",
"notices.more": "더 보기",
"notice.flagged": "계정 표시됨: 찍찍 횟수가 이론상 한도를 넘었어요",
"notice.cooldown": "찍찍가 너무 잦아 쿨다운",
"notice.error": "서버 오류",
"notice.mail_failed": "인증 메일 전송 실패",
"notice.admin_locked": "관리자 로그인 잠김",
"flag.text": "이 계정은 표시되었어요: 찍찍 횟수가 이론상 한도를 넘었어요.",
"flag.clear": "표시 해제",
"flag.cleared": "표시를 해제했어요",
"err.cooldown": "너무 빨라요. 10초 쉬었다 하세요",
"err.too_frequent": "너무 자주 시도했어요. 잠시 후 다시 시도해 주세요",
"notice.admin_login": "관리자 로그인",
"notice.mail_limit": "메일 발송이 전체 한도에 도달했어요",
"user.edit": "편집",
"images.heading": "이미지 관리",
"images.add": "이미지 추가",
"images.add_hint": "고른 이미지는 다시 인코딩해서 심사 없이 바로 공개돼요. 출처는 이번에 고른 이미지 전체에 적용돼요. 한 장에 5MB까지.",
"images.choose": "이미지 선택",
"images.progress": "업로드 중 {i} / {n}",
"images.added": "{n}장 추가했어요",
"images.gallery": "이미지 목록",
"images.shown": "공개 중 ({n})",
"images.hidden": "비공개 ({n})",
"images.hide": "비공개",
"images.show": "공개",
"images.used": "{n}번 뽑힘",
"images.empty": "이미지가 없어요",
"images.saved": "업데이트했어요",
"source.label": "출처 (선택)",
"source.placeholder": "예: x@sthkm3",
"err.source_too_long": "출처는 40자까지예요",
"err.unsupported_format": "JPG, PNG, WEBP만 지원해요 (GIF 불가)"
}
+54 -5
View File
@@ -1,5 +1,9 @@
{
"lang.label": "语言",
"search.label": "用 UID 搜索",
"search.placeholder": "输入 UID",
"search.invalid": "请输入 1~8 位数字的 UID",
"oss.label": "开源链接",
"menu": "菜单",
"auth.heading": "登录 / 注册",
"auth.hint": "输入邮箱接收验证码,第一次登录会自动创建账号。",
@@ -24,7 +28,7 @@
"profile.save": "保存",
"profile.cancel": "取消",
"profile.saved": "已保存",
"checkin.login_first": "不是松鼠,是鼯鼠。登录后每天吱吱签到一次,领一张吱吱小卡。",
"checkin.login_first": "不是老鼠,是鼯鼠。每天吱吱后领一张吱咪小卡。",
"checkin.ready": "今天还没吱吱",
"checkin.success": "吱吱成功!",
"checkin.done_today": "今天已经吱吱过了",
@@ -53,9 +57,9 @@
"err.unknown": "发生错误,请稍后再试",
"err.code_used": "这组验证码已经用过,请稍后获取新的验证码",
"nav.upload": "投稿图片",
"nav.review": "审核投稿({n})",
"nav.review": "管理图片({n})",
"upload.heading": "投稿图片",
"upload.hint": "上传你觉得适合放上小卡的图,审核通过后就会加入抽卡。每天最多 5 张(台湾时间 04:00 重置),上限 5MB。",
"upload.hint": "上传你觉得适合放上吱咪小卡的图,审核通过后就会加入抽卡。每天最多 5 张(台湾时间 04:00 重置),上限 5MB。",
"upload.choose": "选择图片",
"upload.remaining": "今天还能上传 {n} / {max} 张",
"upload.done": "已上传 {n} 张,等待审核",
@@ -64,7 +68,7 @@
"upload.status.pending": "审核中",
"upload.status.approved": "已加入",
"upload.status.rejected": "未通过",
"review.heading": "审核投稿",
"review.heading": "待审投稿",
"review.left": "待审 {n} 张",
"review.approve": "同意",
"review.reject": "拒绝",
@@ -95,5 +99,50 @@
"title.saved": "已更新称号",
"err.title_too_long": "称号最多 16 个字",
"err.invalid_color": "颜色格式不正确",
"err.user_not_found": "找不到这个用户"
"err.user_not_found": "找不到这个用户",
"guest.button": "访客吱吱",
"guest.name": "访客 #{code}",
"guest.success": "访客吱吱成功!",
"guest.card": "访客的吱咪小卡",
"about.yuzumi": "关于Yuzumi",
"install.ios": "添加到主屏幕,每天吱吱更方便:点「分享」→「添加到主屏幕」",
"install.android": "安装到桌面,每天吱吱更方便",
"install.generic": "添加到主屏幕,每天吱吱更方便:浏览器菜单 →「添加到主屏幕」",
"install.button": "安装",
"install.close": "关闭",
"nav.notices": "通知箱({n})",
"notices.heading": "通知箱",
"notices.empty": "目前没有通知",
"notices.more": "加载更多",
"notice.flagged": "账号被标记:吱吱次数超过理论上限",
"notice.cooldown": "吱吱太频繁,进入冷静时间",
"notice.error": "服务器错误",
"notice.mail_failed": "验证邮件发送失败",
"notice.admin_locked": "管理员登录被锁定",
"flag.text": "这个账号被标记:吱吱次数超过理论上限。",
"flag.clear": "解除标记",
"flag.cleared": "已解除标记",
"err.cooldown": "吱太快了,冷静 10 秒再吱",
"err.too_frequent": "操作太频繁,请稍后再试",
"notice.admin_login": "管理员登录",
"notice.mail_limit": "发信数量到达全站上限",
"user.edit": "编辑",
"images.heading": "管理图片",
"images.add": "新增图片",
"images.add_hint": "选好的图会重新编码后直接上架,不用审核;出处会套用到这一批。每张上限 5MB。",
"images.choose": "选择图片",
"images.progress": "上传中 {i} / {n}",
"images.added": "已新增 {n} 张",
"images.gallery": "图库",
"images.shown": "上架中({n})",
"images.hidden": "已下架({n})",
"images.hide": "下架",
"images.show": "上架",
"images.used": "抽过 {n} 次",
"images.empty": "没有图片",
"images.saved": "已更新",
"source.label": "出处(选填)",
"source.placeholder": "例如 x@sthkm3",
"err.source_too_long": "出处最多 40 个字",
"err.unsupported_format": "只支持 JPG、PNG、WEBP(不收 GIF)"
}
+54 -5
View File
@@ -1,5 +1,9 @@
{
"lang.label": "語言",
"search.label": "用 UID 搜尋",
"search.placeholder": "輸入 UID",
"search.invalid": "請輸入 1~8 位數字的 UID",
"oss.label": "開源連結",
"menu": "選單",
"auth.heading": "登入 / 註冊",
"auth.hint": "輸入信箱收驗證碼,第一次登入會自動建立帳號。",
@@ -24,7 +28,7 @@
"profile.save": "儲存",
"profile.cancel": "取消",
"profile.saved": "已儲存",
"checkin.login_first": "不是松鼠,是鼯鼠。登入後每天吱吱簽到一次,領一張吱吱小卡。",
"checkin.login_first": "不是老鼠,是鼯鼠。每天吱吱後領一張吱咪小卡。",
"checkin.ready": "今天還沒吱吱",
"checkin.success": "吱吱成功!",
"checkin.done_today": "今天已經吱吱過了",
@@ -53,9 +57,9 @@
"err.unknown": "發生錯誤,請稍後再試",
"err.code_used": "這組驗證碼已經用過,請稍後取得新的驗證碼",
"nav.upload": "投稿圖片",
"nav.review": "審核投稿({n})",
"nav.review": "管理圖片({n})",
"upload.heading": "投稿圖片",
"upload.hint": "上傳你覺得適合放上吱吱小卡的圖,審核通過後就會加入抽卡。每天最多 5 張(台灣時間 04:00 重置),上限 5MB。",
"upload.hint": "上傳你覺得適合放上吱咪小卡的圖,審核通過後就會加入抽卡。每天最多 5 張(台灣時間 04:00 重置),上限 5MB。",
"upload.choose": "選擇圖片",
"upload.remaining": "今天還能上傳 {n} / {max} 張",
"upload.done": "已上傳 {n} 張,等待審核",
@@ -64,7 +68,7 @@
"upload.status.pending": "審核中",
"upload.status.approved": "已加入",
"upload.status.rejected": "未通過",
"review.heading": "審核投稿",
"review.heading": "待審投稿",
"review.left": "待審 {n} 張",
"review.approve": "同意",
"review.reject": "拒絕",
@@ -95,5 +99,50 @@
"title.saved": "已更新稱號",
"err.title_too_long": "稱號最多 16 個字",
"err.invalid_color": "顏色格式不正確",
"err.user_not_found": "找不到這個使用者"
"err.user_not_found": "找不到這個使用者",
"guest.button": "訪客吱吱",
"guest.name": "訪客 #{code}",
"guest.success": "訪客吱吱成功!",
"guest.card": "訪客的吱咪小卡",
"about.yuzumi": "關於Yuzumi",
"install.ios": "加到主畫面,每天吱吱更方便:點「分享」→「加入主畫面」",
"install.android": "安裝到桌面,每天吱吱更方便",
"install.generic": "加到主畫面,每天吱吱更方便:瀏覽器選單 →「加到主畫面」",
"install.button": "安裝",
"install.close": "關閉",
"nav.notices": "通知匣({n})",
"notices.heading": "通知匣",
"notices.empty": "目前沒有通知",
"notices.more": "載入更多",
"notice.flagged": "帳號被標記:吱吱次數超過理論上限",
"notice.cooldown": "吱吱太頻繁,進入冷靜時間",
"notice.error": "伺服器錯誤",
"notice.mail_failed": "驗證信寄送失敗",
"notice.admin_locked": "管理員登入被鎖定",
"flag.text": "這個帳號被標記:吱吱次數超過理論上限。",
"flag.clear": "解除標記",
"flag.cleared": "已解除標記",
"err.cooldown": "吱太快了,冷靜 10 秒再吱",
"err.too_frequent": "操作太頻繁,請稍後再試",
"notice.admin_login": "管理員登入",
"notice.mail_limit": "寄信數量到達全站上限",
"user.edit": "編輯",
"images.heading": "管理圖片",
"images.add": "新增圖片",
"images.add_hint": "選好的圖會重新編碼後直接上架,不用審核;出處會套用到這一批。每張上限 5MB。",
"images.choose": "選擇圖片",
"images.progress": "上傳中 {i} / {n}",
"images.added": "已新增 {n} 張",
"images.gallery": "圖庫",
"images.shown": "上架中({n})",
"images.hidden": "已下架({n})",
"images.hide": "下架",
"images.show": "上架",
"images.used": "抽過 {n} 次",
"images.empty": "沒有圖片",
"images.saved": "已更新",
"source.label": "出處(選填)",
"source.placeholder": "例如 x@sthkm3",
"err.source_too_long": "出處最多 40 個字",
"err.unsupported_format": "只支援 JPG、PNG、WEBP(不收 GIF)"
}
+87 -20
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>吱鼯計畫<!--BETA_TITLE--> — 你今天吱吱了嗎</title>
<title>吱鼯計畫 — 你今天吱吱了嗎</title>
<meta name="description" content="吱鼯計畫:你今天吱吱了嗎">
<meta name="theme-color" content="#1a0f06">
<link rel="icon" href="/favicon.ico" sizes="48x48">
@@ -19,7 +19,10 @@
<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>
<a href="/"><img class="logo" src="/assets/logo.png" alt="" width="32" height="32"><span class="brand-text"><b>吱鼯計畫</b><small data-i18n="site.tagline"></small></span></a>
<form id="uid-search" class="uid-search" role="search" novalidate>
<input id="uid-input" type="text" inputmode="numeric" enterkeyhint="go" maxlength="8" autocomplete="off" data-i18n-placeholder="search.placeholder" data-i18n-aria="search.label">
</form>
<button id="menu-toggle" class="icon-btn only-mobile" type="button" data-i18n-aria="menu">☰</button>
</div>
@@ -54,21 +57,28 @@
<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>
<a id="review-link" href="/images" hidden></a>
<a id="notices-link" href="/notices" hidden></a>
<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 class="sidebar-foot">
<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 class="oss-links">
<span data-i18n="oss.label"></span>
<a href="https://github.com/Sthkm3/ZhiwuProject" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://gitea.sthkm3.org/sthkm3/ZhiwuProject" target="_blank" rel="noopener noreferrer">Gitea</a>
</div>
</div>
</div>
</aside>
@@ -79,7 +89,11 @@
<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 class="row actions">
<button id="guest-login" class="primary" type="button" data-i18n="auth.heading"></button>
<button id="guest-zhi" type="button" data-i18n="guest.button"></button>
</div>
<p class="stats" id="guest-stats" hidden></p>
</div>
<!-- 今天還沒簽到、但先把全螢幕的吱吱畫面關掉(等等再吱)時顯示 -->
<div id="checkin-ready" class="center" hidden>
@@ -97,8 +111,15 @@
<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>
<button id="done-login" type="button" data-i18n="auth.heading" hidden></button>
</div>
<p class="stats" id="done-stats"></p>
<!-- 手機、還沒安裝到桌面時才顯示 -->
<div id="install-hint" class="install-hint" hidden>
<span id="install-text"></span>
<button id="install-btn" class="primary" type="button" data-i18n="install.button" hidden></button>
<button id="install-close" class="icon-btn" type="button" data-i18n-aria="install.close">×</button>
</div>
</div>
<p class="hint center-text" id="next-reset" hidden></p>
</section>
@@ -108,40 +129,80 @@
<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>
<input type="file" id="upload-file" accept="image/jpeg,image/png,image/webp" multiple hidden>
<span class="muted" id="upload-quota"></span>
</div>
<label class="source-field"><span data-i18n="source.label"></span>
<input id="upload-source" maxlength="40" autocomplete="off" data-i18n-placeholder="source.placeholder">
</label>
<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>
<section id="view-images" hidden>
<h1 data-i18n="images.heading"></h1>
<h2><span data-i18n="review.heading"></span> <small class="muted" id="review-left"></small></h2>
<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>
<label class="source-field"><span data-i18n="source.label"></span>
<input id="review-source" maxlength="40" autocomplete="off" data-i18n-placeholder="source.placeholder">
</label>
<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>
<p class="muted" id="review-empty" data-i18n="review.empty" hidden></p>
<h2 data-i18n="images.add"></h2>
<p class="hint" data-i18n="images.add_hint"></p>
<label class="source-field"><span data-i18n="source.label"></span>
<input id="add-source" maxlength="40" autocomplete="off" data-i18n-placeholder="source.placeholder">
</label>
<div class="row upload-bar">
<label class="button primary" for="add-file" id="add-pick" data-i18n="images.choose"></label>
<input type="file" id="add-file" accept="image/jpeg,image/png,image/webp" multiple hidden>
<span class="muted" id="add-progress"></span>
</div>
<p class="error" id="add-error" hidden></p>
<h2 data-i18n="images.gallery"></h2>
<div class="row seg">
<button type="button" id="gallery-shown" class="on" aria-pressed="true"></button>
<button type="button" id="gallery-hidden" aria-pressed="false"></button>
</div>
<p class="hint" id="gallery-empty" data-i18n="images.empty" hidden></p>
<div class="meme-grid" id="gallery"></div>
</section>
<section id="view-notices" hidden>
<h1 data-i18n="notices.heading"></h1>
<p class="hint" id="notices-empty" data-i18n="notices.empty" hidden></p>
<ul class="notice-list" id="notices-list"></ul>
<button type="button" id="notices-more" data-i18n="notices.more" hidden></button>
</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>
<button type="button" id="user-edit" data-i18n="user.edit" hidden></button>
<div class="uid" id="user-uid"></div>
<p class="stats" id="user-stats"></p>
<div class="bio" id="user-bio"></div>
<p class="hint" id="user-joined"></p>
<!-- 管理員才看得到:這個帳號的吱吱次數超過理論上限 -->
<div id="flag-box" class="flag-box" hidden>
<p class="error" data-i18n="flag.text"></p>
<button type="button" id="flag-clear" data-i18n="flag.clear"></button>
</div>
<!-- 管理員才看得到:指定這個 UID 的顏色與稱號 -->
<form id="title-form" class="title-form" hidden novalidate>
<h2 data-i18n="title.heading"></h2>
@@ -165,6 +226,12 @@
<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>
<footer class="site-footer">
<span data-i18n="about.yuzumi"></span><br>
<a href="https://official-website.meridianproject.tw/talents/yuzumi" target="_blank" rel="noopener noreferrer">official-website.meridianproject.tw/talents/yuzumi</a><br>
<span class="version">v<!--APP_VERSION--></span>
</footer>
</main>
</div>
@@ -175,7 +242,7 @@
<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>
<input type="file" id="avatar-file" accept="image/jpeg,image/png,image/webp" hidden>
<p class="hint" data-i18n="profile.avatar_hint"></p>
</div>
</div>
+13 -2
View File
@@ -1,12 +1,23 @@
{
"id": "/",
"name": "吱鼯計畫",
"short_name": "吱鼯計畫",
"description": "你今天吱吱了嗎",
"start_url": "/",
"scope": "/",
"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" }
{
"src": "/assets/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/assets/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+70 -10
View File
@@ -94,19 +94,19 @@ button.link:disabled { color: var(--muted); }
.avatar { border-radius: 50%; object-fit: cover; background: var(--panel-2); width: 96px; height: 96px; }
.avatar.large { width: 160px; height: 160px; }
.beta { font-size: 12px; font-weight: 600; color: var(--muted); }
/* UID 與稱號:管理員預設黃底(和 server/app/titles.py TIER_COLORS 一致);
/* UID 與稱號:每個 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 {
.uid, .title-badge {
display: inline-block;
font-weight: 700;
font-variant-numeric: tabular-nums;
padding: 2px 10px;
border-radius: 8px;
margin-top: 2px;
background: #c9a27a;
color: #2a1400;
}
.uid.tier-admin, .title-badge.tier-admin { background: #ffd166; color: #2a1400; }
@@ -125,10 +125,54 @@ button.link:disabled { color: var(--muted); }
.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; }
/* UID 搜尋:電腦在品牌下面一整行;手機在 ☰ 左邊(見下面的 @media) */
.brand { flex-wrap: wrap; gap: 12px; }
.uid-search { flex: 1 1 100%; }
.uid-search input { padding: 8px 12px; }
/* 側欄最底下:語言與開源連結 */
.sidebar-foot { margin-top: auto; display: flex; flex-direction: column; gap: 12px; }
.oss-links { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; font-size: 14px; color: var(--muted); }
.oss-links span { width: 100%; }
/* ---------- 主畫面 ---------- */
#main { flex: 1; padding: 40px 24px; display: flex; justify-content: center; }
#main { flex: 1; min-width: 0; padding: 40px 24px 24px; display: flex; flex-direction: column; align-items: center; }
/* 每一頁最底下:關於 Yuzumi */
.site-footer {
margin-top: auto;
padding-top: 48px;
text-align: center;
font-size: 13px;
line-height: 1.7;
color: var(--muted);
overflow-wrap: anywhere;
}
.site-footer .version { font-size: 12px; opacity: .7; }
/* 管理員:通知匣、被標記的帳號 */
.notice-list { list-style: none; margin: 16px 0; padding: 0; width: min(720px, 100%); display: flex; flex-direction: column; gap: 10px; }
.notice-list li { padding: 12px 16px; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); overflow-wrap: anywhere; }
.notice-list li.unread { border-color: var(--accent); }
.flag-box { width: 100%; margin-top: 12px; padding: 12px 16px; border: 1px solid var(--error); border-radius: var(--radius); }
/* 手機:提示可以安裝到桌面 */
.install-hint {
width: 100%;
display: flex;
align-items: center;
gap: 10px;
text-align: left;
font-size: 14px;
padding: 10px 12px 10px 16px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.install-hint span { flex: 1; }
.install-hint .primary { padding: 6px 16px; white-space: nowrap; }
.install-hint .icon-btn { border: none; background: none; color: var(--muted); padding: 0 6px; }
#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; }
@@ -214,9 +258,11 @@ body.zhi-on { overflow: hidden; }
-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;
/* 晚 100ms 才出現:等門的圖先畫出來。每次重新顯示(display 變回來)動畫都會重跑 */
animation: zhi-show 1ms 100ms both, zhi-breathe 1.4s 100ms ease-in-out infinite;
}
.zhi-stage.playing .zhi-hint { display: none; }
@keyframes zhi-show { from { opacity: 0; } to { opacity: 1; } }
@keyframes zhi-breathe {
0%, 100% { transform: translate(-50%, -50%) scale(1); }
50% { transform: translate(-50%, -50%) scale(1.08); }
@@ -285,7 +331,8 @@ body.zhi-on { overflow: hidden; }
}
@media (prefers-reduced-motion: reduce) {
.particle { display: none; }
.zhi-hint, .zhi-count.bump { animation: none; }
.zhi-hint { animation: zhi-show 1ms 100ms both; }
.zhi-count.bump { animation: none; }
}
.checkin-msg { font-size: 22px; font-weight: 700; margin: 0; }
@@ -312,6 +359,15 @@ body.zhi-on { overflow: hidden; }
}
.sub-status.approved { background: #2f9e5a; color: #fff; }
.sub-status.rejected { background: #6b3a3a; color: #fff; }
.source-field { max-width: 360px; width: 100%; margin-top: 12px; text-align: left; }
#view-images h2 { margin-top: 32px; }
.seg { gap: 8px; margin-bottom: 12px; }
.seg button.on { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 700; }
.meme-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: 14px; width: 100%; }
.meme-item { display: flex; flex-direction: column; gap: 6px; padding: 8px; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); }
.meme-item img { width: 100%; aspect-ratio: 1; object-fit: contain; border-radius: 8px; background: var(--panel-2); }
.meme-item input { padding: 6px 8px; font-size: 14px; }
.meme-item button { padding: 6px 12px; font-size: 14px; }
.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; }
@@ -373,9 +429,13 @@ dialog h2 { margin: 0 0 4px; }
.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; }
.brand { flex-wrap: nowrap; }
.uid-search { flex: 1 1 0; min-width: 80px; max-width: 160px; margin-left: auto; }
.brand a, .brand-text { min-width: 0; } /* 螢幕太窄時標語用「…」截斷,不擠掉搜尋框 */
.brand-text small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#sidebar:not(.open) #sidebar-body { display: none; }
#sidebar-body { padding-bottom: 8px; }
#main { padding: 24px 16px; }
#main { padding: 24px 16px 20px; }
.big-logo { margin-top: 4vh; }
.big-mark { font-size: 48px; }
}