優化顯示與增強反作弊

This commit is contained in:
Sahik committed 2026-11-25 14:28:56 +08:00
1 parent d2be83ee77
commit 5bd77d2599
30 files changed
+764 -106

No files matched your search

+2 -1
View File
@@ -9,4 +9,5 @@ image
icon
tools
media-src
Version.md
Version.md
make.md
-2
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
+3 -20
View File
@@ -21,7 +21,7 @@
## 功能
- **吱咪小卡**:每次簽到從圖庫隨機抽一張圖,加上你的名稱、大頭貼、簽到天數和吱吱次數。分享連結貼到 Discord、X、LINE 會出現小卡預覽
- **繼續吱吱**:簽到完還想吱,可以回去一直吱。每吱完一次才能吱下一次,一秒最多算一次
- **繼續吱吱**:簽到完還想吱,可以回去一直吱。每吱完一次才能吱下一次,1.5 秒最多算一次
- **全自動吱吱**:懶得點的話,繼續吱吱畫面下方有開關,打開就會自己一直吱
- **訪客吱吱**:不用登入就能吱,會拿到一張「訪客 #四位亂碼」的小卡。代號和次數只記在你自己的瀏覽器,伺服器不會記;之後登入的話帳號從頭算,訪客的次數不會帶過去
- **兩個數字分開算**:簽到天數一天只加一次;吱吱次數每吱一下加一次
@@ -39,26 +39,9 @@
- 訪客吱吱不會在伺服器留下任何紀錄
- 上傳的圖片會重新編碼並移除 EXIF(包含 GPS)資訊
## 更新紀錄
## 想改一個自己的
- **1.0.1**:新增訪客吱吱;每個 UID 都有底色;每頁最下方加上 Yuzumi 官方頁面連結;手機可以加到主畫面
- **1.0.0**:第一版。吱吱簽到、吱咪小卡、繼續吱吱、全自動吱吱、投稿圖片、稱號
## 自己架一個
需要 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),新增圖片不用重啟。
也可以不 build,直接拉現成的映像:`docker pull gitea.sthkm3.org/sthkm3/zhiwuproject:1.0.1`
clone 之後要改哪裡、怎麼部署:[make.md](make.md)
## 技術
-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:-}
+87
View File
@@ -0,0 +1,87 @@
# 改一個自己的
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`,這兩個要掛出來並備份。程式只能跑一個 worker,限流和冷靜時間都記在記憶體。
+2
View File
@@ -0,0 +1,2 @@
"""版本號只寫在這裡,頁尾會顯示;發布新版本時改這一行。"""
__version__ = "1.0.2"
+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}")
+44
View File
@@ -0,0 +1,44 @@
"""反作弊:每小時檢查一次有沒有帳號的吱吱次數超過理論上限。
理論上限 = 從最初架設(meta.server_start)到現在的秒數 / ZHI_GAP。
超過就標記(users.flagged_at)並通知管理員;只是標記,不扣次數也不封鎖。
"""
import asyncio
from . import clock, config, db, 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)
+4 -2
View File
@@ -12,7 +12,7 @@ from collections import defaultdict, deque
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel
from . import clock, config, db, mailer, totp
from . import clock, config, db, 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
@@ -93,6 +93,7 @@ def request_code(body: CodeRequest, request: Request, conn: sqlite3.Connection =
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 +127,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:
+3 -4
View File
@@ -171,8 +171,7 @@ def draw(lang: str, meme: str | None, name: str, avatar: Image.Image | None, bad
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
@@ -262,11 +261,11 @@ def guest_meme(code: str, day: str) -> str | 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 not n.isascii() or not n.isdigit() or int(n) > config.GUEST_CLICKS_MAX:
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)
key = (code, clicks, lang, day, meme, CARD_VERSION, config.BETA)
key = (code, clicks, lang, day, meme, CARD_VERSION)
with _guest_lock:
png = _guest_cache.get(key)
if png is None:
+32 -11
View File
@@ -1,12 +1,14 @@
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 .db import get_db, transaction
from .deps import current_user, fail
from .i18n import t
@@ -100,17 +102,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 +137,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]
+15 -6
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"
@@ -74,10 +72,21 @@ 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 每分鐘最多畫幾張(從快取拿的不算)
+19 -1
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
);
@@ -63,6 +64,19 @@ CREATE TABLE IF NOT EXISTS submissions (
);
CREATE INDEX IF NOT EXISTS submissions_uid_day ON submissions(uid, day);
CREATE INDEX IF NOT EXISTS submissions_status ON submissions(status, id);
-- 管理員通知匣(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,6 +104,9 @@ 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()
@@ -100,6 +117,7 @@ _USER_COLUMNS = {
"clicks": "INTEGER NOT NULL DEFAULT 0",
"title": "TEXT NOT NULL DEFAULT ''",
"title_color": "TEXT NOT NULL DEFAULT ''",
"flagged_at": "INTEGER",
}
+21 -5
View File
@@ -1,3 +1,4 @@
import asyncio
import hashlib
import mimetypes
from contextlib import asynccontextmanager
@@ -7,7 +8,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, 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"),
@@ -26,7 +27,10 @@ async def lifespan(app: FastAPI):
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)
@@ -41,7 +45,13 @@ async def guard(request: Request, call_next):
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)
@@ -52,10 +62,16 @@ async def guard(request: Request, call_next):
return response
for module in (auth, users, checkin, card, share, submissions):
for module in (auth, users, checkin, card, share, submissions, 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 +91,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"})
@@ -89,4 +104,5 @@ 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("/notices", index, methods=["GET", "HEAD"], include_in_schema=False)
app.mount("/assets", StaticFiles(directory=config.WEB_DIR, check_dir=False), name="assets")
+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 = "") -> None:
"""自己開一條連線;不要在交易裡呼叫(會等自己的寫入鎖)。"""
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 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)}
+4 -3
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
@@ -47,7 +47,7 @@ PAGE = """<!DOCTYPE html>
<body>
<img src="{image_path}" alt="{title}">
<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></footer>
<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>"""
@@ -66,7 +66,7 @@ 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),
@@ -74,4 +74,5 @@ def share_page(uid: int, day: str, conn: sqlite3.Connection = Depends(get_db)):
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__,
)
+1
View File
@@ -195,6 +195,7 @@ def approve(sid: int, admin=Depends(admin_user), conn: sqlite3.Connection = Depe
os.close(fd)
try:
shutil.copyfile(src, tmp)
os.chmod(tmp, 0o644) # mkstemp 是 0600,圖庫要讓 NAS 上的其他帳號也讀得到
os.replace(tmp, config.MEME_DIR / name)
except BaseException:
Path(tmp).unlink(missing_ok=True)
+20 -4
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, 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
@@ -175,6 +176,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 +187,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 的顏色與稱號 ----------
+3 -1
View File
@@ -4,7 +4,7 @@ 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, mailer, totp
ADMIN_LOGIN = "sthkm3"
ADMIN_TOTP = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" # 測試用密鑰
@@ -46,6 +46,8 @@ def client(tmp_path, monkeypatch, fake_clock, sent):
monkeypatch.setattr(config, "ADMIN_LOGIN", ADMIN_LOGIN)
monkeypatch.setattr(config, "ADMIN_TOTP", ADMIN_TOTP)
auth._ip_hits.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
+202
View File
@@ -0,0 +1,202 @@
"""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_LOGIN, admin_code, login
from .test_zhi import frozen # noqa: F401 (fixture)
def as_admin(client, fake_clock):
client.cookies.clear()
r = client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": admin_code(fake_clock)})
assert r.status_code == 200, r.text
def zhi(client):
return client.post("/api/zhi", json={"n": 1})
def kinds(client):
return [n["kind"] for n in client.get("/api/admin/notices").json()["items"]]
# ---------- 冷靜時間 ----------
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):
client.post("/api/auth/verify", json={"email": ADMIN_LOGIN, "code": "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 == 2
@@ -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())
# 同一天可以重新簽到
+17 -7
View File
@@ -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
+100 -9
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 = {
@@ -31,6 +32,8 @@ const state = {
zhiTimer: null,
zhiAuto: false, // 全自動吱吱開著:播完自動接下一次
zhiAutoTimer: null,
zhiCoolUntil: 0, // 冷靜到什麼時候
noticeCount: 0, // 通知匣已經載入幾則
zhiLastAt: 0, // 上一次繼續吱吱的時間
zhiPlay: 0, // 第幾次播放;離開再進來時,舊的那次播完不能動到新的
zhiFlush: null, // 正在送次數的 Promise(離開時等它送完)
@@ -157,7 +160,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) {
@@ -624,7 +631,8 @@ 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;
@@ -660,7 +668,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);
@@ -674,7 +682,7 @@ function zhiAutoTick() {
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 把還沒送的次數一下一下送給伺服器(伺服器一個帳號一秒只收一下)
// 把還沒送的次數一下一下送給伺服器(伺服器一個帳號 1.5 秒只收一下)
function flushZhi() {
clearTimeout(state.zhiTimer);
state.zhiTimer = null;
@@ -683,22 +691,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; // 正在送的那個請求會自己完成
@@ -758,7 +780,7 @@ function bindCheckin() {
// ---------- 畫面切換 ----------
function showView(id) {
for (const v of ["view-checkin", "view-user", "view-upload", "view-review"]) $(v).hidden = v !== id;
for (const v of ["view-checkin", "view-user", "view-upload", "view-review", "view-notices"]) $(v).hidden = v !== id;
if (id !== "view-checkin") { clearInterval(state.resetTimer); closeStage(); state.guestOn = false; }
}
@@ -881,6 +903,71 @@ function bindReview() {
$("review-reject").addEventListener("click", () => decide("reject"));
}
// ---------- 管理員通知匣 ----------
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)); }
}));
}
// ---------- 個人頁 ----------
async function showUser(uid) {
@@ -895,6 +982,8 @@ async function showUser(uid) {
// 管理員:下面多一個設定這個 UID 顏色與稱號的表單
const form = $("title-form");
form.hidden = !state.me?.is_admin;
$("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";
@@ -1034,6 +1123,7 @@ async function route() {
if (m) return showUser(m[1]);
if (location.pathname === "/upload") return showUpload();
if (location.pathname === "/review") return showReview();
if (location.pathname === "/notices") return showNotices();
return showCheckin();
}
@@ -1046,6 +1136,7 @@ async function init() {
bindInstall();
bindUpload();
bindReview();
bindNotices();
$("menu-toggle").addEventListener("click", () => $("sidebar").classList.toggle("open"));
+14 -1
View File
@@ -105,5 +105,18 @@
"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"
"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"
}
+14 -1
View File
@@ -105,5 +105,18 @@
"install.android": "インストールすると毎日チューチューしやすくなります",
"install.generic": "ホーム画面に追加すると便利です:ブラウザのメニュー →「ホーム画面に追加」",
"install.button": "インストール",
"install.close": "閉じる"
"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 秒待ってからどうぞ"
}
+14 -1
View File
@@ -105,5 +105,18 @@
"install.android": "설치하면 매일 찍찍하기 편해요",
"install.generic": "홈 화면에 추가하면 편해요: 브라우저 메뉴 →「홈 화면에 추가」",
"install.button": "설치",
"install.close": "닫기"
"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초 쉬었다 하세요"
}
+14 -1
View File
@@ -105,5 +105,18 @@
"install.android": "安装到桌面,每天吱吱更方便",
"install.generic": "添加到主屏幕,每天吱吱更方便:浏览器菜单 →「添加到主屏幕」",
"install.button": "安装",
"install.close": "关闭"
"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 秒再吱"
}
+14 -1
View File
@@ -105,5 +105,18 @@
"install.android": "安裝到桌面,每天吱吱更方便",
"install.generic": "加到主畫面,每天吱吱更方便:瀏覽器選單 →「加到主畫面」",
"install.button": "安裝",
"install.close": "關閉"
"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 秒再吱"
}
+17 -3
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,7 @@
<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>
<button id="menu-toggle" class="icon-btn only-mobile" type="button" data-i18n-aria="menu">☰</button>
</div>
@@ -55,6 +55,7 @@
<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>
<a id="notices-link" href="/notices" hidden></a>
<button type="button" class="link" id="edit-profile" data-i18n="profile.edit"></button>
<button type="button" class="link" id="logout" data-i18n="auth.logout"></button>
</nav>
@@ -145,6 +146,13 @@
<p class="center-text muted" id="review-empty" data-i18n="review.empty" hidden></p>
</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">
@@ -153,6 +161,11 @@
<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>
@@ -179,7 +192,8 @@
<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>
<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>
+13 -4
View File
@@ -94,8 +94,6 @@ 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 與稱號:每個 UID 都有底色。一般使用者淺咖啡、管理員黃(和 server/app/titles.py TIER_COLORS 一致);
管理員指定的顏色由 app.js 直接寫在 style 上 */
.uid-wrap { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 6px; }
@@ -143,6 +141,14 @@ button.link:disabled { 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%;
@@ -244,9 +250,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); }
@@ -315,7 +323,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; }