"""로고 그림 관리(관리자 페이지 '로고' 메뉴). 관리자가 올린 그림이나 후보 그림을 골라 홈페이지 로고와 파비콘 및 홈 화면 아이콘을 바꾼다. 크기별 PNG는 관리자 브라우저가 만들어 보내고 서버는 PNG 형식과 크기만 확인해 데이터 폴더에 둔다. 바꾼 그림이 없으면 web 폴더의 기본 로고를 그대로 준다. 새 파이썬 패키지는 쓰지 않는다. 제미나이 키는 systemd LoadCredential(gemini)로만 받는다. 키 값은 응답·기록·화면 어디에도 내보내지 않는다. 키 넣기: 보조 서버에서 ~/bin/duty-gemini-key.sh (사용자가 직접 실행) """ import base64 import json import os import re import secrets import struct import threading import time import urllib.error import urllib.parse from pathlib import Path from urllib.request import Request as UrlRequest, urlopen from fastapi import HTTPException, Request from fastapi.responses import FileResponse, JSONResponse, Response import site_admin # 관리자 브라우저가 만들어 보내는 그림. 이름: (가로·세로 픽셀) SIZES = {"512": 512, "192": 192, "180": 180, "64": 64, "maskable": 512} MAX_IMAGE = 1_500_000 MAX_CANDIDATES = 40 GEMINI_URL = os.environ.get("DUTY_GEMINI_URL", "https://generativelanguage.googleapis.com").rstrip("/") DEFAULT_MODEL = "gemini-2.5-flash-image" DEFAULT_PROMPT = ("Minimal modern app icon for a Korean duty-shift calendar app named '당직근무'. " "A clean calendar page with a small crescent moon for night duty, flat vector style, " "deep navy #26364d and terracotta #b65b3c on warm off-white #fffdf8, centered, " "simple geometric shapes, no text, no letters, rounded square background, crisp edges, high contrast.") # 공개 주소 → (바꾼 그림 파일, 기본 그림 파일, 형식) 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 gemini_key(): folder = os.environ.get("CREDENTIALS_DIRECTORY") path = Path(folder) / "gemini" if folder else Path(os.environ.get("DUTY_GEMINI_KEY_FILE", "/nonexistent")) try: key = path.read_text(encoding="utf8").strip() except OSError: return "" return key if re.fullmatch(r"[A-Za-z0-9_\-]{20,200}", key) else "" def gemini_image(key, model, prompt): """제미나이에 그림 한 장을 요청한다. 모델이 그림 설정을 모르면 더 단순한 요청으로 한 번 더 시도한다.""" url = GEMINI_URL + "/v1beta/models/" + urllib.parse.quote(model, safe="-._") + ":generateContent" attempts = [ {"responseModalities": ["IMAGE"], "imageConfig": {"aspectRatio": "1:1"}}, {"responseModalities": ["TEXT", "IMAGE"]}, ] last = "그림을 받지 못했습니다." for index, config in enumerate(attempts): body = json.dumps({"contents": [{"parts": [{"text": prompt}]}], "generationConfig": config}).encode() request = UrlRequest(url, data=body, method="POST", headers={"Content-Type": "application/json", "x-goog-api-key": key}) try: with urlopen(request, timeout=120) as response: data = json.loads(response.read(30_000_000)) except urllib.error.HTTPError as error: try: detail = json.loads(error.read(20000)).get("error", {}).get("message", "") except ValueError: detail = "" error.close() names = {400: "요청 형식 또는 모델", 401: "키", 403: "키 권한", 404: "모델 이름", 429: "사용 한도"} last = "그림 만들기 오류 " + str(error.code) + " (" + names.get(error.code, "서버") + "): " + detail[:200] if error.code == 400 and index == 0: continue raise RuntimeError(last) except (urllib.error.URLError, TimeoutError, ValueError) as error: raise RuntimeError("그림 만들기 서버에 연결하지 못했습니다: " + str(error)[:150]) texts = [] for candidate in data.get("candidates", []): for part in candidate.get("content", {}).get("parts", []): inline = part.get("inlineData") or part.get("inline_data") if inline and inline.get("data"): return base64.b64decode(inline["data"]) if part.get("text"): texts.append(part["text"]) reason = data.get("promptFeedback", {}).get("blockReason") or (data.get("candidates") or [{}])[0].get("finishReason", "") last = "그림 없이 답이 왔습니다" + (" (" + reason + ")" if reason else "") + (": " + " ".join(texts)[:150] if texts else "") if index == 0: continue raise RuntimeError(last) 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) jobs = {} job_lock = threading.Lock() 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,c.prompt,c.model,m.display_name AS actor FROM brand_candidates c LEFT JOIN members m ON m.id=c.actor ORDER BY c.created DESC")] with job_lock: running = [dict(id=key, **value) for key, value in jobs.items() if value["state"] == "running"] return {"custom": custom(), "candidates": rows, "gemini": bool(gemini_key()), "defaultPrompt": DEFAULT_PROMPT, "defaultModel": DEFAULT_MODEL, "running": running} @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} # ---------------------------------------------------------------- 관리자: 제미나이 후보 def run_job(job_id, actor, model, prompt, count): key = gemini_key() made, errors = 0, [] for _ in range(count): try: raw = gemini_image(key, model, prompt) mime, ext = image_kind(raw) if not mime or len(raw) > 20_000_000: raise RuntimeError("그림 형식을 알 수 없습니다.") cid = secrets.token_hex(8) (candidates / (cid + "." + ext)).write_bytes(raw) with db() as conn: conn.execute("INSERT INTO brand_candidates(id,created,prompt,model,ext,actor) VALUES(?,?,?,?,?,?)", (cid, int(time.time()), prompt, model, ext, actor)) made += 1 except Exception as error: # 한 장이 실패해도 나머지는 계속 만든다. errors.append(str(error)[:300]) if "키" in str(error) or "모델 이름" in str(error) or "사용 한도" in str(error): break with job_lock: jobs[job_id].update(made=made, errors=errors) # 오래된 후보부터 정리해 데이터 폴더가 계속 커지지 않게 한다. with db() as conn: old = conn.execute("SELECT id,ext FROM brand_candidates ORDER BY created DESC LIMIT -1 OFFSET ?", (MAX_CANDIDATES,)).fetchall() for row in old: (candidates / (row[0] + "." + row[1])).unlink(missing_ok=True) conn.execute("DELETE FROM brand_candidates WHERE id=?", (row[0],)) with job_lock: # 키·모델 오류로 중간에 멈춘 경우에도 마지막 오류를 화면에 보여 줄 수 있게 함께 남긴다. jobs[job_id].update(made=made, errors=errors, state="done" if made else "error") log(actor, "logo-generate", model + " · " + str(made) + "/" + str(count) + "장" + (" · " + errors[0][:120] if errors else "")) @app.post(prefix + "/api/admin/brand-generate") async def brand_generate(request: Request): actor = administrator(request) throttle(request, "admin-brand-generate", 10, 3600) data = await payload(request) prompt, model, count = data.get("prompt"), data.get("model", DEFAULT_MODEL), data.get("count", 2) if not isinstance(prompt, str) or not 10 <= len(prompt.strip()) <= 1500: raise HTTPException(400, "그림 설명을 10~1500자로 써 주세요.") if not isinstance(model, str) or not re.fullmatch(r"[a-z0-9][a-z0-9.\-]{2,80}", model): raise HTTPException(400, "모델 이름을 확인해 주세요.") if type(count) is not int or not 1 <= count <= 4: raise HTTPException(400, "한 번에 1~4장까지 만들 수 있습니다.") if not gemini_key(): raise HTTPException(409, "그림 만들기 키가 아직 설정되지 않았습니다.") with job_lock: if any(job["state"] == "running" for job in jobs.values()): raise HTTPException(409, "이미 후보를 만들고 있습니다. 끝난 뒤 다시 눌러 주세요.") job_id = secrets.token_hex(8) jobs[job_id] = {"state": "running", "made": 0, "count": count, "errors": [], "started": int(time.time())} for key in [key for key, job in jobs.items() if job["state"] != "running" and job["started"] < time.time() - 86400]: del jobs[key] threading.Thread(target=run_job, args=(job_id, actor["member"], model, prompt.strip(), count), daemon=True).start() return {"job": job_id} @app.get(prefix + "/api/admin/brand-job/{job_id}") async def brand_job(request: Request, job_id: str): administrator(request) with job_lock: job = jobs.get(job_id) if job is None: raise HTTPException(404, "작업을 찾을 수 없습니다.") return dict(job) @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}