Compare commits
9
Commits
poster-20261113
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3f48094f3 | ||
|
|
1c6bbf3018 | ||
|
|
3ee96dd741 | ||
|
|
b8138151ec | ||
|
|
7b1030b17e | ||
|
|
234fc5510d | ||
|
|
6d50969caa | ||
|
|
2141d6fd82 | ||
|
|
b33b149555 |
No files matched your search
@@ -16,6 +16,25 @@ Docker 镜像内置:calibre(`ebook-convert`)、ffmpeg、Piper(本地 TTS
|
||||
|
||||
镜像也可直接拉取:`192.168.68.19:3200/jinghui/it-tools-relay:latest`(Gitea Container Registry,免登录)。
|
||||
|
||||
## 授权功能接口
|
||||
|
||||
| 接口 | 方法 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `/ai/face-swap` | POST | AI 换脸(授权):multipart `source`/`target`(文件)+ `consent=1`(必填授权承诺),需 `X-Machine-Id` 头;多脸取最大,返回站内图片 URL |
|
||||
| `/ai/gen-image` | POST | AI 生图(每日免费额度):JSON `machine`/`prompt`/`model`/`width`/`height`;尺寸需按模型档位传(dall-e-3 仅 1024×1024 / 1792×1024 / 1024×1792) |
|
||||
| `/ai/image-models` | GET | 生图模型列表 |
|
||||
| `/draft/save` | POST | 草稿保存(全站自动保存):JSON `machine`/`tool`/`state`,落盘 `data/drafts/<machine>/<tool>.json`,state 上限 300KB;需 `X-Machine-Id` 头,`tool` 做路径穿越防护 |
|
||||
| `/draft/load` | GET | 草稿读取:`?machine=&tool=`,无草稿返回 `data: null` |
|
||||
| `/draft/delete` | POST | 草稿删除:离开站点时清理,返回 `deleted: true/false` |
|
||||
|
||||
| `/admin/tools` | GET | 授权应用管理(需 `X-Admin-Token`):返回全部 18 个 slug 的 `visible`/`trial_minutes` + `default_trial` |
|
||||
| `/admin/tools` | POST | 保存显示开关与试用时长:JSON `{tools: {slug: {visible, trial_minutes}}}`,合并写 `data/tool_config.json`(trial_minutes 限 1–1440 分钟) |
|
||||
| `/tool-config` | GET | 公开配置:前台显示开关与试用时长(只回非默认项,缺省即默认),供前端菜单/定价/试用浮条消费 |
|
||||
`PROTECTED_TOOLS` 集合含 `face-swap`、`poster-maker`(海报前端门控),与前端 `license.ts` 双端同步。
|
||||
|
||||
|
||||
`PROTECTED_TOOLS` 集合含 `face-swap`、`poster-maker`(海报前端门控),与前端 `license.ts` 双端同步。每日试用时长按功能覆盖默认 `TRIAL_MS_MIN`(`trial_allowed` 读 `tool_config.json` 的 `trial_minutes`,未配置走默认)。
|
||||
|
||||
## 环境变量(`.env`)
|
||||
|
||||
```bash
|
||||
|
||||
+2
-1
@@ -76,7 +76,8 @@ def mcp_usage_query(days: int = 7) -> dict:
|
||||
conn = sqlite3.connect(_CTX["usage_db"])
|
||||
rows = conn.execute(
|
||||
"SELECT token_tail, machine, tool, ok, err, dur_ms, at FROM mcp_usage "
|
||||
"WHERE at>? ORDER BY at DESC LIMIT 300", (since,)).fetchall()
|
||||
# 铁规则:所有功能历史最多显示 100 条
|
||||
"WHERE at>? ORDER BY at DESC LIMIT 100", (since,)).fetchall()
|
||||
by_tool = conn.execute(
|
||||
"SELECT tool, COUNT(*), SUM(ok) FROM mcp_usage WHERE at>? GROUP BY tool ORDER BY COUNT(*) DESC",
|
||||
(since,)).fetchall()
|
||||
|
||||
@@ -21,6 +21,7 @@ Trial state persisted to /app/data/trials.json (mounted volume).
|
||||
import cgi
|
||||
import io
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
@@ -183,6 +184,44 @@ def _today_start(now_ms: int) -> int:
|
||||
return (now_ms + TZ_OFFSET_MS) // DAY_MS * DAY_MS - TZ_OFFSET_MS
|
||||
|
||||
|
||||
|
||||
# ---------- 授权应用配置:前台显示开关 + 每工具每日试用时长(管理后台可改) ----------
|
||||
def _tool_cfg_path() -> str:
|
||||
return os.path.join(DATA_DIR, "tool_config.json")
|
||||
|
||||
def _load_tool_cfg() -> dict:
|
||||
try:
|
||||
with open(_tool_cfg_path(), encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _save_tool_cfg(cfg: dict) -> None:
|
||||
with open(_tool_cfg_path(), "w", encoding="utf-8") as f:
|
||||
json.dump(cfg, f, ensure_ascii=False, indent=2)
|
||||
|
||||
def _cfg_int(d: dict, key: str, default: int) -> int:
|
||||
try:
|
||||
n = int(d.get(key))
|
||||
return n if 1 <= n <= 1440 else default
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
def tool_visible(tool: str) -> bool:
|
||||
"""前台是否显示该应用(管理后台开关;默认显示)"""
|
||||
v = _load_tool_cfg().get("visible")
|
||||
if isinstance(v, dict):
|
||||
return bool(v.get(tool, True))
|
||||
return True
|
||||
|
||||
def trial_minutes_of(tool: str) -> int:
|
||||
"""该应用每日免费试用时长(分钟,默认 TRIAL_MS_MIN)"""
|
||||
t = _load_tool_cfg().get("trial_minutes")
|
||||
if isinstance(t, dict):
|
||||
return _cfg_int(t, tool, TRIAL_MS // 60000)
|
||||
return TRIAL_MS // 60000
|
||||
|
||||
def trial_allowed(machine: str, tool: str) -> bool:
|
||||
key = f"{machine}|{tool}"
|
||||
now_ms = int(time.time() * 1000)
|
||||
@@ -196,7 +235,7 @@ def trial_allowed(machine: str, tool: str) -> bool:
|
||||
trials[key] = now_ms
|
||||
_save_trials(trials)
|
||||
return True
|
||||
return (now_ms - start) < TRIAL_MS
|
||||
return (now_ms - start) < trial_minutes_of(tool) * 60 * 1000
|
||||
|
||||
|
||||
# ---------- AI 生图页:每日免费次数(未授权;北京时间 0 点重置,自带 KEY 不计次) ----------
|
||||
@@ -716,6 +755,7 @@ _FACE_LOCK = threading.Lock()
|
||||
_FACE_APP = None
|
||||
_FACE_SWAP = None
|
||||
_FACE_MODELS_DIR = os.environ.get("FACE_MODELS_DIR", "/app/face-models")
|
||||
_GFPGAN_SESS = None
|
||||
|
||||
|
||||
def _face_engine():
|
||||
@@ -737,6 +777,67 @@ def _largest_face(faces):
|
||||
return max(faces, key=lambda f: float((f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])))
|
||||
|
||||
|
||||
def _gfpgan_session():
|
||||
global _GFPGAN_SESS
|
||||
if _GFPGAN_SESS is None:
|
||||
import onnxruntime as _ort
|
||||
path = os.path.join(_FACE_MODELS_DIR, "gfpgan_1.4.onnx")
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
_GFPGAN_SESS = _ort.InferenceSession(path, providers=["CPUExecutionProvider"])
|
||||
return _GFPGAN_SESS
|
||||
|
||||
|
||||
def _gfpgan_enhance(img):
|
||||
"""用 GFPGAN 对图中最大人脸做修复增强,返回增强后的整图(失败则原样返回)。"""
|
||||
try:
|
||||
import cv2 as _cv2
|
||||
import numpy as _np
|
||||
sess = _gfpgan_session()
|
||||
if sess is None:
|
||||
return img
|
||||
app, _ = _face_engine()
|
||||
faces = app.get(img)
|
||||
if not faces:
|
||||
return img
|
||||
f = _largest_face(faces)
|
||||
x1, y1, x2, y2 = [int(v) for v in f.bbox]
|
||||
h, w = img.shape[:2]
|
||||
# 扩展 bbox
|
||||
pad = int(0.25 * max(x2 - x1, y2 - y1))
|
||||
x1 = max(0, x1 - pad); y1 = max(0, y1 - pad)
|
||||
x2 = min(w, x2 + pad); y2 = min(h, y2 + pad)
|
||||
crop = img[y1:y2, x1:x2]
|
||||
if crop.size == 0:
|
||||
return img
|
||||
inp = _cv2.resize(crop, (512, 512))
|
||||
inp = _cv2.cvtColor(inp, _cv2.COLOR_BGR2RGB).astype("float32") / 255.0
|
||||
inp = (inp - 0.5) / 0.5
|
||||
inp = _np.transpose(inp, (2, 0, 1))[None, ...].astype("float32")
|
||||
out = sess.run(None, {sess.get_inputs()[0].name: inp})[0]
|
||||
out = out[0].transpose(1, 2, 0)
|
||||
out = (out * 0.5 + 0.5) * 255.0
|
||||
out = _np.clip(out, 0, 255).astype("uint8")
|
||||
out = _cv2.cvtColor(out, _cv2.COLOR_RGB2BGR)
|
||||
out = _cv2.resize(out, (x2 - x1, y2 - y1))
|
||||
# 羽化混合
|
||||
mask = _np.zeros((y2 - y1, x2 - x1), dtype="float32")
|
||||
cx, cy = (x2 - x1) // 2, (y2 - y1) // 2
|
||||
# 简单中心渐变蒙版
|
||||
Y, X = _np.ogrid[:y2-y1, :x2-x1]
|
||||
dist = _np.sqrt((X - cx) ** 2 + (Y - cy) ** 2)
|
||||
r = min(cx, cy)
|
||||
mask = _np.clip(1 - dist / max(r, 1), 0, 1)
|
||||
mask = mask[..., None]
|
||||
blended = (out.astype("float32") * mask + crop.astype("float32") * (1 - mask)).astype("uint8")
|
||||
res = img.copy()
|
||||
res[y1:y2, x1:x2] = blended
|
||||
return res
|
||||
except Exception as e:
|
||||
print(f"[gfpgan] enhance failed: {e}", flush=True)
|
||||
return img
|
||||
|
||||
|
||||
def _face_swap_run(src_img, dst_img):
|
||||
"""源人脸 -> 目标照片。返回 (jpg字节|None, 错误信息, 耗时ms)。加锁串行避免并发吃满 CPU。"""
|
||||
import cv2 as _cv2
|
||||
@@ -750,6 +851,9 @@ def _face_swap_run(src_img, dst_img):
|
||||
if not dst_faces:
|
||||
return None, "目标图中未检测到人脸,请换一张含人物的照片", 0
|
||||
out = swap.get(dst_img, _largest_face(dst_faces), _largest_face(src_faces), paste_back=True)
|
||||
# GFPGAN 修复增强(可选)
|
||||
if os.environ.get("FACE_SWAP_GFPGAN", "1") != "0":
|
||||
out = _gfpgan_enhance(out)
|
||||
ok, buf = _cv2.imencode(".jpg", out, [int(_cv2.IMWRITE_JPEG_QUALITY), 92])
|
||||
if not ok:
|
||||
return None, "结果编码失败", 0
|
||||
@@ -1211,6 +1315,21 @@ def _admin_auth(handler) -> bool:
|
||||
tok = handler.headers.get("X-Admin-Token", "")
|
||||
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
|
||||
return True
|
||||
# query token fallback: <img src> / <a download> 无法携带 header,缩略图与下载走 ?token=
|
||||
if not tok:
|
||||
try:
|
||||
tok = (parse.parse_qs(parse.urlparse(handler.path).query).get("token") or [""])[0]
|
||||
except Exception:
|
||||
tok = ""
|
||||
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
|
||||
return True
|
||||
if tok:
|
||||
acc = _parse_token(tok)
|
||||
if acc:
|
||||
role, disabled = _user_attr(acc)
|
||||
if role == "admin" and not disabled:
|
||||
return True
|
||||
tok = ""
|
||||
# channel 2: logged-in admin account
|
||||
auth = handler.headers.get("Authorization", "")
|
||||
if auth.lower().startswith("bearer "):
|
||||
@@ -1278,26 +1397,170 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
"totals": {"users": len(out_users), "files": total_files, "size": total_size},
|
||||
}}
|
||||
|
||||
# ---- 统一文件下载/缩略图:path 相对 DATA_DIR(users/、gen_images/、mcp_files/ 白名单)----
|
||||
# 鉴权走 _admin_auth(支持 header 或 ?token=,因 <img src>/<a download> 无法带 header)
|
||||
if method == "GET" and sub == "/file":
|
||||
qs = parse.parse_qs(parse.urlparse(handler.path).query)
|
||||
rel = (qs.get("path") or [""])[0]
|
||||
as_dl = (qs.get("dl") or [""])[0] == "1"
|
||||
disp_q = (qs.get("name") or [""])[0]
|
||||
if not rel or rel.startswith("/") or ".." in rel.split("/"):
|
||||
return 400, {"code": 400, "message": "参数错误"}
|
||||
if rel.split("/")[0] not in ("users", "gen_images", "mcp_files"):
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
root = os.path.realpath(DATA_DIR)
|
||||
fp = os.path.realpath(os.path.join(root, rel))
|
||||
if not fp.startswith(root + os.sep) or not os.path.isfile(fp):
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
try:
|
||||
with open(fp, "rb") as fh:
|
||||
data = fh.read()
|
||||
except OSError:
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
disp = os.path.basename(disp_q.replace(chr(92), "/")) if disp_q else os.path.basename(fp)
|
||||
disp = re.sub(r'[\r\n"]+', '', disp)[:180] or os.path.basename(fp)
|
||||
ctype = mimetypes.guess_type(fp)[0] or "application/octet-stream"
|
||||
handler.send_response(200)
|
||||
handler.send_header("Content-Type", ctype)
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
if as_dl:
|
||||
handler.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + parse.quote(disp))
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
return None, None
|
||||
|
||||
# ---- 文件管理:默认全量聚合(所有用户文件 + AI 生成图片 + MCP 产出),50/页分页 ----
|
||||
if method == "GET" and sub.startswith("/files"):
|
||||
qs = parse.parse_qs(parse.urlparse(handler.path).query)
|
||||
username = (qs.get("username") or [""])[0]
|
||||
if not username or "/" in username or ".." in username:
|
||||
scope = (qs.get("scope") or [""])[0]
|
||||
kind = (qs.get("kind") or [""])[0] # 按功能筛选:gen/face-swap/poster/... 或 __none__=未分类
|
||||
try:
|
||||
page = max(1, int((qs.get("page") or ["1"])[0]))
|
||||
except Exception:
|
||||
page = 1
|
||||
try:
|
||||
page_size = min(200, max(1, int((qs.get("page_size") or ["50"])[0])))
|
||||
except Exception:
|
||||
page_size = 50
|
||||
if username and ("/" in username or ".." in username):
|
||||
return 400, {"code": 400, "message": "参数错误"}
|
||||
fdir = os.path.join(_user_dir(username), "files")
|
||||
files = []
|
||||
total = 0
|
||||
for root, _d, fs in os.walk(fdir):
|
||||
kind = os.path.basename(root) if root != fdir else ""
|
||||
for f in fs:
|
||||
fp = os.path.join(root, f)
|
||||
IMG_EXT = {"png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "avif", "ico"}
|
||||
items = []
|
||||
want_user = scope not in ("gen", "mcp")
|
||||
want_gen = scope in ("", "gen")
|
||||
want_mcp = scope in ("", "mcp")
|
||||
if username: # 指定用户时只看该用户文件(兼容旧下拉语义)
|
||||
want_user, want_gen, want_mcp = True, False, False
|
||||
# 1) 用户上传文件(磁盘是 uuid 名 -> DB 取真实文件名/mime)
|
||||
if want_user:
|
||||
db_meta = {}
|
||||
try:
|
||||
conn = _db()
|
||||
for fid, un, nm, mi in conn.execute("SELECT id, username, name, mime FROM files").fetchall():
|
||||
db_meta[(un, fid)] = (nm or fid, mi or "")
|
||||
conn.close()
|
||||
except Exception:
|
||||
db_meta = {}
|
||||
uroots = [username] if username else (
|
||||
sorted(os.listdir(USERS_ROOT)) if os.path.isdir(USERS_ROOT) else [])
|
||||
for u in uroots:
|
||||
fdir = os.path.join(USERS_ROOT, u, "files")
|
||||
if not os.path.isdir(fdir):
|
||||
continue
|
||||
for root, _d, fs in os.walk(fdir):
|
||||
ukind = os.path.basename(root) if root != fdir else ""
|
||||
for f in fs:
|
||||
fp = os.path.join(root, f)
|
||||
try:
|
||||
st = os.stat(fp)
|
||||
except OSError:
|
||||
continue
|
||||
nm, mi = db_meta.get((u, f), (f, ""))
|
||||
ext = os.path.splitext(nm)[1].lower().lstrip(".")
|
||||
items.append({
|
||||
"id": f, "name": nm, "kind": ukind, "size": st.st_size,
|
||||
"mtime": int(st.st_mtime), "source": "user", "username": u,
|
||||
"mime": mi, "is_image": mi.startswith("image/") or ext in IMG_EXT,
|
||||
"file_type": (ext or (mi.split("/")[-1] if mi else "file") or "file").upper(),
|
||||
"path": os.path.relpath(fp, DATA_DIR),
|
||||
})
|
||||
# 2) AI 生成图片(换脸/生图/海报/编辑,跨所有机器聚合 gen_images/*/)
|
||||
if want_gen:
|
||||
groot = os.path.join(DATA_DIR, "gen_images")
|
||||
for m in (sorted(os.listdir(groot)) if os.path.isdir(groot) else []):
|
||||
gdir = os.path.join(groot, m)
|
||||
if not os.path.isdir(gdir):
|
||||
continue
|
||||
idx = {}
|
||||
try:
|
||||
idxp = os.path.join(gdir, "index.json")
|
||||
for it in (json.load(open(idxp, encoding="utf-8")) if os.path.exists(idxp) else []):
|
||||
if isinstance(it, dict):
|
||||
idx[str(it.get("id"))] = it
|
||||
except Exception:
|
||||
idx = {}
|
||||
for f in os.listdir(gdir):
|
||||
if f == "index.json":
|
||||
continue
|
||||
fp = os.path.join(gdir, f)
|
||||
try:
|
||||
st = os.stat(fp)
|
||||
except OSError:
|
||||
continue
|
||||
iid = os.path.splitext(f)[0]
|
||||
meta = idx.get(iid, {})
|
||||
ext = os.path.splitext(f)[1].lower().lstrip(".")
|
||||
items.append({
|
||||
"id": iid, "name": f, "kind": str(meta.get("kind") or "gen"),
|
||||
"size": st.st_size, "mtime": int(st.st_mtime), "machine": m,
|
||||
"prompt": str(meta.get("prompt") or ""), "url": f"/relay/ai/img/{m}/{iid}",
|
||||
"source": "gen", "username": "", "mime": f"image/{ext}",
|
||||
"is_image": ext in IMG_EXT, "file_type": (ext or "img").upper(),
|
||||
"path": os.path.relpath(fp, DATA_DIR),
|
||||
})
|
||||
# 3) MCP 产出文件(data/mcp_files/)
|
||||
if want_mcp:
|
||||
mroot = os.path.join(DATA_DIR, "mcp_files")
|
||||
for f in (sorted(os.listdir(mroot)) if os.path.isdir(mroot) else []):
|
||||
fp = os.path.join(mroot, f)
|
||||
if not os.path.isfile(fp):
|
||||
continue
|
||||
try:
|
||||
st = os.stat(fp)
|
||||
except OSError:
|
||||
continue
|
||||
total += st.st_size
|
||||
files.append({"id": f, "name": f, "kind": kind, "size": st.st_size, "mtime": int(st.st_mtime)})
|
||||
files.sort(key=lambda x: -x["mtime"])
|
||||
return 200, {"code": 200, "message": "ok", "data": {"files": files, "total_size": total, "count": len(files)}}
|
||||
ext = os.path.splitext(f)[1].lower().lstrip(".")
|
||||
items.append({
|
||||
"id": f, "name": f, "kind": "mcp", "size": st.st_size,
|
||||
"mtime": int(st.st_mtime), "source": "mcp", "username": "",
|
||||
"mime": "", "is_image": ext in IMG_EXT,
|
||||
"file_type": (ext or "file").upper(),
|
||||
"path": os.path.relpath(fp, DATA_DIR),
|
||||
})
|
||||
# 按功能(kind)分布:在 kind 过滤之前统计,下拉计数反映 scope/username 下的全集
|
||||
_kc: dict = {}
|
||||
for x in items:
|
||||
k = str(x.get("kind") or "").strip() or "__none__"
|
||||
_kc[k] = _kc.get(k, 0) + 1
|
||||
kinds = sorted(({"k": k, "n": n} for k, n in _kc.items()), key=lambda y: (-y["n"], y["k"]))
|
||||
if kind:
|
||||
if kind == "__none__":
|
||||
items = [x for x in items if not str(x.get("kind") or "").strip()]
|
||||
else:
|
||||
items = [x for x in items if str(x.get("kind") or "").strip() == kind]
|
||||
items.sort(key=lambda x: -x["mtime"])
|
||||
total = len(items)
|
||||
total_size = sum(x["size"] for x in items)
|
||||
pages = max(1, (total + page_size - 1) // page_size)
|
||||
page = min(page, pages)
|
||||
start = (page - 1) * page_size
|
||||
page_items = items[start:start + page_size]
|
||||
return 200, {"code": 200, "message": "ok", "data": {
|
||||
"files": page_items, "total": total, "total_size": total_size,
|
||||
"page": page, "page_size": page_size, "pages": pages, "count": len(page_items),
|
||||
"kinds": kinds,
|
||||
}}
|
||||
|
||||
if method == "POST" and sub == "/cleanup":
|
||||
before = int(payload.get("before") or 0)
|
||||
@@ -1340,8 +1603,45 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
if method == "POST" and sub == "/delete-file":
|
||||
file_id = str(payload.get("id") or "")
|
||||
username = str(payload.get("username") or "")
|
||||
# MCP 文件删除:username 特殊标记 __mcp__,id=文件名(可含扩展名)
|
||||
if username == "__mcp__":
|
||||
if not file_id or file_id != os.path.basename(file_id) or file_id in (".", ".."):
|
||||
return 400, {"code": 400, "message": "参数错误"}
|
||||
mroot = os.path.realpath(os.path.join(DATA_DIR, "mcp_files"))
|
||||
fp2 = os.path.realpath(os.path.join(mroot, file_id))
|
||||
if not fp2.startswith(mroot + os.sep) or not os.path.isfile(fp2):
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
size2 = os.path.getsize(fp2)
|
||||
os.remove(fp2)
|
||||
return 200, {"code": 200, "message": "ok", "data": {"freed": size2}}
|
||||
if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id) or not username:
|
||||
return 400, {"code": 400, "message": "参数错误"}
|
||||
# AI 生成图片删除:username 为特殊标记 __gen__,带 machine 定位 gen_images/<machine>/
|
||||
if username == "__gen__":
|
||||
machine = str(payload.get("machine") or "")
|
||||
if not re.fullmatch(r"\d{10,16}", machine):
|
||||
return 400, {"code": 400, "message": "参数错误"}
|
||||
gdir = os.path.join(DATA_DIR, "gen_images", machine)
|
||||
target = None
|
||||
if os.path.isdir(gdir):
|
||||
for fn in os.listdir(gdir):
|
||||
if fn.startswith(file_id + ".") and os.path.isfile(os.path.join(gdir, fn)):
|
||||
target = os.path.join(gdir, fn)
|
||||
break
|
||||
if not target:
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
size = os.path.getsize(target)
|
||||
os.remove(target)
|
||||
idxp = os.path.join(gdir, "index.json")
|
||||
with GEN_IMG_LOCK:
|
||||
try:
|
||||
idx = json.load(open(idxp, encoding="utf-8")) if os.path.exists(idxp) else []
|
||||
idx = [it for it in idx if str((it or {}).get("id")) != file_id]
|
||||
with open(idxp, "w", encoding="utf-8") as f:
|
||||
json.dump(idx, f, ensure_ascii=False)
|
||||
except Exception:
|
||||
pass
|
||||
return 200, {"code": 200, "message": "ok", "data": {"freed": size}}
|
||||
base = os.path.join(_user_dir(username), "files")
|
||||
target = os.path.join(base, file_id)
|
||||
if not os.path.exists(target):
|
||||
@@ -1488,8 +1788,48 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
_save_feedback(items)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
# ---- 授权应用管理:显示开关 + 每工具试用时长 ----
|
||||
if method == "GET" and sub == "/tools":
|
||||
cfg = _load_tool_cfg()
|
||||
vis = cfg.get("visible") if isinstance(cfg.get("visible"), dict) else {}
|
||||
tr = cfg.get("trial_minutes") if isinstance(cfg.get("trial_minutes"), dict) else {}
|
||||
dflt = TRIAL_MS // 60000
|
||||
tools = []
|
||||
for t in sorted(PROTECTED_TOOLS):
|
||||
tools.append({"slug": t, "visible": bool(vis.get(t, True)),
|
||||
"trial_minutes": _cfg_int(tr, t, dflt)})
|
||||
return 200, {"code": 200, "message": "ok",
|
||||
"data": {"tools": tools, "default_trial": dflt}}
|
||||
|
||||
if method == "POST" and sub == "/tools":
|
||||
upd = payload.get("tools")
|
||||
if not isinstance(upd, dict) or not upd:
|
||||
return 400, {"code": 400, "message": "缺少 tools 配置"}
|
||||
cfg = _load_tool_cfg()
|
||||
vis = cfg.get("visible") if isinstance(cfg.get("visible"), dict) else {}
|
||||
tr = cfg.get("trial_minutes") if isinstance(cfg.get("trial_minutes"), dict) else {}
|
||||
dflt = TRIAL_MS // 60000
|
||||
applied = 0
|
||||
for slug, item in upd.items():
|
||||
if slug not in PROTECTED_TOOLS or not isinstance(item, dict):
|
||||
continue
|
||||
if "visible" in item:
|
||||
vis[slug] = bool(item["visible"])
|
||||
if "trial_minutes" in item:
|
||||
tr[slug] = _cfg_int(item, "trial_minutes", dflt)
|
||||
applied += 1
|
||||
if applied == 0:
|
||||
return 400, {"code": 400, "message": "没有有效的应用配置"}
|
||||
try:
|
||||
_save_tool_cfg({"visible": vis, "trial_minutes": tr})
|
||||
except Exception as e:
|
||||
return 500, {"code": 500, "message": f"保存失败:{e}"}
|
||||
return 200, {"code": 200, "message": "已保存", "data": {"applied": applied}}
|
||||
|
||||
if method == "GET" and sub == "/storage":
|
||||
total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0
|
||||
if os.path.isdir(os.path.join(DATA_DIR, "gen_images")):
|
||||
total += _dir_size(os.path.join(DATA_DIR, "gen_images"))
|
||||
for extra in ("users.db", "usage.db", "trials.json"):
|
||||
fp = os.path.join(DATA_DIR, extra)
|
||||
if os.path.exists(fp):
|
||||
@@ -1531,10 +1871,10 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
os.remove(probe)
|
||||
except Exception as e:
|
||||
return 400, {"code": 400, "message": f"目标路径不可写: {e}"}
|
||||
# migrate existing data (users dir + db files)
|
||||
# migrate existing data (users dir + AI 生成图片 + db files)
|
||||
moved = []
|
||||
old_root = DATA_DIR
|
||||
for item in ("users",):
|
||||
for item in ("users", "gen_images"):
|
||||
src = os.path.join(old_root, item)
|
||||
dst = os.path.join(new_root, item)
|
||||
if os.path.isdir(src) and not os.path.isdir(dst):
|
||||
@@ -2089,6 +2429,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
status, body = admin_api(method, sub, payload, self)
|
||||
if status is None:
|
||||
return # 二进制下载分支已自行写出响应
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
# ---------- 网速测试(用户浏览器 <-> 本站服务器) ----------
|
||||
@@ -2151,6 +2493,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/img-history":
|
||||
self._handle_img_history()
|
||||
return
|
||||
if parsed.path == "/draft/load":
|
||||
self._handle_draft_load(parsed)
|
||||
return
|
||||
if parsed.path == "/draft/history":
|
||||
self._handle_draft_history(parsed)
|
||||
return
|
||||
if parsed.path.startswith("/ai/img/"):
|
||||
self._handle_img_file(parsed)
|
||||
return
|
||||
@@ -2247,6 +2595,24 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
if parsed.path == "/tool-config":
|
||||
# 公开:前台显示开关与试用时长(只回非默认项,缺省即默认)
|
||||
cfg = _load_tool_cfg()
|
||||
dflt = TRIAL_MS // 60000
|
||||
vis = cfg.get("visible") if isinstance(cfg.get("visible"), dict) else {}
|
||||
tr = cfg.get("trial_minutes") if isinstance(cfg.get("trial_minutes"), dict) else {}
|
||||
hidden = {k: False for k, v in vis.items() if k in PROTECTED_TOOLS and v is False}
|
||||
custom = {}
|
||||
for k in PROTECTED_TOOLS:
|
||||
n = _cfg_int(tr, k, dflt)
|
||||
if n != dflt:
|
||||
custom[k] = n
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {
|
||||
"defaults": {"visible": True, "trial_minutes": dflt},
|
||||
"visible": hidden, "trial_minutes": custom,
|
||||
}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
if parsed.path == "/check":
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
tool = self.headers.get("X-Tool", "")
|
||||
@@ -3166,6 +3532,15 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/gen-image":
|
||||
self._handle_gen_image()
|
||||
return
|
||||
if parsed.path == "/ai/img-save":
|
||||
self._handle_img_save()
|
||||
return
|
||||
if parsed.path == "/draft/save":
|
||||
self._handle_draft_save()
|
||||
return
|
||||
if parsed.path == "/draft/delete":
|
||||
self._handle_draft_delete()
|
||||
return
|
||||
if parsed.path == "/ai/edit-image":
|
||||
self._handle_edit_image()
|
||||
return
|
||||
@@ -3395,11 +3770,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
msg = str(err or d.get("message") or "")
|
||||
raise RuntimeError(msg[:300] or "上游未返回图片")
|
||||
|
||||
def _persist_gen_image(self, machine, d, model, prompt, w, h, kind="gen"):
|
||||
def _hist_owner(self, machine):
|
||||
"""历史归属:登录账号优先,未登录回落机器码(铁规则:只看本人历史)。"""
|
||||
u = _auth_user(self)
|
||||
return u if u else machine
|
||||
|
||||
def _persist_gen_image(self, machine, d, model, prompt, w, h, kind="gen", owner=None):
|
||||
"""把生成结果落盘并写入该机器的历史索引;返回站内图片 URL(任何失败返回空串)。"""
|
||||
try:
|
||||
if not self._gen_machine_ok(machine):
|
||||
return ""
|
||||
if owner is None:
|
||||
owner = self._hist_owner(machine)
|
||||
items = (d or {}).get("data") or []
|
||||
if not items:
|
||||
return ""
|
||||
@@ -3451,6 +3833,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
idx.insert(0, {"id": iid, "file": fname, "at": int(time.time()),
|
||||
"model": str(model)[:60], "prompt": str(prompt)[:500],
|
||||
"kind": str(kind or "gen")[:20],
|
||||
"owner": str(owner)[:64],
|
||||
"w": w, "h": h})
|
||||
while len(idx) > 100:
|
||||
old = idx.pop() or {}
|
||||
@@ -3541,26 +3924,257 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": ids[:200]}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_img_save(self):
|
||||
"""导出海报/成片落盘:客户端把 PNG base64 POST 上来,写入该机器的图片历史。"""
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
tool = str(payload.get("tool") or "poster-maker")[:40]
|
||||
if tool in PROTECTED_TOOLS:
|
||||
if check(machine, tool) != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或今日免费试用已用完"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
elif not MACHINE_RE.match(machine or ""):
|
||||
# 免费工具历史落盘:仅要求合法机器码,不走授权门禁
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
b64 = str(payload.get("b64") or "")
|
||||
if "," in b64[:100]:
|
||||
b64 = b64.split(",", 1)[1]
|
||||
if not b64:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "缺少图片数据"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if len(b64) > 40 * 1024 * 1024:
|
||||
self._reply(413, json.dumps({"code": 413, "message": "图片超过 30MB 限制"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
prompt = str(payload.get("prompt") or "海报导出")[:500]
|
||||
model = str(payload.get("model") or "AI海报")[:60]
|
||||
d = {"data": [{"b64_json": b64}]}
|
||||
img_url = self._persist_gen_image(machine, d, model, prompt, 0, 0, kind=str(payload.get("kind") or "poster")[:20])
|
||||
if not img_url:
|
||||
self._reply(500, json.dumps({"code": 500, "message": "保存失败"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
log_usage(machine, tool)
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"img_url": img_url}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
# ---------- 全站草稿自动保存(每 1 分钟 / 立即保存按钮 / 离开拦截)----------
|
||||
@staticmethod
|
||||
def _draft_path(machine: str, tool: str) -> str:
|
||||
"""校验并映射到 DATA_DIR/drafts/<machine>/<tool>.json;非法返回空串。"""
|
||||
m = MACHINE_RE.match(machine or "")
|
||||
t = re.sub(r"[^A-Za-z0-9_-]", "", tool or "")[:64]
|
||||
if not m or not t:
|
||||
return ""
|
||||
return os.path.join(DATA_DIR, "drafts", m.group(0), t + ".json")
|
||||
|
||||
def _handle_draft_save(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
tool = str(payload.get("tool") or "")
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
state = payload.get("state")
|
||||
try:
|
||||
raw = json.dumps(state, ensure_ascii=False)
|
||||
except (TypeError, ValueError):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad state"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if len(raw.encode("utf-8")) > 300 * 1024:
|
||||
self._reply(413, json.dumps({"code": 413, "message": "草稿超过 300KB 限制"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
rec = {"tool": tool[:64], "machine": machine, "ts": int(time.time()), "state": state}
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(rec, f, ensure_ascii=False)
|
||||
os.replace(tmp, path)
|
||||
except OSError:
|
||||
self._reply(500, json.dumps({"code": 500, "message": "保存失败"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
# 追加历史版本(保留最近 20 版,供前端「找回」面板选择回填)
|
||||
try:
|
||||
hpath = path[:-5] + ".hist.json"
|
||||
hist = []
|
||||
if os.path.isfile(hpath):
|
||||
with open(hpath, "r", encoding="utf-8") as f:
|
||||
loaded = json.load(f)
|
||||
if isinstance(loaded, list):
|
||||
hist = [h for h in loaded if isinstance(h, dict)]
|
||||
# 连续保存相同内容不重复入档(只更新最新一条时间戳)
|
||||
if hist and hist[0].get("state") == state:
|
||||
hist[0]["ts"] = rec["ts"]
|
||||
elif hist and hist[0].get("ts") == rec["ts"]:
|
||||
# 同一秒内的连续保存:按最新内容覆盖,避免出现两条同时间条目
|
||||
hist[0] = {"ts": rec["ts"], "state": state}
|
||||
else:
|
||||
hist.insert(0, {"ts": rec["ts"], "state": state})
|
||||
hist = hist[:20]
|
||||
tmp2 = hpath + ".tmp"
|
||||
with open(tmp2, "w", encoding="utf-8") as f:
|
||||
json.dump(hist, f, ensure_ascii=False)
|
||||
os.replace(tmp2, hpath)
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass # 历史写入失败不影响主保存
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"ts": rec["ts"]}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_draft_load(self, parsed):
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
machine = str((qs.get("machine") or [""])[0] or "")
|
||||
tool = str((qs.get("tool") or [""])[0] or "")
|
||||
try:
|
||||
want_ts = int((qs.get("ts") or ["0"])[0] or 0)
|
||||
except ValueError:
|
||||
want_ts = 0
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
data = None
|
||||
# 指定 ts:从历史版本里找回该条
|
||||
if want_ts > 0:
|
||||
hpath = path[:-5] + ".hist.json"
|
||||
if os.path.isfile(hpath):
|
||||
try:
|
||||
with open(hpath, "r", encoding="utf-8") as f:
|
||||
hist = json.load(f)
|
||||
if isinstance(hist, list):
|
||||
for h in hist:
|
||||
if isinstance(h, dict) and int(h.get("ts") or 0) == want_ts:
|
||||
data = {"state": h.get("state"), "ts": want_ts}
|
||||
break
|
||||
except (OSError, ValueError, TypeError):
|
||||
data = None
|
||||
else:
|
||||
if os.path.isfile(path):
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
rec = json.load(f)
|
||||
data = {"state": rec.get("state"), "ts": int(rec.get("ts") or 0)}
|
||||
except (OSError, ValueError):
|
||||
data = None
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_draft_history(self, parsed):
|
||||
"""历史版本清单(只回 ts/bytes,不回 state,面板按需逐条取)。"""
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
machine = str((qs.get("machine") or [""])[0] or "")
|
||||
tool = str((qs.get("tool") or [""])[0] or "")
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
items = []
|
||||
hpath = path[:-5] + ".hist.json"
|
||||
if os.path.isfile(hpath):
|
||||
try:
|
||||
with open(hpath, "r", encoding="utf-8") as f:
|
||||
hist = json.load(f)
|
||||
if isinstance(hist, list):
|
||||
for h in hist:
|
||||
if not isinstance(h, dict):
|
||||
continue
|
||||
st = h.get("state")
|
||||
try:
|
||||
b = len(json.dumps(st, ensure_ascii=False).encode("utf-8")) if st is not None else 0
|
||||
except (TypeError, ValueError):
|
||||
b = 0
|
||||
items.append({"ts": int(h.get("ts") or 0), "bytes": b})
|
||||
except (OSError, ValueError):
|
||||
items = []
|
||||
# 当前草稿(draft 文件)的时间戳:>0 表示草稿仍在,历史列表首项若同 ts
|
||||
# 才有资格标「当前草稿」徽标(丢弃后 draft 删除、hist 保留,此时 curTs=0 不标)
|
||||
cur_ts = 0
|
||||
if os.path.isfile(path):
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
rec = json.load(f)
|
||||
cur_ts = int(rec.get("ts") or 0)
|
||||
except (OSError, ValueError, TypeError):
|
||||
cur_ts = 0
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"items": items, "curTs": cur_ts}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_draft_delete(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
tool = str(payload.get("tool") or "")
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
if os.path.isfile(path):
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_img_history(self):
|
||||
parsed = parse.urlparse(self.path)
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
machine = str((qs.get("machine") or [""])[0] or "")
|
||||
fkind = str((qs.get("kind") or [""])[0] or "")
|
||||
if not self._gen_machine_ok(machine):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
idx_path = os.path.join(DATA_DIR, "gen_images", machine, "index.json")
|
||||
items = []
|
||||
if os.path.exists(idx_path):
|
||||
# 铁规则:只看本人历史。登录=账号本人条目(跨设备)+ 本机匿名条目;
|
||||
# 未登录=仅本机匿名条目(owner 为空或等于机器码,含迁移前旧记录)。
|
||||
me = _auth_user(self)
|
||||
root = os.path.join(DATA_DIR, "gen_images")
|
||||
pairs = []
|
||||
if me:
|
||||
try:
|
||||
items = json.load(open(idx_path, encoding="utf-8"))
|
||||
if not isinstance(items, list):
|
||||
items = []
|
||||
for name in sorted(os.listdir(root)):
|
||||
ip = os.path.join(root, name, "index.json")
|
||||
if not os.path.isfile(ip):
|
||||
continue
|
||||
try:
|
||||
its = json.load(open(ip, encoding="utf-8"))
|
||||
except Exception:
|
||||
continue
|
||||
if isinstance(its, list):
|
||||
pairs.append((name, its))
|
||||
except Exception:
|
||||
items = []
|
||||
pairs = []
|
||||
else:
|
||||
its = []
|
||||
ip = os.path.join(root, machine, "index.json")
|
||||
if os.path.exists(ip):
|
||||
try:
|
||||
its = json.load(open(ip, encoding="utf-8"))
|
||||
except Exception:
|
||||
its = []
|
||||
if not isinstance(its, list):
|
||||
its = []
|
||||
pairs.append((machine, its))
|
||||
items = []
|
||||
for name, its in pairs:
|
||||
for it in its:
|
||||
if isinstance(it, dict):
|
||||
it["_dir"] = name
|
||||
items.append(it)
|
||||
if fkind:
|
||||
# kind 过滤:逗号分隔多值;旧记录无 kind 字段视为 "gen"
|
||||
want = {k for k in fkind.split(",") if k}
|
||||
items = [it for it in items if str(it.get("kind") or "gen") in want]
|
||||
vis = []
|
||||
for it in items:
|
||||
if isinstance(it, dict):
|
||||
it["img_url"] = f"/relay/ai/img/{machine}/{it.get('id', '')}"
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": items}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
o = str(it.get("owner") or "")
|
||||
d = str(it.get("_dir") or machine)
|
||||
if me:
|
||||
ok = (o == me) or (d == machine and (not o or o == machine))
|
||||
else:
|
||||
ok = (d == machine) and (not o or o == machine)
|
||||
if ok:
|
||||
it["img_url"] = f"/relay/ai/img/{d}/{it.get('id', '')}"
|
||||
vis.append(it)
|
||||
vis.sort(key=lambda x: int(x.get("at") or 0), reverse=True)
|
||||
# 铁规则:所有功能历史最多显示 100 条(按时间倒序取前 100)
|
||||
vis = vis[:100]
|
||||
for it in vis:
|
||||
it.pop("_dir", None)
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": vis}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_img_file(self, parsed):
|
||||
# 兼容两条链路:直连 relay(/relay/ai/img/m/id)与经 nginx(/ai/img/m/id)
|
||||
@@ -3598,7 +4212,15 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "private, max-age=86400")
|
||||
if dl == "1":
|
||||
self.send_header("Content-Disposition", f'attachment; filename="{iid}{ext}"')
|
||||
# 下载名:?name= 优先(UTF-8 文件名,浏览器全部支持 filename*),缺省用磁盘名
|
||||
nm = str((qs.get("name") or [""])[0] or "")
|
||||
nm = os.path.basename(nm.replace("\\", "/")).strip()[:180]
|
||||
nm = re.sub(r'[\x00-\x1f\x7f"]', "", nm)
|
||||
if nm and nm not in (".", ".."):
|
||||
self.send_header("Content-Disposition",
|
||||
"attachment; filename*=UTF-8''" + parse.quote(nm))
|
||||
else:
|
||||
self.send_header("Content-Disposition", f'attachment; filename="{iid}{ext}"')
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(raw)
|
||||
@@ -3640,7 +4262,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"生图失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
# 落盘保存到该机器的历史(失败不阻断响应)
|
||||
img_url = self._persist_gen_image(machine, d, model, prompt, w, h) # 历史存用户原文
|
||||
try:
|
||||
kind = str(payload.get("kind") or "gen")[:20]
|
||||
except Exception:
|
||||
kind = "gen"
|
||||
img_url = self._persist_gen_image(machine, d, model, prompt, w, h, kind=kind) # 历史存用户原文
|
||||
if isinstance(d, dict) and img_url:
|
||||
d["img_url"] = img_url
|
||||
if translated and isinstance(d, dict):
|
||||
@@ -3676,6 +4302,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
|
||||
if translated and isinstance(d, dict):
|
||||
d["prompt_en"] = gen_prompt
|
||||
# 铁规则:生成即保存到后台存储目录(失败静默,不阻断响应)
|
||||
img_url = self._persist_gen_image(machine, d, model, prompt, 0, 0, kind="edit")
|
||||
if img_url and isinstance(d, dict):
|
||||
d["img_url"] = img_url
|
||||
self._img_reply_ok(d)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[img] edit failed: {e}", flush=True)
|
||||
@@ -3997,6 +4627,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
idx = []
|
||||
idx.insert(0, {"id": iid, "file": iid + ".jpg", "at": int(time.time()),
|
||||
"model": "AI换脸", "prompt": "face-swap",
|
||||
"kind": "face-swap",
|
||||
"owner": str(self._hist_owner(machine))[:64],
|
||||
"w": int(dst_img.shape[1]), "h": int(dst_img.shape[0])})
|
||||
while len(idx) > 100:
|
||||
old = idx.pop() or {}
|
||||
@@ -4112,6 +4744,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(502, json.dumps({"code": 502, "message": f"重绘失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
# 落盘到该机器图片历史(铁规则:生成即保存,失败不阻断响应)
|
||||
try:
|
||||
for im in images:
|
||||
self._persist_gen_image(machine, {"data": [{"b64_json": im["b64"]}]},
|
||||
"无痕改字", prompt, base_im.size[0], base_im.size[1],
|
||||
kind="seamless")
|
||||
except Exception as _pe: # noqa: BLE001
|
||||
print(f"[se] persist failed: {_pe}", flush=True)
|
||||
pub = [{"old": r["old"], "new": r["new"] or "(仅删除)", "style": r["style"]} for r in results]
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"images": images, "edits": pub, "note": note}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
|
||||
Reference in new issue
Block a user