From d4377a47e496bbf4f6ae7eba3999c8744b89ca87 Mon Sep 17 00:00:00 2001 From: sthkm3 Date: Wed, 2 Dec 2026 17:25:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=A6=9C=E5=96=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + server/app/__init__.py | 2 +- server/app/config.py | 3 + server/app/leaderboard.py | 52 ++++++++++++++++ server/app/main.py | 6 +- server/tests/test_leaderboard.py | 101 +++++++++++++++++++++++++++++++ web/app.js | 55 ++++++++++++++++- web/i18n/en.json | 11 +++- web/i18n/ja.json | 11 +++- web/i18n/ko.json | 11 +++- web/i18n/zh-CN.json | 11 +++- web/i18n/zh-TW.json | 11 +++- web/index.html | 20 ++++++ web/style.css | 29 +++++++++ 14 files changed, 315 insertions(+), 9 deletions(-) create mode 100644 server/app/leaderboard.py create mode 100644 server/tests/test_leaderboard.py diff --git a/README.md b/README.md index 690ef6c..0470e1f 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ - **全自動吱吱**:懶得點的話,繼續吱吱畫面下方有開關,打開就會自己一直吱 - **訪客吱吱**:不用登入就能吱,會拿到一張「訪客 #四位亂碼」的小卡。代號和次數只記在你自己的瀏覽器,伺服器不會記;之後登入的話帳號從頭算,訪客的次數不會帶過去 - **兩個數字分開算**:簽到天數一天只加一次;吱吱次數每吱一下加一次 +- **全服總榜**:選單裡的「全服總榜」,最上面是全伺服器的總簽到次數和總吱吱次數,下面是簽到次數和吱吱次數的前 10 名(不算管理員),沒登入也能看 - **投稿圖片**:可以上傳你覺得適合放上小卡的圖,每天最多 5 張,可以附上出處;管理員審核通過後加入圖庫,出處會小小地寫在小卡圖片的右下角 - **個人頁**:名稱、大頭貼、自我介紹(支援 Markdown),在自己的個人頁按「編輯」修改 - **稱號**:管理員可以幫指定的 UID 加上顏色和稱號 diff --git a/server/app/__init__.py b/server/app/__init__.py index 6b83ed6..f011317 100644 --- a/server/app/__init__.py +++ b/server/app/__init__.py @@ -1,2 +1,2 @@ """版本號只寫在這裡,頁尾會顯示;發布新版本時改這一行。""" -__version__ = "1.2.0" +__version__ = "1.3.0" diff --git a/server/app/config.py b/server/app/config.py index f57d304..90707a7 100644 --- a/server/app/config.py +++ b/server/app/config.py @@ -105,6 +105,9 @@ COOL_SECONDS = 10 # 反作弊:多久檢查一次吱吱次數有沒有超過理論上限(見 anticheat.py) CHECK_INTERVAL = 3600 +# 全服總榜:每個排行榜列前幾名(leaderboard.py) +LEADERBOARD_SIZE = 10 + # 管理員通知匣:同樣的通知 NOTICE_MERGE 秒內併成一則,最多留 NOTICE_KEEP 則 NOTICE_MERGE = 3600 NOTICE_KEEP = 500 diff --git a/server/app/leaderboard.py b/server/app/leaderboard.py new file mode 100644 index 0000000..92bc5ad --- /dev/null +++ b/server/app/leaderboard.py @@ -0,0 +1,52 @@ +"""全服總榜:總簽到次數、總吱吱次數,加上兩個排行榜。 + +- 不算管理員(UID 0),總數也不算 +- 被反作弊標記的帳號照常上榜;管理員清掉作弊者的數字後,下一次讀取就會反映(不快取,每次即時算) +- 數字是 0 的帳號不上榜;同分同名次(1、1、3),同分時 UID 小的排前面 +""" +import sqlite3 + +from fastapi import APIRouter, Depends + +from . import config +from .db import get_db +from .titles import badge, fmt_uid +from .users import avatar_url + +router = APIRouter() + + +def _entries(rows: list[sqlite3.Row]) -> list[dict]: + out, rank, prev = [], 0, None + for i, r in enumerate(rows, 1): + if r["value"] != prev: + rank, prev = i, r["value"] + out.append({ + "rank": rank, + "uid": r["uid"], + "uid_str": fmt_uid(r["uid"]), + "display_name": r["display_name"], + "avatar_url": avatar_url(r), + **badge(r), + "value": r["value"], + }) + return out + + +@router.get("/api/leaderboard") +def leaderboard(conn: sqlite3.Connection = Depends(get_db)): + admin, size = config.ADMIN_UID, config.LEADERBOARD_SIZE + total_checkins = conn.execute("SELECT COUNT(*) FROM checkins WHERE uid != ?", (admin,)).fetchone()[0] + total_clicks = conn.execute("SELECT COALESCE(SUM(clicks), 0) FROM users WHERE uid != ?", (admin,)).fetchone()[0] + by_days = conn.execute( + "SELECT u.*, COUNT(*) AS value FROM users u JOIN checkins c ON c.uid = u.uid " + "WHERE u.uid != ? GROUP BY u.uid ORDER BY value DESC, u.uid ASC LIMIT ?", (admin, size)).fetchall() + by_clicks = conn.execute( + "SELECT *, clicks AS value FROM users WHERE uid != ? AND clicks > 0 " + "ORDER BY clicks DESC, uid ASC LIMIT ?", (admin, size)).fetchall() + return { + "total_checkins": total_checkins, + "total_clicks": total_clicks, + "by_days": _entries(by_days), + "by_clicks": _entries(by_clicks), + } diff --git a/server/app/main.py b/server/app/main.py index 1bfe867..b5ba0e4 100644 --- a/server/app/main.py +++ b/server/app/main.py @@ -9,7 +9,8 @@ from fastapi import FastAPI, Request from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles -from . import __version__, anticheat, auth, card, checkin, config, db, limits, memes, notices, share, submissions, users +from . import (__version__, anticheat, auth, card, checkin, config, db, leaderboard, 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"), @@ -82,7 +83,7 @@ async def guard(request: Request, call_next): app.add_middleware(limits.BodyLimit) # 最後加的在最外層 -for module in (auth, users, checkin, card, share, submissions, memes, notices): +for module in (auth, users, checkin, card, share, submissions, memes, notices, leaderboard): app.include_router(module.router) @@ -126,4 +127,5 @@ app.add_api_route("/upload", index, methods=["GET", "HEAD"], include_in_schema=F 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.add_api_route("/leaderboard", index, methods=["GET", "HEAD"], include_in_schema=False) app.mount("/assets", StaticFiles(directory=config.WEB_DIR, check_dir=False), name="assets") diff --git a/server/tests/test_leaderboard.py b/server/tests/test_leaderboard.py new file mode 100644 index 0000000..49a7d56 --- /dev/null +++ b/server/tests/test_leaderboard.py @@ -0,0 +1,101 @@ +"""全服總榜:總簽到次數、總吱吱次數、兩個前 10 名排行榜,不算管理員。""" +from app import admin, config, db + +from .conftest import admin_code, admin_verify, login + + +def seed(users: dict[int, tuple[int, int]], flagged: set[int] = frozenset()) -> None: + """直接寫資料庫:{uid: (簽到天數, 吱吱次數)}。""" + conn = db.connect() + for uid, (days, clicks) in users.items(): + conn.execute( + "INSERT INTO users(uid, email, display_name, lang, clicks, flagged_at, created_at) " + "VALUES (?, ?, ?, 'zh-TW', ?, ?, 0)", + (uid, f"u{uid}@example.com", f"鼠{uid}", clicks, 1 if uid in flagged else None)) + for d in range(days): + conn.execute("INSERT INTO checkins(uid, day, created_at) VALUES (?, ?, 0)", (uid, f"2026-10-{d + 1:02d}")) + conn.close() + + +def board(client): + r = client.get("/api/leaderboard") + assert r.status_code == 200, r.text + return r.json() + + +def ranks(entries): + return [(e["uid"], e["rank"], e["value"]) for e in entries] + + +def test_empty(client): + assert board(client) == {"total_checkins": 0, "total_clicks": 0, "by_days": [], "by_clicks": []} + + +def test_order_ties_and_totals(client): + seed({1: (3, 10), 2: (5, 40), 3: (3, 40), 4: (1, 5), 5: (0, 0)}) + b = board(client) + assert b["total_checkins"] == 12 and b["total_clicks"] == 95 + # 同分同名次,同分時 UID 小的在前;0 的不上榜 + assert ranks(b["by_days"]) == [(2, 1, 5), (1, 2, 3), (3, 2, 3), (4, 4, 1)] + assert ranks(b["by_clicks"]) == [(2, 1, 40), (3, 1, 40), (1, 3, 10), (4, 4, 5)] + e = b["by_days"][0] + assert e["uid_str"] == "00000002" and e["display_name"] == "鼠2" and e["avatar_url"] is None + assert e["title"] == "" and e["title_color"] is None and e["uid_tier"] is None + assert "email" not in e and "flagged" not in e and "flagged_at" not in e + + +def test_real_checkins_and_zhi(client, sent, fake_clock): + login(client, sent) + client.post("/api/checkin") + fake_clock.set("2026-11-22T12:00:00+08:00") + client.post("/api/checkin") + b = board(client) + assert b["total_checkins"] == 2 and b["total_clicks"] == 2 + assert ranks(b["by_days"]) == [(1, 1, 2)] and ranks(b["by_clicks"]) == [(1, 1, 2)] + + +def test_admin_excluded(client, sent, fake_clock): + r = admin_verify(client, admin_code(fake_clock)) + assert r.status_code == 200, r.text + client.post("/api/checkin") + conn = db.connect() + conn.execute("UPDATE users SET clicks = 999999 WHERE uid = ?", (config.ADMIN_UID,)) + conn.close() + seed({1: (1, 3)}) + b = board(client) + assert b["total_checkins"] == 1 and b["total_clicks"] == 3 + assert [e["uid"] for e in b["by_days"] + b["by_clicks"]] == [1, 1] + + +def test_top_ten_only(client): + seed({uid: (uid, uid * 100) for uid in range(1, 13)}) + b = board(client) + assert len(b["by_days"]) == len(b["by_clicks"]) == config.LEADERBOARD_SIZE == 10 + assert [e["uid"] for e in b["by_days"]] == list(range(12, 2, -1)) + assert b["total_checkins"] == sum(range(1, 13)) # 總數還是算全部 + assert b["total_clicks"] == sum(range(1, 13)) * 100 + + +def test_flagged_still_listed_until_cleared(client): + seed({1: (2, 50), 2: (1, 999_999)}, flagged={2}) + b = board(client) + assert b["by_clicks"][0]["uid"] == 2 and b["total_clicks"] == 1_000_049 + # 管理員清掉作弊者的次數:總數和名次馬上更新 + conn = db.connect() + conn.execute("UPDATE users SET clicks = 0 WHERE uid = 2") + conn.close() + b = board(client) + assert ranks(b["by_clicks"]) == [(1, 1, 50)] and b["total_clicks"] == 50 + + +def test_reset_progress_clears_board(client): + seed({1: (2, 50), 2: (1, 7)}) + admin.main(["reset-progress", "--yes"]) + assert board(client) == {"total_checkins": 0, "total_clicks": 0, "by_days": [], "by_clicks": []} + + +def test_public_page_and_api(client): + client.cookies.clear() + assert client.get("/api/leaderboard").status_code == 200 + r = client.get("/leaderboard") + assert r.status_code == 200 and 'id="view-leaderboard"' in r.text diff --git a/web/app.js b/web/app.js index ab1e1e8..cd08fa0 100644 --- a/web/app.js +++ b/web/app.js @@ -159,6 +159,7 @@ function renderSidebar() { const me = state.me; $("auth-box").hidden = !!me; $("me-box").hidden = !me; + $("site-nav").hidden = !!me; if (!me) return; $("me-avatar").src = me.avatar_url || DEFAULT_AVATAR; $("me-name").textContent = me.display_name; @@ -785,7 +786,7 @@ function bindCheckin() { // ---------- 畫面切換 ---------- function showView(id) { - for (const v of ["view-checkin", "view-user", "view-upload", "view-images", "view-notices"]) $(v).hidden = v !== id; + for (const v of ["view-checkin", "view-user", "view-upload", "view-images", "view-notices", "view-leaderboard"]) $(v).hidden = v !== id; if (id !== "view-checkin") { clearInterval(state.resetTimer); closeStage(); state.guestOn = false; } } @@ -1075,6 +1076,57 @@ function bindNotices() { })); } +// ---------- 全服總榜 ---------- + +// 一列:名次、大頭貼、名稱與 UID、數值(unit 是 lb.days / lb.clicks) +function lbRow(e, unit) { + const li = document.createElement("li"); + li.className = "lb-row"; + if (e.rank <= 3) li.classList.add(`top${e.rank}`); + if (state.me?.uid === e.uid) li.classList.add("me"); + const rank = document.createElement("span"); + rank.className = "lb-rank"; + rank.textContent = e.rank; + const avatar = document.createElement("img"); + avatar.className = "avatar lb-avatar"; + avatar.alt = ""; + avatar.width = avatar.height = 40; + avatar.src = e.avatar_url || DEFAULT_AVATAR; + const who = document.createElement("span"); + who.className = "lb-who"; + const name = document.createElement("a"); + name.className = "lb-name"; + name.href = `/u/${e.uid_str}`; + name.textContent = e.display_name; + const uid = document.createElement("span"); + showUid(uid, e); + who.append(name, uid); + const value = document.createElement("span"); + value.className = "lb-value"; + value.textContent = t(unit, { n: fmtNum(e.value) }); + li.append(rank, avatar, who, value); + return li; +} + +function renderLbList(listId, emptyId, items, unit) { + $(listId).replaceChildren(...items.map((e) => lbRow(e, unit))); + $(emptyId).hidden = items.length > 0; +} + +async function showLeaderboard() { + showView("view-leaderboard"); + document.title = `${t("lb.heading")} · ${SITE_TITLE}`; + try { + const r = await api("GET", "/api/leaderboard"); + $("lb-total-checkins").textContent = fmtNum(r.total_checkins); + $("lb-total-clicks").textContent = fmtNum(r.total_clicks); + renderLbList("lb-days", "lb-days-empty", r.by_days, "lb.days"); + renderLbList("lb-clicks", "lb-clicks-empty", r.by_clicks, "lb.clicks"); + } catch (e) { + toast(errText(e)); + } +} + // ---------- 個人頁 ---------- async function showUser(uid) { @@ -1243,6 +1295,7 @@ async function route() { if (location.pathname === "/upload") return showUpload(); if (location.pathname === "/images" || location.pathname === "/review") return showImages(); if (location.pathname === "/notices") return showNotices(); + if (location.pathname === "/leaderboard") return showLeaderboard(); return showCheckin(); } diff --git a/web/i18n/en.json b/web/i18n/en.json index d6cb2c3..5b75551 100644 --- a/web/i18n/en.json +++ b/web/i18n/en.json @@ -144,5 +144,14 @@ "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)" + "err.unsupported_format": "Only JPG, PNG and WEBP are supported (no GIF)", + "nav.leaderboard": "Leaderboard", + "lb.heading": "Leaderboard", + "lb.total_checkins": "Total check-ins", + "lb.total_clicks": "Total squeaks", + "lb.by_days": "Most check-ins", + "lb.by_clicks": "Most squeaks", + "lb.days": "{n} days", + "lb.clicks": "{n} squeaks", + "lb.empty": "No one on the board yet" } diff --git a/web/i18n/ja.json b/web/i18n/ja.json index bf986eb..fac190e 100644 --- a/web/i18n/ja.json +++ b/web/i18n/ja.json @@ -144,5 +144,14 @@ "source.label": "出典(任意)", "source.placeholder": "例:x@sthkm3", "err.source_too_long": "出典は 40 文字までです", - "err.unsupported_format": "JPG・PNG・WEBP のみ対応しています(GIF は不可)" + "err.unsupported_format": "JPG・PNG・WEBP のみ対応しています(GIF は不可)", + "nav.leaderboard": "全体ランキング", + "lb.heading": "全体ランキング", + "lb.total_checkins": "合計チェックイン回数", + "lb.total_clicks": "合計チューチュー回数", + "lb.by_days": "チェックイン回数ランキング", + "lb.by_clicks": "チューチュー回数ランキング", + "lb.days": "{n} 日", + "lb.clicks": "{n} 回", + "lb.empty": "まだ誰もランクインしていません" } diff --git a/web/i18n/ko.json b/web/i18n/ko.json index fc82cc7..0c3191d 100644 --- a/web/i18n/ko.json +++ b/web/i18n/ko.json @@ -144,5 +144,14 @@ "source.label": "출처 (선택)", "source.placeholder": "예: x@sthkm3", "err.source_too_long": "출처는 40자까지예요", - "err.unsupported_format": "JPG, PNG, WEBP만 지원해요 (GIF 불가)" + "err.unsupported_format": "JPG, PNG, WEBP만 지원해요 (GIF 불가)", + "nav.leaderboard": "전체 랭킹", + "lb.heading": "전체 랭킹", + "lb.total_checkins": "총 출석 횟수", + "lb.total_clicks": "총 찍찍 횟수", + "lb.by_days": "출석 횟수 랭킹", + "lb.by_clicks": "찍찍 횟수 랭킹", + "lb.days": "{n}일", + "lb.clicks": "{n}번", + "lb.empty": "아직 랭킹에 오른 사람이 없어요" } diff --git a/web/i18n/zh-CN.json b/web/i18n/zh-CN.json index b86894d..2269070 100644 --- a/web/i18n/zh-CN.json +++ b/web/i18n/zh-CN.json @@ -144,5 +144,14 @@ "source.label": "出处(选填)", "source.placeholder": "例如 x@sthkm3", "err.source_too_long": "出处最多 40 个字", - "err.unsupported_format": "只支持 JPG、PNG、WEBP(不收 GIF)" + "err.unsupported_format": "只支持 JPG、PNG、WEBP(不收 GIF)", + "nav.leaderboard": "全服总榜", + "lb.heading": "全服总榜", + "lb.total_checkins": "总签到次数", + "lb.total_clicks": "总吱吱次数", + "lb.by_days": "签到次数排行榜", + "lb.by_clicks": "吱吱次数排行榜", + "lb.days": "{n} 天", + "lb.clicks": "{n} 次", + "lb.empty": "还没有人上榜" } diff --git a/web/i18n/zh-TW.json b/web/i18n/zh-TW.json index 6caa92c..8908932 100644 --- a/web/i18n/zh-TW.json +++ b/web/i18n/zh-TW.json @@ -144,5 +144,14 @@ "source.label": "出處(選填)", "source.placeholder": "例如 x@sthkm3", "err.source_too_long": "出處最多 40 個字", - "err.unsupported_format": "只支援 JPG、PNG、WEBP(不收 GIF)" + "err.unsupported_format": "只支援 JPG、PNG、WEBP(不收 GIF)", + "nav.leaderboard": "全服總榜", + "lb.heading": "全服總榜", + "lb.total_checkins": "總簽到次數", + "lb.total_clicks": "總吱吱次數", + "lb.by_days": "簽到次數排行榜", + "lb.by_clicks": "吱吱次數排行榜", + "lb.days": "{n} 天", + "lb.clicks": "{n} 次", + "lb.empty": "還沒有人上榜" } diff --git a/web/index.html b/web/index.html index ee2721d..1494d85 100644 --- a/web/index.html +++ b/web/index.html @@ -59,10 +59,16 @@ + + + +