179 lines
8.7 KiB
Python
179 lines
8.7 KiB
Python
"""로고 그림 관리(관리자 페이지 '로고' 메뉴).
|
|
|
|
관리자가 올린 그림이나 보관한 그림을 골라 홈페이지 로고와 파비콘 및 홈 화면 아이콘을 바꾼다.
|
|
크기별 PNG는 관리자 브라우저가 만들어 보내고 서버는 PNG 형식과 크기만 확인해 데이터 폴더에 둔다.
|
|
바꾼 그림이 없으면 web 폴더의 기본 로고를 그대로 준다. 보관한 그림은 운영 도구(brand_import.py)로 넣는다.
|
|
새 파이썬 패키지는 쓰지 않는다.
|
|
"""
|
|
import base64
|
|
import json
|
|
import re
|
|
import struct
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from fastapi import HTTPException, Request
|
|
from fastapi.responses import FileResponse, JSONResponse
|
|
|
|
import site_admin
|
|
|
|
# 관리자 브라우저가 만들어 보내는 그림. 이름: (가로·세로 픽셀)
|
|
SIZES = {"512": 512, "192": 192, "180": 180, "64": 64, "maskable": 512}
|
|
MAX_IMAGE = 1_500_000
|
|
# 공개 주소 → (바꾼 그림 파일, 기본 그림 파일, 형식)
|
|
PUBLIC = {
|
|
"logo": ("logo-192.png", "icon.svg"),
|
|
"favicon": ("logo-64.png", "icon.svg"),
|
|
"apple-touch": ("logo-180.png", "apple-touch-icon.png"),
|
|
"icon-192": ("logo-192.png", "icon-192.png"),
|
|
"icon-512": ("logo-512.png", "icon-512.png"),
|
|
"icon-maskable": ("logo-maskable.png", "icon-maskable-512.png"),
|
|
}
|
|
FILES = {"512": "logo-512.png", "192": "logo-192.png", "180": "logo-180.png", "64": "logo-64.png", "maskable": "logo-maskable.png"}
|
|
|
|
|
|
def png_size(raw):
|
|
"""PNG 서명과 IHDR에서 가로·세로를 읽는다. PNG가 아니면 None."""
|
|
if len(raw) < 24 or raw[:8] != b"\x89PNG\r\n\x1a\n" or raw[12:16] != b"IHDR":
|
|
return None
|
|
return struct.unpack(">II", raw[16:24])
|
|
|
|
|
|
def image_kind(raw):
|
|
if raw[:8] == b"\x89PNG\r\n\x1a\n":
|
|
return "image/png", "png"
|
|
if raw[:3] == b"\xff\xd8\xff":
|
|
return "image/jpeg", "jpg"
|
|
if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
|
|
return "image/webp", "webp"
|
|
return None, None
|
|
|
|
|
|
def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
|
web = Path(root) / "web"
|
|
brand = Path(data_dir) / "brand"
|
|
candidates = brand / "candidates"
|
|
candidates.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
with db() as conn:
|
|
conn.execute("""CREATE TABLE IF NOT EXISTS brand_candidates(id TEXT PRIMARY KEY, created INTEGER NOT NULL,
|
|
prompt TEXT NOT NULL, model TEXT NOT NULL, ext TEXT NOT NULL, actor TEXT NOT NULL)""")
|
|
|
|
def log(actor, action, detail=""):
|
|
with db() as conn:
|
|
conn.execute("INSERT INTO admin_log(actor,area,target,action,detail,created) VALUES(?,?,?,?,?,?)",
|
|
(actor, "site", "", action, detail[:500], int(time.time())))
|
|
|
|
def custom():
|
|
meta = brand / "logo.json"
|
|
if not meta.exists() or not all((brand / name).exists() for name in FILES.values()):
|
|
return None
|
|
try:
|
|
return json.loads(meta.read_text())
|
|
except ValueError:
|
|
return None
|
|
|
|
# ---------------------------------------------------------------- 공개: 로고 파일과 앱 설치 정보
|
|
@app.get(prefix + "/brand/{name}")
|
|
async def brand_file(name: str):
|
|
if name not in PUBLIC:
|
|
raise HTTPException(404)
|
|
mine, default = PUBLIC[name]
|
|
if custom():
|
|
return FileResponse(brand / mine, media_type="image/png")
|
|
return FileResponse(web / default, media_type="image/svg+xml" if default.endswith(".svg") else "image/png")
|
|
|
|
@app.get(prefix + "/manifest.webmanifest")
|
|
async def manifest():
|
|
with db() as conn:
|
|
values, _ = site_admin.read_settings(conn)
|
|
body = {
|
|
"name": values["brandName"], "short_name": values["brandName"][:12],
|
|
"description": values["heroIntro"].replace("\n", " "), "lang": "ko",
|
|
"start_url": prefix + "/", "scope": prefix + "/", "display": "standalone",
|
|
"background_color": "#f4f1ea", "theme_color": "#26364d",
|
|
"icons": [
|
|
{"src": "brand/icon-192", "sizes": "192x192", "type": "image/png"},
|
|
{"src": "brand/icon-512", "sizes": "512x512", "type": "image/png"},
|
|
{"src": "brand/icon-maskable", "sizes": "512x512", "type": "image/png", "purpose": "maskable"},
|
|
],
|
|
}
|
|
return JSONResponse(body, media_type="application/manifest+json")
|
|
|
|
# ---------------------------------------------------------------- 관리자: 현재 로고와 바꾸기
|
|
@app.get(prefix + "/api/admin/brand")
|
|
async def brand_state(request: Request):
|
|
administrator(request)
|
|
with db() as conn:
|
|
rows = [dict(row) for row in conn.execute(
|
|
"SELECT c.id,c.created,m.display_name AS actor FROM brand_candidates c LEFT JOIN members m ON m.id=c.actor ORDER BY c.created DESC")]
|
|
return {"custom": custom(), "candidates": rows}
|
|
|
|
@app.post(prefix + "/api/admin/brand-logo")
|
|
async def brand_logo(request: Request):
|
|
actor = administrator(request)
|
|
throttle(request, "admin-brand", 20, 600)
|
|
data = await payload(request)
|
|
images, source = data.get("images"), data.get("source")
|
|
if not isinstance(images, dict) or set(images) != set(SIZES) or source not in ("upload", "candidate"):
|
|
raise HTTPException(400, "로고 그림 다섯 가지 크기를 모두 보내 주세요.")
|
|
decoded = {}
|
|
for name, size in SIZES.items():
|
|
value = images[name]
|
|
if not isinstance(value, str) or len(value) > MAX_IMAGE * 4 // 3 + 8:
|
|
raise HTTPException(400, "로고 그림이 너무 큽니다.")
|
|
try:
|
|
raw = base64.b64decode(value, validate=True)
|
|
except ValueError:
|
|
raise HTTPException(400, "로고 그림 자료를 읽지 못했습니다.")
|
|
if png_size(raw) != (size, size):
|
|
raise HTTPException(400, str(size) + "px PNG 그림이 아닙니다.")
|
|
decoded[name] = raw
|
|
candidate = data.get("candidate") if source == "candidate" else None
|
|
if candidate is not None and not re.fullmatch(r"[a-f0-9]{16}", str(candidate)):
|
|
raise HTTPException(400, "보관한 그림을 확인해 주세요.")
|
|
# 파일마다 임시 이름으로 쓴 뒤 바꿔 끼워 반쯤 바뀐 상태가 보이지 않게 한다.
|
|
(brand / "logo.json").unlink(missing_ok=True)
|
|
for name, raw in decoded.items():
|
|
temp = brand / (FILES[name] + ".tmp")
|
|
temp.write_bytes(raw)
|
|
temp.replace(brand / FILES[name])
|
|
meta = {"updated": int(time.time()), "by": actor["display_name"], "source": source, "candidate": candidate}
|
|
temp = brand / "logo.json.tmp"
|
|
temp.write_text(json.dumps(meta, ensure_ascii=False))
|
|
temp.replace(brand / "logo.json")
|
|
log(actor["member"], "logo", "올린 그림" if source == "upload" else "보관한 그림 " + str(candidate))
|
|
return {"custom": meta}
|
|
|
|
@app.post(prefix + "/api/admin/brand-logo-reset")
|
|
async def brand_reset(request: Request):
|
|
actor = administrator(request)
|
|
throttle(request, "admin-brand", 20, 600)
|
|
(brand / "logo.json").unlink(missing_ok=True)
|
|
for name in FILES.values():
|
|
(brand / name).unlink(missing_ok=True)
|
|
log(actor["member"], "logo-reset", "기본 로고")
|
|
return {"custom": None}
|
|
|
|
# ---------------------------------------------------------------- 관리자: 보관한 그림
|
|
@app.get(prefix + "/api/admin/brand-candidate/{candidate_id}")
|
|
async def brand_candidate(request: Request, candidate_id: str):
|
|
administrator(request)
|
|
with db() as conn:
|
|
row = conn.execute("SELECT id,ext FROM brand_candidates WHERE id=?", (candidate_id,)).fetchone()
|
|
path = candidates / (row[0] + "." + row[1]) if row else None
|
|
if path is None or not path.exists():
|
|
raise HTTPException(404, "보관한 그림을 찾을 수 없습니다.")
|
|
return FileResponse(path, media_type={"png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"}[row[1]])
|
|
|
|
@app.post(prefix + "/api/admin/brand-candidate-delete/{candidate_id}")
|
|
async def brand_candidate_delete(request: Request, candidate_id: str):
|
|
actor = administrator(request)
|
|
with db() as conn:
|
|
row = conn.execute("SELECT id,ext FROM brand_candidates WHERE id=?", (candidate_id,)).fetchone()
|
|
if row is None:
|
|
raise HTTPException(404, "보관한 그림을 찾을 수 없습니다.")
|
|
conn.execute("DELETE FROM brand_candidates WHERE id=?", (candidate_id,))
|
|
(candidates / (row[0] + "." + row[1])).unlink(missing_ok=True)
|
|
log(actor["member"], "logo-candidate-delete", candidate_id)
|
|
return {"deleted": True}
|