diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d8198c..6e8a785 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,8 +6,8 @@
# 관리자 로고 화면 · 2026년 12월 1일
-- 관리자 로고 화면의 안내와 후보 설명을 줄였습니다. 후보 아래에는 넣은 날과 넣은 사람만 보입니다.
-- 그림 만들기 키가 없는 서버에서는 만들기 칸을 숨깁니다. 웹 버전과 앱 APK 및 회원 자료는 바뀌지 않았습니다.
+- 관리자 로고 화면은 그림 올리기와 보관한 그림 고르기만 합니다. 그림을 만드는 칸과 기능은 뺐습니다.
+- 보관한 그림 아래에는 넣은 날과 넣은 사람만 보입니다. 웹 버전과 앱 APK 및 회원 자료는 바뀌지 않았습니다.
# 0.15.9 · 웹 2026-11-26.4 · 2026년 11월 26일
@@ -101,7 +101,7 @@
# 관리자 로고 메뉴 · 2026년 11월 24일
-- 관리자 페이지에서 로고 그림을 올리거나 후보 목록에서 골라 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿀 수 있습니다.
+- 관리자 페이지에서 로고 그림을 올리거나 보관한 그림에서 골라 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿀 수 있습니다.
- 기본 로고로 언제든 되돌릴 수 있습니다. 앱 설치 정보는 서비스 이름과 바꾼 아이콘을 따라갑니다.
- 웹 버전과 앱 APK 및 회원 자료는 바뀌지 않았습니다.
diff --git a/docs/제작매뉴얼-웹서버.md b/docs/제작매뉴얼-웹서버.md
index 8e4d80d..c965c4d 100644
--- a/docs/제작매뉴얼-웹서버.md
+++ b/docs/제작매뉴얼-웹서버.md
@@ -157,19 +157,19 @@ ANNUAL_LEAVE와 MONTHLY_LEAVE 및 VACATION과 OFFICIAL_LEAVE 및 FAMILY_LEAVE를
## 관리자 로고 메뉴 · 2026년 11월 24일
-관리자 페이지의 **로고**에서 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿉니다. 그림을 올리거나 후보 목록에서 고릅니다. 관리자 브라우저가 가운데를 정사각형으로 잘라 512·192·180·64px와 둥근 홈 화면용 512px PNG를 만들어 보내고 서버는 PNG 서명과 크기만 확인해 데이터 폴더의 `brand/`에 둡니다. 여백과 홈 화면 배경색을 고를 수 있습니다. 바꾼 그림이 없으면 기본 로고(`web/icon.svg` 등)를 쓰고 **기본 로고로 되돌리기**로 언제든 돌아갑니다.
+관리자 페이지의 **로고**에서 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿉니다. 그림을 올리거나 보관한 그림에서 고릅니다. 관리자 브라우저가 가운데를 정사각형으로 잘라 512·192·180·64px와 둥근 홈 화면용 512px PNG를 만들어 보내고 서버는 PNG 서명과 크기만 확인해 데이터 폴더의 `brand/`에 둡니다. 여백과 홈 화면 배경색을 고를 수 있습니다. 바꾼 그림이 없으면 기본 로고(`web/icon.svg` 등)를 쓰고 **기본 로고로 되돌리기**로 언제든 돌아갑니다.
공개 주소는 `brand/logo`·`brand/favicon`·`brand/apple-touch`·`brand/icon-192`·`brand/icon-512`·`brand/icon-maskable`입니다. 앱 설치 정보 `manifest.webmanifest`는 서버가 서비스 이름과 이 주소로 만들어 줍니다. 홈페이지와 관리자 페이지는 이 주소만 씁니다.
-후보는 최근 40장까지 보관합니다. 따로 만든 그림을 운영 도구로 넣으면 이 목록에 나옵니다. 그림 만들기 키를 설정한 서버에서만 관리자가 쓴 설명으로 한 번에 1~4장을 바로 만드는 칸이 보이고 키가 없으면 그 칸은 숨겨집니다. 키 값은 응답과 기록에 남기지 않습니다. 키 설정은 `brand_admin.py` 머리 설명에 있습니다.
+보관한 그림은 운영 도구로 넣고 관리자 화면에서 고르거나 지웁니다. 목록에는 넣은 날과 넣은 사람만 보입니다.
로고 업로드 `POST /calendar/api/admin/brand-logo`만 요청 한도가 6MB입니다. 앱과 nginx 두 곳에서 같은 주소만 올렸고 다른 요청은 256KB를 지킵니다. 사이트 보안 정책이 blob: 그림을 막아서 올린 파일은 data: 주소로 읽습니다.
-검사: `test_site_admin`의 로고 시험은 가짜 그림 서버를 띄워 키가 머리글로만 전달되는지와 후보 저장·삭제 및 오류 안내를 확인합니다.
+검사: `test_site_admin`의 로고 시험은 그림 올리기와 크기 검사 및 기본 로고로 되돌리기를 확인하고 운영 도구로 넣은 그림의 보관과 적용 및 지우기를 확인합니다.
-### 서버 밖에서 만든 그림 넣기
+### 운영 도구로 그림 넣기
-운영 서버는 그림 만들기 키를 쓰지 않습니다. 따로 만든 그림을 `brand_import.py`로 넣습니다. `add-candidate`는 그림을 후보 목록에 넣고 `apply`는 미리 만든 크기별 PNG 다섯 장으로 로고를 바꿉니다. 둘 다 서비스 계정으로 실행하고 관리 작업 기록에 남습니다. 사용법은 파일 머리 설명에 있습니다.
+`brand_import.py`의 `add-candidate`는 그림을 보관한 그림에 넣고 `apply`는 미리 준비한 크기별 PNG 다섯 장으로 로고를 바꿉니다. 둘 다 서비스 계정으로 실행하고 관리 작업 기록에 남습니다. 사용법은 파일 머리 설명에 있습니다.
관리자 화면은 둥근 사각형 바깥 모서리가 흰 그림을 알아보고 16% 확대해 잘라 내며 배경색을 가장자리 색에 맞춥니다. **확대** 조절로 직접 바꿀 수 있습니다.
diff --git a/server/brand_admin.py b/server/brand_admin.py
index 21be5e5..30910d2 100644
--- a/server/brand_admin.py
+++ b/server/brand_admin.py
@@ -1,40 +1,25 @@
"""로고 그림 관리(관리자 페이지 '로고' 메뉴).
-관리자가 올린 그림이나 후보 그림을 골라 홈페이지 로고와 파비콘 및 홈 화면 아이콘을 바꾼다.
+관리자가 올린 그림이나 보관한 그림을 골라 홈페이지 로고와 파비콘 및 홈 화면 아이콘을 바꾼다.
크기별 PNG는 관리자 브라우저가 만들어 보내고 서버는 PNG 형식과 크기만 확인해 데이터 폴더에 둔다.
-바꾼 그림이 없으면 web 폴더의 기본 로고를 그대로 준다. 새 파이썬 패키지는 쓰지 않는다.
-
-제미나이 키는 systemd LoadCredential(gemini)로만 받는다. 키 값은 응답·기록·화면 어디에도 내보내지 않는다.
-키 넣기: 보조 서버에서 ~/bin/duty-gemini-key.sh (사용자가 직접 실행)
+바꾼 그림이 없으면 web 폴더의 기본 로고를 그대로 준다. 보관한 그림은 운영 도구(brand_import.py)로 넣는다.
+새 파이썬 패키지는 쓰지 않는다.
"""
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
+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
-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"),
@@ -64,65 +49,11 @@ def image_kind(raw):
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)""")
@@ -174,11 +105,8 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
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}
+ "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):
@@ -202,7 +130,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
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, "후보를 확인해 주세요.")
+ raise HTTPException(400, "보관한 그림을 확인해 주세요.")
# 파일마다 임시 이름으로 쓴 뒤 바꿔 끼워 반쯤 바뀐 상태가 보이지 않게 한다.
(brand / "logo.json").unlink(missing_ok=True)
for name, raw in decoded.items():
@@ -213,7 +141,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
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))
+ log(actor["member"], "logo", "올린 그림" if source == "upload" else "보관한 그림 " + str(candidate))
return {"custom": meta}
@app.post(prefix + "/api/admin/brand-logo-reset")
@@ -226,72 +154,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
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)
@@ -299,7 +162,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
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, "후보 그림을 찾을 수 없습니다.")
+ 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}")
@@ -308,7 +171,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
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, "후보 그림을 찾을 수 없습니다.")
+ 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)
diff --git a/server/brand_import.py b/server/brand_import.py
index 3e83e36..712c8a4 100644
--- a/server/brand_import.py
+++ b/server/brand_import.py
@@ -1,13 +1,13 @@
"""로고 그림을 서버에서 직접 넣는 운영 도구.
-관리자 페이지의 '로고' 메뉴와 같은 저장 방식과 검사를 쓴다. 서버 밖에서 만든 그림을
-후보 목록에 넣거나, 미리 만든 크기별 PNG로 로고를 바로 바꿀 때 쓴다. 작업은 관리 작업 기록에 남는다.
+관리자 페이지의 '로고' 메뉴와 같은 저장 방식과 검사를 쓴다. 그림을 관리자 화면의 '보관한 그림'에 넣거나
+미리 준비한 크기별 PNG로 로고를 바로 바꿀 때 쓴다. 작업은 관리 작업 기록에 남는다.
서비스 계정으로 실행한다(데이터 폴더 권한 때문):
sudo -u duty-calendar env DUTY_DATA=/var/lib/duty-calendar /opt/duty-calendar/venv/bin/python brand_import.py \\
- add-candidate 그림.jpg --prompt-file 설명.txt --actor syskiller
+ add-candidate 그림.jpg --actor syskiller
sudo -u duty-calendar env DUTY_DATA=/var/lib/duty-calendar /opt/duty-calendar/venv/bin/python brand_import.py \\
- apply PNG폴더 --candidate 후보ID --actor syskiller (폴더에 logo-512.png logo-192.png logo-180.png logo-64.png logo-maskable.png)
+ apply PNG폴더 --candidate 보관그림ID --actor syskiller (폴더에 logo-512.png logo-192.png logo-180.png logo-64.png logo-maskable.png)
"""
import argparse
import json
@@ -46,7 +46,6 @@ def add_candidate(args):
mime, ext = image_kind(raw)
if not mime or len(raw) > 20_000_000:
sys.exit("PNG·JPG·WebP 그림이 아니거나 너무 큽니다.")
- prompt = Path(args.prompt_file).read_text(encoding="utf8").strip()[:1500] if args.prompt_file else "서버에서 가져온 그림"
folder = DATA / "brand" / "candidates"
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
cid = secrets.token_hex(8)
@@ -54,7 +53,7 @@ def add_candidate(args):
with connect() as conn:
who = actor_id(conn, args.actor)
conn.execute("INSERT INTO brand_candidates(id,created,prompt,model,ext,actor) VALUES(?,?,?,?,?,?)",
- (cid, int(time.time()), prompt, args.model[:80], ext, who))
+ (cid, int(time.time()), "", "운영 도구", ext, who))
log(conn, who, "logo-import", "운영 도구 · " + Path(args.file).name)
print(cid)
@@ -72,7 +71,7 @@ def apply(args):
who = actor_id(conn, args.actor)
name = conn.execute("SELECT display_name FROM members WHERE id=?", (who,)).fetchone()[0]
if args.candidate and not conn.execute("SELECT 1 FROM brand_candidates WHERE id=?", (args.candidate,)).fetchone():
- sys.exit("후보를 찾을 수 없습니다: " + args.candidate)
+ sys.exit("보관한 그림을 찾을 수 없습니다: " + args.candidate)
# 관리자 화면과 같은 순서: 표식을 먼저 지우고 파일을 바꿔 끼운 뒤 표식을 다시 쓴다.
(brand / "logo.json").unlink(missing_ok=True)
for key, raw in data.items():
@@ -83,7 +82,7 @@ def apply(args):
temp = brand / "logo.json.tmp"
temp.write_text(json.dumps(meta, ensure_ascii=False))
temp.replace(brand / "logo.json")
- log(conn, who, "logo", "운영 도구 · " + ("후보 " + args.candidate if args.candidate else "미리 만든 그림"))
+ log(conn, who, "logo", "운영 도구 · " + ("보관한 그림 " + args.candidate if args.candidate else "미리 준비한 그림"))
print("로고를 바꿨습니다.")
@@ -92,8 +91,6 @@ def main():
sub = parser.add_subparsers(dest="command", required=True)
one = sub.add_parser("add-candidate")
one.add_argument("file")
- one.add_argument("--prompt-file")
- one.add_argument("--model", default="서버에서 가져옴")
one.add_argument("--actor", required=True)
two = sub.add_parser("apply")
two.add_argument("folder")
diff --git a/server/release.json b/server/release.json
index 5540b43..4a4b413 100644
--- a/server/release.json
+++ b/server/release.json
@@ -8,6 +8,6 @@
"앱을 열 때마다 새 공지를 확인하고 연결이 없을 때는 마지막으로 받은 공지를 보여 줍니다.",
"Play 프로텍트 차단 해제가 확인된 버전은 아닙니다."
],
- "apkBytes": 882130,
- "apkSha256": "ed53324179b2b96e04e315fc9d6dce1e0149fedae4e1b8c8ee9fef9a088cc7c9"
+ "apkBytes": 880718,
+ "apkSha256": "89169df2ae03bba9da1baacbcb91ae5f70f157fb071cf18afd5b61c11b8336b0"
}
diff --git a/server/site_admin.py b/server/site_admin.py
index f0e885a..370e192 100644
--- a/server/site_admin.py
+++ b/server/site_admin.py
@@ -71,8 +71,8 @@ ACTION_NAMES = {
"rename": "소속 이름 변경", "revoke-invite": "초대코드 종료", "remove-member": "소속에서 내보내기",
"transfer": "소속 관리자 변경", "delete-company": "소속 삭제", "settings": "홈페이지 설정 변경",
"settings-reset": "홈페이지 설정 기본값", "holiday-refresh": "공휴일 자료 갱신",
- "logo": "로고 바꾸기", "logo-reset": "기본 로고로 되돌리기", "logo-generate": "로고 후보 만들기",
- "logo-candidate-delete": "로고 후보 지우기", "logo-import": "로고 후보 가져오기",
+ "logo": "로고 바꾸기", "logo-reset": "기본 로고로 되돌리기",
+ "logo-candidate-delete": "보관한 로고 그림 지우기", "logo-import": "로고 그림 보관",
}
diff --git a/server/test_site_admin.py b/server/test_site_admin.py
index a95e6e2..f724d7e 100644
--- a/server/test_site_admin.py
+++ b/server/test_site_admin.py
@@ -4,11 +4,9 @@
추가 패키지 없이 서버 실행 환경(uvicorn)만 있으면 돌릴 수 있다: python -m unittest test_site_admin
"""
import base64
-import http.server
import json
import os
import struct
-import threading
import zlib
import socket
import subprocess
@@ -21,7 +19,6 @@ import urllib.request
from pathlib import Path
HERE = Path(__file__).parent
-FAKE_KEY = "fake-gemini-key-for-tests-0001"
def png(size, rgb=(38, 54, 77)):
@@ -32,25 +29,6 @@ def png(size, rgb=(38, 54, 77)):
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
-class FakeGemini(http.server.BaseHTTPRequestHandler):
- """제미나이 대신 그림 한 장을 돌려주는 가짜 서버. 받은 요청을 기록한다."""
- calls = []
-
- def do_POST(self):
- body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
- FakeGemini.calls.append({"path": self.path, "key": self.headers.get("x-goog-api-key"), "body": body})
- if "bad-model" in self.path:
- self.send_response(404); self.send_header("Content-Type", "application/json"); self.end_headers()
- self.wfile.write(json.dumps({"error": {"message": "models/bad-model is not found"}}).encode()); return
- image = base64.b64encode(png(300, (182, 91, 60))).decode()
- reply = {"candidates": [{"content": {"parts": [{"text": "여기 있습니다"}, {"inlineData": {"mimeType": "image/png", "data": image}}]}}]}
- self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers()
- self.wfile.write(json.dumps(reply).encode())
-
- def log_message(self, *args):
- pass
-
-
def free_port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
@@ -61,14 +39,9 @@ class SiteAdminTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp = tempfile.TemporaryDirectory()
- cls.fake = http.server.ThreadingHTTPServer(("127.0.0.1", 0), FakeGemini)
- threading.Thread(target=cls.fake.serve_forever, daemon=True).start()
- key_file = Path(cls.temp.name) / "gemini.key"
- key_file.write_text(FAKE_KEY)
cls.port = free_port()
cls.base = "http://127.0.0.1:%d/calendar/" % cls.port
- env = {**os.environ, "DUTY_DATA": cls.temp.name, "DUTY_REFRESH": "0", "DUTY_ORIGIN": "http://127.0.0.1:%d" % cls.port, "PYTHONDONTWRITEBYTECODE": "1",
- "DUTY_GEMINI_URL": "http://127.0.0.1:%d" % cls.fake.server_address[1], "DUTY_GEMINI_KEY_FILE": str(key_file)}
+ env = {**os.environ, "DUTY_DATA": cls.temp.name, "DUTY_REFRESH": "0", "DUTY_ORIGIN": "http://127.0.0.1:%d" % cls.port, "PYTHONDONTWRITEBYTECODE": "1"}
# 최초 관리자는 서버 밖에서만 만들 수 있다(공개 가입으로는 관리자가 되지 않는다).
boot = "import manage; manage.bootstrap({'username':'adminqa','displayName':'관리자시험','password':'Admin-pass-1'}, must_change=False)"
subprocess.run([sys.executable, "-c", boot], cwd=HERE, env=env, check=True, capture_output=True)
@@ -92,8 +65,6 @@ class SiteAdminTest(unittest.TestCase):
cls.server.terminate()
cls.server.wait(10)
cls.server.stderr.close()
- cls.fake.shutdown()
- cls.fake.server_close()
cls.temp.cleanup()
@classmethod
@@ -243,7 +214,9 @@ class SiteAdminTest(unittest.TestCase):
self.assertEqual(manifest["icons"][0]["src"], "brand/icon-192")
state = self.call("api/admin/brand", token=self.admin)[1]
self.assertIsNone(state["custom"])
- self.assertTrue(state["gemini"])
+ # 로고 화면에는 그림을 만드는 기능이 없다. 보관한 그림 목록과 지금 로고만 준다(2026-12-01).
+ self.assertEqual(set(state), {"custom", "candidates"})
+ self.assertEqual(self.call("api/admin/brand-generate", {"prompt": "달력과 초승달 아이콘", "count": 1}, token=self.admin)[0], 404)
member = self.login("memberqa", "Member-pass-1")
self.assertEqual(self.call("api/admin/brand", token=member)[0], 403)
images = {name: base64.b64encode(png(size)).decode() for name, size in (("512", 512), ("192", 192), ("180", 180), ("64", 64), ("maskable", 512))}
@@ -263,49 +236,22 @@ class SiteAdminTest(unittest.TestCase):
self.assertEqual(self.call("api/admin/brand-logo-reset", {}, token=self.admin)[0], 200)
self.assertEqual(self.raw("brand/logo")[1], "image/svg+xml")
- def test_08_gemini_candidates(self):
- self.assertEqual(self.call("api/admin/brand-generate", {"prompt": "짧음", "count": 1}, token=self.admin)[0], 400)
- self.assertEqual(self.call("api/admin/brand-generate", {"prompt": "달력과 초승달 아이콘", "count": 9}, token=self.admin)[0], 400)
- status, body = self.call("api/admin/brand-generate", {"prompt": "달력과 초승달이 있는 앱 아이콘", "model": "gemini-test-image", "count": 2}, token=self.admin)
- self.assertEqual(status, 200, body)
- job = self.wait_job(body["job"])
- self.assertEqual((job["state"], job["made"]), ("done", 2))
- call = FakeGemini.calls[-1]
- self.assertEqual(call["key"], FAKE_KEY)
- self.assertIn("/v1beta/models/gemini-test-image:generateContent", call["path"])
- self.assertEqual(call["body"]["contents"][0]["parts"][0]["text"], "달력과 초승달이 있는 앱 아이콘")
- state = self.call("api/admin/brand", token=self.admin)[1]
- self.assertEqual(len(state["candidates"]), 2)
- self.assertNotIn(FAKE_KEY, json.dumps(state))
- first = state["candidates"][0]["id"]
- status, kind, raw = self.raw("api/admin/brand-candidate/" + first, token=self.admin)
- self.assertEqual((status, kind), (200, "image/png"))
- self.assertEqual(self.raw("api/admin/brand-candidate/" + first, token=self.login("memberqa", "Member-pass-1"))[0], 403)
- self.assertEqual(self.call("api/admin/brand-candidate-delete/" + first, {}, token=self.admin)[0], 200)
- self.assertEqual(len(self.call("api/admin/brand", token=self.admin)[1]["candidates"]), 1)
- # 모델 이름이 틀리면 작업이 실패로 끝나고 원인을 알려 준다.
- job = self.wait_job(self.call("api/admin/brand-generate", {"prompt": "달력과 초승달이 있는 앱 아이콘", "model": "bad-model", "count": 2}, token=self.admin)[1]["job"])
- self.assertEqual(job["state"], "error")
- self.assertIn("404", job["errors"][0])
- actions = {row["action"] for row in self.call("api/admin/log?area=site", token=self.admin)[1]["entries"]}
- self.assertTrue({"logo", "logo-reset", "logo-generate", "logo-candidate-delete"} <= actions, actions)
-
def test_09_import_tool(self):
- # 서버 밖에서 만든 그림(제미나이 구독 agy 등)을 운영 도구로 후보에 넣고 로고로 적용한다.
+ # 운영 도구로 그림을 '보관한 그림'에 넣고 로고로 적용한 뒤 보관한 그림을 지운다.
folder = Path(self.temp.name) / "import"
folder.mkdir()
(folder / "art.png").write_bytes(png(400, (40, 60, 90)))
- (folder / "prompt.txt").write_text("달력과 초승달", encoding="utf8")
for name, size in (("logo-512.png", 512), ("logo-192.png", 192), ("logo-180.png", 180), ("logo-64.png", 64), ("logo-maskable.png", 512)):
(folder / name).write_bytes(png(size, (40, 60, 90)))
env = {**os.environ, "DUTY_DATA": self.temp.name}
run = lambda *args: subprocess.run([sys.executable, "brand_import.py", *args], cwd=HERE, env=env, capture_output=True, text=True)
self.assertNotEqual(run("add-candidate", str(folder / "art.png"), "--actor", "memberqa").returncode, 0)
- done = run("add-candidate", str(folder / "art.png"), "--prompt-file", str(folder / "prompt.txt"), "--model", "agy 시험", "--actor", "adminqa")
+ done = run("add-candidate", str(folder / "art.png"), "--actor", "adminqa")
self.assertEqual(done.returncode, 0, done.stderr)
cid = done.stdout.strip()
state = self.call("api/admin/brand", token=self.admin)[1]
self.assertIn(cid, [row["id"] for row in state["candidates"]])
+ self.assertEqual(set(state["candidates"][0]), {"id", "created", "actor"})
(folder / "logo-64.png").write_bytes(png(32))
self.assertNotEqual(run("apply", str(folder), "--candidate", cid, "--actor", "adminqa").returncode, 0)
(folder / "logo-64.png").write_bytes(png(64))
@@ -318,14 +264,13 @@ class SiteAdminTest(unittest.TestCase):
# 두 기록은 같은 초에 남을 수 있어 순서는 보지 않는다(2026-11-25 전체 시험에서 한 번 뒤바뀜).
self.assertEqual(set(actions[:2]), {"logo", "logo-import"})
self.assertEqual(self.call("api/admin/brand-logo-reset", {}, token=self.admin)[0], 200)
-
- def wait_job(self, job_id):
- for _ in range(100):
- job = self.call("api/admin/brand-job/" + job_id, token=self.admin)[1]
- if job["state"] != "running":
- return job
- time.sleep(0.1)
- self.fail("후보 만들기가 끝나지 않았습니다")
+ status, kind, _ = self.raw("api/admin/brand-candidate/" + cid, token=self.admin)
+ self.assertEqual((status, kind), (200, "image/png"))
+ self.assertEqual(self.raw("api/admin/brand-candidate/" + cid, token=self.login("memberqa", "Member-pass-1"))[0], 403)
+ self.assertEqual(self.call("api/admin/brand-candidate-delete/" + cid, {}, token=self.admin)[0], 200)
+ self.assertNotIn(cid, [row["id"] for row in self.call("api/admin/brand", token=self.admin)[1]["candidates"]])
+ entries = self.call("api/admin/log?area=site", token=self.admin)[1]["entries"]
+ self.assertIn("logo-candidate-delete", {row["action"] for row in entries})
@classmethod
def raw(cls, path, token=None):
diff --git a/server/web/admin.html b/server/web/admin.html
index 9b8fa93..c61698a 100644
--- a/server/web/admin.html
+++ b/server/web/admin.html
@@ -101,19 +101,13 @@
지금 쓰는 로고
PNG·JPG·WebP 그림을 고르면 가운데를 정사각형으로 잘라 크기별 아이콘을 만듭니다. 512px 이상인 그림을 권합니다.
PNG·JPG·WebP 그림을 고르면 가운데를 정사각형으로 잘라 크기별 아이콘을 만듭니다. 512px 이상인 그림을 권합니다.
둥근 홈 화면과 아이폰 아이콘은 투명한 곳을 배경색으로 채웁니다. 그림 바깥 모서리가 흰색이면 확대로 잘라 내세요(자동으로 맞춰 둡니다).
만든 후보는 최근 40장까지 보관합니다. 고르기를 누르면 위 미리보기에서 확인한 뒤 바꿀 수 있습니다.
보관해 둔 로고 그림입니다. 고르기를 누르면 위 미리보기에서 확인한 뒤 바꿀 수 있습니다.