編輯個人資料改地方、圖片自帶出處
This commit is contained in:
1 parent
e75f0c95e9
commit
61e8580c72
27 files changed
+906
-160
No files matched your search
@@ -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)}
|
||||
|
||||
Reference in new issue
Block a user