Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3f48094f3 | ||
|
|
1c6bbf3018 | ||
|
|
3ee96dd741 | ||
|
|
b8138151ec | ||
|
|
7b1030b17e |
No files matched your search
@@ -23,9 +23,18 @@ Docker 镜像内置:calibre(`ebook-convert`)、ffmpeg、Piper(本地 TTS
|
||||
| `/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
|
||||
|
||||
@@ -184,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)
|
||||
@@ -197,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 不计次) ----------
|
||||
@@ -1750,6 +1788,44 @@ 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")):
|
||||
@@ -2420,6 +2496,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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
|
||||
@@ -2516,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", "")
|
||||
@@ -3896,9 +3993,71 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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 "")
|
||||
@@ -3906,15 +4065,35 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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
|
||||
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)
|
||||
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")
|
||||
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()
|
||||
@@ -4033,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)
|
||||
|
||||
Reference in new issue
Block a user