2 Commits
Author SHA1 Message Date
Sahik d4377a47e4 新增榜單 2026-12-02 17:25:56 +08:00
Sahik d2bba07749 更新示意圖 2026-12-01 03:55:10 +08:00
16 changed files with 317 additions and 11 deletions

No files matched your search

+3 -2
View File
@@ -4,9 +4,9 @@
每天來吱一下,領一張吱咪小卡的簽到網站。
**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">
## 怎麼玩
@@ -25,6 +25,7 @@
- **全自動吱吱**:懶得點的話,繼續吱吱畫面下方有開關,打開就會自己一直吱
- **訪客吱吱**:不用登入就能吱,會拿到一張「訪客 #四位亂碼」的小卡。代號和次數只記在你自己的瀏覽器,伺服器不會記;之後登入的話帳號從頭算,訪客的次數不會帶過去
- **兩個數字分開算**:簽到天數一天只加一次;吱吱次數每吱一下加一次
- **全服總榜**:選單裡的「全服總榜」,最上面是全伺服器的總簽到次數和總吱吱次數,下面是簽到次數和吱吱次數的前 10 名(不算管理員),沒登入也能看
- **投稿圖片**:可以上傳你覺得適合放上小卡的圖,每天最多 5 張,可以附上出處;管理員審核通過後加入圖庫,出處會小小地寫在小卡圖片的右下角
- **個人頁**:名稱、大頭貼、自我介紹(支援 Markdown),在自己的個人頁按「編輯」修改
- **稱號**:管理員可以幫指定的 UID 加上顏色和稱號
Binary file not shown.

Before

Width:  |  Height:  |  Size: 623 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 658 KiB

+1 -1
View File
@@ -1,2 +1,2 @@
"""版本號只寫在這裡,頁尾會顯示;發布新版本時改這一行。"""
__version__ = "1.2.0"
__version__ = "1.3.0"
+3
View File
@@ -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
+52
View File
@@ -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),
}
+4 -2
View File
@@ -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")
+101
View File
@@ -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
+54 -1
View File
@@ -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();
}
+10 -1
View File
@@ -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"
}
+10 -1
View File
@@ -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": "まだ誰もランクインしていません"
}
+10 -1
View File
@@ -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": "아직 랭킹에 오른 사람이 없어요"
}
+10 -1
View File
@@ -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": "还没有人上榜"
}
+10 -1
View File
@@ -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": "還沒有人上榜"
}
+20
View File
@@ -59,10 +59,16 @@
<a id="upload-link" href="/upload" data-i18n="nav.upload"></a>
<a id="review-link" href="/images" hidden></a>
<a id="notices-link" href="/notices" hidden></a>
<a href="/leaderboard" data-i18n="nav.leaderboard"></a>
<button type="button" class="link" id="logout" data-i18n="auth.logout"></button>
</nav>
</section>
<!-- 沒登入時的選單(登入後全服總榜在上面個人選單的登出上方) -->
<nav class="me-nav site-nav" id="site-nav">
<a href="/leaderboard" data-i18n="nav.leaderboard"></a>
</nav>
<div class="sidebar-foot">
<label class="lang"><span data-i18n="lang.label"></span>
<select id="lang">
@@ -189,6 +195,20 @@
<button type="button" id="notices-more" data-i18n="notices.more" hidden></button>
</section>
<section id="view-leaderboard" hidden>
<h1 data-i18n="lb.heading"></h1>
<div class="lb-totals">
<div class="lb-total"><b id="lb-total-checkins">–</b><span data-i18n="lb.total_checkins"></span></div>
<div class="lb-total"><b id="lb-total-clicks">–</b><span data-i18n="lb.total_clicks"></span></div>
</div>
<h2 data-i18n="lb.by_days"></h2>
<ol class="lb-list" id="lb-days"></ol>
<p class="hint" id="lb-days-empty" data-i18n="lb.empty" hidden></p>
<h2 data-i18n="lb.by_clicks"></h2>
<ol class="lb-list" id="lb-clicks"></ol>
<p class="hint" id="lb-clicks-empty" data-i18n="lb.empty" hidden></p>
</section>
<section id="view-user" hidden>
<div id="user-card" class="profile" hidden>
<img id="user-avatar" class="avatar large" alt="" width="160" height="160">
+29
View File
@@ -157,6 +157,35 @@ button.link:disabled { color: var(--muted); }
.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); }
/* 全服總榜 */
.site-nav { margin-top: 0; }
#view-leaderboard { width: 100%; max-width: 560px; }
#view-leaderboard h1 { font-size: 24px; margin: 0 0 8px; }
#view-leaderboard h2 { font-size: 18px; margin: 28px 0 4px; }
.lb-totals { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin: 8px 0 8px; }
.lb-total {
display: flex; flex-direction: column; align-items: center; gap: 4px;
padding: 20px 12px; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
text-align: center;
}
.lb-total b { font-size: clamp(26px, 7vw, 40px); color: var(--accent); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; line-height: 1.1; }
.lb-total span { font-size: 14px; color: var(--muted); }
.lb-list { list-style: none; margin: 8px 0 16px; padding: 0; display: flex; flex-direction: column; gap: 8px; }
.lb-row {
display: flex; align-items: center; gap: 12px;
padding: 10px 14px; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
}
.lb-row.me { border-color: var(--accent); }
.lb-rank { flex: 0 0 2em; text-align: center; font-size: 18px; font-weight: 700; color: var(--muted); font-variant-numeric: tabular-nums; }
.lb-row.top1 .lb-rank { color: #ffd166; }
.lb-row.top2 .lb-rank { color: #d9d9d9; }
.lb-row.top3 .lb-rank { color: #e0a070; }
.lb-avatar { width: 40px; height: 40px; flex: 0 0 auto; }
.lb-who { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: flex-start; gap: 2px; }
.lb-name { font-weight: 700; text-decoration: none; overflow-wrap: anywhere; }
.lb-who .uid, .lb-who .title-badge { font-size: 12px; padding: 1px 8px; margin-top: 0; }
.lb-value { flex: 0 0 auto; font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; }
/* 手機:提示可以安裝到桌面 */
.install-hint {
width: 100%;