Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61e8580c72 |
No files matched your search
@@ -25,8 +25,8 @@
|
||||
- **全自動吱吱**:懶得點的話,繼續吱吱畫面下方有開關,打開就會自己一直吱
|
||||
- **訪客吱吱**:不用登入就能吱,會拿到一張「訪客 #四位亂碼」的小卡。代號和次數只記在你自己的瀏覽器,伺服器不會記;之後登入的話帳號從頭算,訪客的次數不會帶過去
|
||||
- **兩個數字分開算**:簽到天數一天只加一次;吱吱次數每吱一下加一次
|
||||
- **投稿圖片**:可以上傳你覺得適合放上小卡的圖,每天最多 5 張,管理員審核通過後加入圖庫
|
||||
- **個人頁**:名稱、大頭貼、自我介紹(支援 Markdown)
|
||||
- **投稿圖片**:可以上傳你覺得適合放上小卡的圖,每天最多 5 張,可以附上出處;管理員審核通過後加入圖庫,出處會小小地寫在小卡圖片的右下角
|
||||
- **個人頁**:名稱、大頭貼、自我介紹(支援 Markdown),在自己的個人頁按「編輯」修改
|
||||
- **稱號**:管理員可以幫指定的 UID 加上顏色和稱號
|
||||
- **加到主畫面**:手機上可以安裝到桌面,像 App 一樣打開
|
||||
- **語言**:繁體中文、简体中文、日本語、한국어、English
|
||||
|
||||
@@ -13,7 +13,7 @@ clone 之後要改哪些地方、怎麼在自己的電腦跑起來、怎麼部
|
||||
| 信件、小卡、分享文字 | `server/app/i18n/*.json` |
|
||||
| 吱吱影片 | 換掉 `media-src/zhizhi.mp4`,執行 `tools/make_media.py` |
|
||||
| 圖標 | 換掉 `icon/zhiwu.jpg`,執行 `tools/make_icons.py`(也會產生圖庫是空的時候用的預設圖) |
|
||||
| 圖庫 | 圖片放進 `image/`(jpg / png / webp / gif),不用重啟 |
|
||||
| 圖庫 | 用管理員登入後的「管理圖片」新增、改出處、下架;也可以直接把圖放進 `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`,兩邊要一樣 |
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
"""版本號只寫在這裡,頁尾會顯示;發布新版本時改這一行。"""
|
||||
__version__ = "1.0.2"
|
||||
__version__ = "1.1.0"
|
||||
+50
-26
@@ -19,12 +19,12 @@ from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
||||
|
||||
from . import clock, config, limits
|
||||
from .checkin import list_memes, stats
|
||||
from . import clock, config, images, limits
|
||||
from .checkin import stats
|
||||
from .db import get_db
|
||||
from .deps import client_ip, fail
|
||||
from .i18n import norm_lang, t
|
||||
from .images import FORMATS
|
||||
from .memes import list_memes, source_of
|
||||
from .titles import badge_colors, fmt_uid
|
||||
|
||||
router = APIRouter()
|
||||
@@ -36,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 = 2 # 版面改了就加 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
|
||||
@@ -86,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, formats=FORMATS) 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 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) -> Image.Image:
|
||||
headline: str, sub: str, clicks: int, source: str = "") -> Image.Image:
|
||||
"""小卡的版面。badge = {"uid": "UID 00000001", "colors": (底色, 文字色), "title": 稱號};
|
||||
訪客沒有 UID,badge 傳 None,那一行就不畫。"""
|
||||
訪客沒有 UID,badge 傳 None,那一行就不畫。source = 圖的出處,空字串不畫。"""
|
||||
# 背景:上下漸層
|
||||
img = Image.new("RGB", (W, H))
|
||||
top, bottom = (70, 38, 12), (24, 13, 5)
|
||||
@@ -110,21 +128,24 @@ def draw(lang: str, meme: str | None, name: str, avatar: Image.Image | None, bad
|
||||
|
||||
# 圖庫抽到的圖
|
||||
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)
|
||||
pd.text((box_w / 2, box_h / 2), t(lang, "card.no_meme"), font=font(lang, 48), fill=MUTED, anchor="mm")
|
||||
img.paste(panel, (PAD, PAD), rounded_mask(panel.size, 28))
|
||||
img.paste(panel.convert("RGB"), (PAD, PAD), rounded_mask(panel.size, 28))
|
||||
|
||||
# 大頭貼(沒有就用主色圓形 + 名稱第一個字)
|
||||
av_size, av_y = 168, PAD + box_h + 40
|
||||
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)
|
||||
@@ -173,18 +194,20 @@ def draw(lang: str, meme: str | None, name: str, avatar: Image.Image | None, bad
|
||||
return img
|
||||
|
||||
|
||||
def render(user: sqlite3.Row, day: str, meme: str | None, total: int, streak: int, clicks: int) -> Image.Image:
|
||||
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)
|
||||
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) -> Image.Image:
|
||||
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)
|
||||
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:
|
||||
@@ -206,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:
|
||||
@@ -252,14 +275,15 @@ def get_guest_card(request: Request, code: str = "", n: str = "0", lang: str = c
|
||||
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)
|
||||
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).save(buf, "PNG")
|
||||
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:
|
||||
|
||||
+1
-12
@@ -9,6 +9,7 @@ from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
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
|
||||
@@ -16,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
|
||||
|
||||
@@ -60,7 +60,7 @@ MAIL_DAY_WINDOW = 24 * 3600
|
||||
# 請求大小上限
|
||||
BODY_MAX = 64 * 1024
|
||||
UPLOAD_BODY_MAX = 6 * 1024 * 1024 # 圖片上限 5MB,加上表單的部分
|
||||
UPLOAD_PATHS = ("/api/me/avatar", "/api/submissions")
|
||||
UPLOAD_PATHS = ("/api/me/avatar", "/api/submissions", "/api/admin/memes")
|
||||
|
||||
# 上傳的圖:像素上限(2400 萬像素的手機照片可以過)、等前一張處理完最多幾秒
|
||||
IMAGE_MAX_PIXELS = 30_000_000
|
||||
@@ -68,6 +68,8 @@ 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。兩個都設定才啟用
|
||||
|
||||
+24
-10
@@ -59,12 +59,20 @@ 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,
|
||||
@@ -112,20 +120,26 @@ def init():
|
||||
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 ''",
|
||||
"flagged_at": "INTEGER",
|
||||
# 後來才加的欄位:舊的資料庫(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:
|
||||
|
||||
@@ -10,5 +10,6 @@
|
||||
"card.clicks": "squeaks",
|
||||
"card.guest_name": "Guest #{code}",
|
||||
"card.guest": "Guest squeak",
|
||||
"about.yuzumi": "About Yuzumi"
|
||||
"about.yuzumi": "About Yuzumi",
|
||||
"card.source": "Source: {s}"
|
||||
}
|
||||
@@ -10,5 +10,6 @@
|
||||
"card.clicks": "チューチュー回数",
|
||||
"card.guest_name": "ゲスト #{code}",
|
||||
"card.guest": "ゲストチューチュー",
|
||||
"about.yuzumi": "Yuzumi について"
|
||||
"about.yuzumi": "Yuzumi について",
|
||||
"card.source": "出典:{s}"
|
||||
}
|
||||
@@ -10,5 +10,6 @@
|
||||
"card.clicks": "찍찍 횟수",
|
||||
"card.guest_name": "게스트 #{code}",
|
||||
"card.guest": "게스트 찍찍",
|
||||
"about.yuzumi": "Yuzumi 소개"
|
||||
"about.yuzumi": "Yuzumi 소개",
|
||||
"card.source": "출처: {s}"
|
||||
}
|
||||
@@ -10,5 +10,6 @@
|
||||
"card.clicks": "吱吱次数",
|
||||
"card.guest_name": "访客 #{code}",
|
||||
"card.guest": "访客吱吱",
|
||||
"about.yuzumi": "关于Yuzumi"
|
||||
"about.yuzumi": "关于Yuzumi",
|
||||
"card.source": "来源:{s}"
|
||||
}
|
||||
@@ -10,5 +10,6 @@
|
||||
"card.clicks": "吱吱次數",
|
||||
"card.guest_name": "訪客 #{code}",
|
||||
"card.guest": "訪客吱吱",
|
||||
"about.yuzumi": "關於Yuzumi"
|
||||
"about.yuzumi": "關於Yuzumi",
|
||||
"card.source": "來源:{s}"
|
||||
}
|
||||
+19
-2
@@ -4,13 +4,15 @@ 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")
|
||||
FORMATS = ("JPEG", "PNG", "WEBP", "GIF") # 讀圖庫裡已經有的圖(以前放進去的 GIF 照樣能畫第一格)
|
||||
UPLOAD_FORMATS = ("JPEG", "PNG", "WEBP") # 使用者上傳:不收 GIF。動態的 WEBP / PNG 只取第一格
|
||||
|
||||
# 第二道保險:Pillow 自己在超過這個值的兩倍時會拒絕(例如檔頭和實際內容不一樣大)
|
||||
Image.MAX_IMAGE_PIXELS = config.IMAGE_MAX_PIXELS // 2
|
||||
@@ -30,10 +32,23 @@ def slot():
|
||||
_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:
|
||||
with Image.open(io.BytesIO(data), formats=FORMATS) as im:
|
||||
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)
|
||||
@@ -41,5 +56,7 @@ def decode(data: bytes) -> tuple[Image.Image, bool]:
|
||||
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")
|
||||
+4
-3
@@ -9,7 +9,7 @@ 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, notices, 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"),
|
||||
@@ -82,7 +82,7 @@ async def guard(request: Request, call_next):
|
||||
|
||||
app.add_middleware(limits.BodyLimit) # 最後加的在最外層
|
||||
|
||||
for module in (auth, users, checkin, card, share, submissions, notices):
|
||||
for module in (auth, users, checkin, card, share, submissions, memes, notices):
|
||||
app.include_router(module.router)
|
||||
|
||||
|
||||
@@ -123,6 +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")
|
||||
@@ -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"})
|
||||
+20
-62
@@ -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
|
||||
from pydantic import BaseModel
|
||||
|
||||
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,37 +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 只取第一格。"""
|
||||
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.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
|
||||
|
||||
@@ -87,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:
|
||||
@@ -100,7 +64,9 @@ _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)
|
||||
@@ -114,8 +80,8 @@ def upload(file: UploadFile = File(...), user=Depends(current_user), conn: sqlit
|
||||
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"])}
|
||||
@@ -176,30 +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.chmod(tmp, 0o644) # mkstemp 是 0600,圖庫要讓 NAS 上的其他帳號也讀得到
|
||||
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)}
|
||||
|
||||
@@ -203,4 +203,4 @@ def test_parallel_requests_count_once(frozen): # noqa: F811
|
||||
|
||||
def test_no_beta_left(client):
|
||||
assert not hasattr(config, "BETA") and "beta" not in client.get("/").text.lower()
|
||||
assert card.CARD_VERSION == 2
|
||||
assert card.CARD_VERSION == 3
|
||||
@@ -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()
|
||||
@@ -240,7 +240,7 @@ def test_bomb_rejected_before_decode(client, sent, monkeypatch):
|
||||
assert r.status_code == 400 and r.json()["detail"] == "invalid_image"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fmt,ok", [("PNG", 1), ("JPEG", 1), ("WEBP", 1), ("GIF", 1),
|
||||
@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)
|
||||
@@ -249,6 +249,18 @@ def test_only_four_formats(client, sent, fmt, ok):
|
||||
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
|
||||
|
||||
+118
-10
@@ -34,6 +34,8 @@ const state = {
|
||||
zhiAutoTimer: null,
|
||||
zhiCoolUntil: 0, // 冷靜到什麼時候
|
||||
noticeCount: 0, // 通知匣已經載入幾則
|
||||
gallery: [], // 管理圖片:圖庫清單
|
||||
galleryHidden: false, // 管理圖片:現在看的是已下架的
|
||||
zhiLastAt: 0, // 上一次繼續吱吱的時間
|
||||
zhiPlay: 0, // 第幾次播放;離開再進來時,舊的那次播完不能動到新的
|
||||
zhiFlush: null, // 正在送次數的 Promise(離開時等它送完)
|
||||
@@ -63,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));
|
||||
});
|
||||
@@ -780,7 +785,7 @@ function bindCheckin() {
|
||||
// ---------- 畫面切換 ----------
|
||||
|
||||
function showView(id) {
|
||||
for (const v of ["view-checkin", "view-user", "view-upload", "view-review", "view-notices"]) $(v).hidden = v !== id;
|
||||
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; }
|
||||
}
|
||||
|
||||
@@ -839,6 +844,7 @@ 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++;
|
||||
@@ -847,12 +853,12 @@ function bindUpload() {
|
||||
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 {
|
||||
@@ -870,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() {
|
||||
@@ -889,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));
|
||||
@@ -901,6 +1000,14 @@ 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(); });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 管理員通知匣 ----------
|
||||
@@ -982,6 +1089,7 @@ 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;
|
||||
@@ -1033,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;
|
||||
@@ -1122,7 +1230,7 @@ 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();
|
||||
}
|
||||
|
||||
+22
-3
@@ -53,7 +53,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 +64,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",
|
||||
@@ -121,5 +121,24 @@
|
||||
"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"
|
||||
"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)"
|
||||
}
|
||||
+22
-3
@@ -53,7 +53,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 +64,7 @@
|
||||
"upload.status.pending": "審査中",
|
||||
"upload.status.approved": "採用",
|
||||
"upload.status.rejected": "不採用",
|
||||
"review.heading": "投稿の審査",
|
||||
"review.heading": "審査待ちの投稿",
|
||||
"review.left": "審査待ち {n} 枚",
|
||||
"review.approve": "採用",
|
||||
"review.reject": "却下",
|
||||
@@ -121,5 +121,24 @@
|
||||
"err.cooldown": "速すぎます。10 秒待ってからどうぞ",
|
||||
"err.too_frequent": "操作が頻繁すぎます。しばらくしてからお試しください",
|
||||
"notice.admin_login": "管理者がログインしました",
|
||||
"notice.mail_limit": "メール送信数がサイト全体の上限に達しました"
|
||||
"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 は不可)"
|
||||
}
|
||||
+22
-3
@@ -53,7 +53,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 +64,7 @@
|
||||
"upload.status.pending": "심사 중",
|
||||
"upload.status.approved": "채택",
|
||||
"upload.status.rejected": "미채택",
|
||||
"review.heading": "투고 심사",
|
||||
"review.heading": "심사 대기 투고",
|
||||
"review.left": "심사 대기 {n}장",
|
||||
"review.approve": "승인",
|
||||
"review.reject": "거절",
|
||||
@@ -121,5 +121,24 @@
|
||||
"err.cooldown": "너무 빨라요. 10초 쉬었다 하세요",
|
||||
"err.too_frequent": "너무 자주 시도했어요. 잠시 후 다시 시도해 주세요",
|
||||
"notice.admin_login": "관리자 로그인",
|
||||
"notice.mail_limit": "메일 발송이 전체 한도에 도달했어요"
|
||||
"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 불가)"
|
||||
}
|
||||
+22
-3
@@ -53,7 +53,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 +64,7 @@
|
||||
"upload.status.pending": "审核中",
|
||||
"upload.status.approved": "已加入",
|
||||
"upload.status.rejected": "未通过",
|
||||
"review.heading": "审核投稿",
|
||||
"review.heading": "待审投稿",
|
||||
"review.left": "待审 {n} 张",
|
||||
"review.approve": "同意",
|
||||
"review.reject": "拒绝",
|
||||
@@ -121,5 +121,24 @@
|
||||
"err.cooldown": "吱太快了,冷静 10 秒再吱",
|
||||
"err.too_frequent": "操作太频繁,请稍后再试",
|
||||
"notice.admin_login": "管理员登录",
|
||||
"notice.mail_limit": "发信数量到达全站上限"
|
||||
"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)"
|
||||
}
|
||||
+22
-3
@@ -53,7 +53,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 +64,7 @@
|
||||
"upload.status.pending": "審核中",
|
||||
"upload.status.approved": "已加入",
|
||||
"upload.status.rejected": "未通過",
|
||||
"review.heading": "審核投稿",
|
||||
"review.heading": "待審投稿",
|
||||
"review.left": "待審 {n} 張",
|
||||
"review.approve": "同意",
|
||||
"review.reject": "拒絕",
|
||||
@@ -121,5 +121,24 @@
|
||||
"err.cooldown": "吱太快了,冷靜 10 秒再吱",
|
||||
"err.too_frequent": "操作太頻繁,請稍後再試",
|
||||
"notice.admin_login": "管理員登入",
|
||||
"notice.mail_limit": "寄信數量到達全站上限"
|
||||
"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)"
|
||||
}
|
||||
+35
-8
@@ -54,9 +54,8 @@
|
||||
<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>
|
||||
<a id="review-link" href="/images" 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>
|
||||
</section>
|
||||
@@ -120,30 +119,57 @@
|
||||
<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>
|
||||
@@ -157,6 +183,7 @@
|
||||
<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>
|
||||
@@ -205,7 +232,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>
|
||||
|
||||
@@ -351,6 +351,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; }
|
||||
|
||||
Reference in new issue
Block a user