Compare commits
21
Commits
poster-20261113
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20e550f341 | ||
|
|
724c6e11e6 | ||
|
|
d473ed4295 | ||
|
|
cb588071bd | ||
|
|
6690d1c5c4 | ||
|
|
b13ffa5eac | ||
|
|
2f05156b55 | ||
|
|
d9aab5d6ef | ||
|
|
9cbec90347 | ||
|
|
ce512f1966 | ||
|
|
958e9039db | ||
|
|
80a12ffbe1 | ||
|
|
f529d5e850 | ||
|
|
7b6513c7de | ||
|
|
3aefc2633b | ||
|
|
78c348198d | ||
|
|
3c126277eb | ||
|
|
225aa5ed68 | ||
|
|
846b161aa3 | ||
|
|
931c0b5673 | ||
|
|
6463aa81d8 |
No files matched your search
@@ -83,10 +83,89 @@
|
|||||||
|
|
||||||
### AI 海报生成(2026.11 新增)
|
### AI 海报生成(2026.11 新增)
|
||||||
|
|
||||||
- 25 套热门海报模板、9 大分类(促销/节日/活动/美食/教育/健身/招聘/生日/封面),模板画布 1080×1440。
|
- 42 套热门海报模板、10 大分类(促销/节日/活动/美食/教育/校园/健身/招聘/生日/封面),模板画布 1080×1440;「校园」分类含教师节/开学第一课/家长会/秋季运动会/毕业季/社团招新/优秀学生表彰/快乐六一/考试加油/读书月等 10 款学校师生主题模板。
|
||||||
- 选中模板后可:**修改文字**(内容/字号/颜色/粗细/对齐/行高/斜体,预览与导出换行一致)、**替换图片**(本地上传 或 AI 生成,圆角可调)、拖动移动图层、图层排序/删除、添加文字与图片框、一键切换背景渐变、AI 生成整屏背景。
|
- 选中模板后可:**修改文字**(内容/字号/颜色/粗细/对齐/行高/斜体,预览与导出换行一致)、**旋转任意图层**(文字/图片/形状均支持,-180°~180° 滑杆 + 一键复位,预览与导出同一旋转中心)、**替换图片**(本地上传 或 AI 生成,圆角可调)、拖动移动图层、图层排序/删除、添加文字与图片框、一键切换背景渐变、AI 生成整屏背景。
|
||||||
|
- 编辑页整页自适应浏览器高度、不出现整体滚动条:内容超出时只在模板列表 / 画布 / 编辑面板各自区域内滚动(窄屏堆叠后统一为一个区域),画布始终完整可见。
|
||||||
- AI 配图复用 `/relay/ai/gen-image` 与每日免费生图额度,按图框宽高比自动匹配上游尺寸档位。
|
- AI 配图复用 `/relay/ai/gen-image` 与每日免费生图额度,按图框宽高比自动匹配上游尺寸档位。
|
||||||
- 完成后一键导出 1080×1440 PNG。授权应用,支持每日免费试用。
|
- 完成后一键导出 1080×1440 PNG(旋转图层同步导出)。授权应用,支持每日免费试用。
|
||||||
|
|
||||||
|
### 后台文件管理·按功能查询(2026.11 新增)
|
||||||
|
|
||||||
|
管理后台「📁 文件管理」在来源筛选旁新增**功能下拉**:按文件的 `kind`(AI 生图 / AI 换脸 / AI 海报 / 文字生图 / 标签设计 / 图片工具 / PDF 工具 / 未分类…)过滤,选项自带计数(如「AI 生图(65)」),计数随来源筛选联动;与「来源」下拉可组合使用,选择后页码自动回到第 1 页。
|
||||||
|
|
||||||
|
- 接口:`GET /admin/files?kind=<值>`,新增返回 `kinds: [{k, n}]` 分布统计(kind 过滤前统计,保证计数是当前来源下的全集);`kind=__none__` 表示未分类(无 kind 的用户根目录文件);
|
||||||
|
- 表格「类型」列同步显示中文功能名(原为 kind 英文原值);
|
||||||
|
- 仍带 `X-Admin-Token` 鉴权,无令牌 403。
|
||||||
|
|
||||||
|
### PDF 水印支持中文(2026.11 修复)
|
||||||
|
|
||||||
|
**问题**:PDF 工具「添加水印」输入中文后,生成的 PDF 里中文显示成 `???`。
|
||||||
|
|
||||||
|
**原因**:水印文字用 `embedFont('Helvetica')` 绘制——Helvetica 是 PDF 西文标准 14 字体(WinAnsi 编码),无法编码中文,pdf-lib 把超出编码范围的字符全部替换成 `?`。
|
||||||
|
|
||||||
|
**修复**(`src/tools/pdf-tools/pdf-tools.vue`):
|
||||||
|
|
||||||
|
- 新增依赖 `@cantoo/fontkit`(`@cantoo/pdf-lib` 官方推荐的 fontkit 实现);
|
||||||
|
- 中文字体 Droid Sans Fallback(4MB,覆盖 CJK,系统自带 `/usr/share/fonts/truetype/droid/`)放入 `public/fonts/DroidSansFallback.ttf`,由 nginx 直接提供;
|
||||||
|
- 水印文字含非西文字符(`charCodeAt > 0xFF`)时才按需 `fetch` 字体并 `registerFontkit` + `embedFont(bytes, { subset: true })`——子集只嵌入用到的字形,输出 PDF 增量很小(实测 3.5KB);纯英文水印仍走原 Helvetica 路径,不下载字体;
|
||||||
|
- 字节缓存在模块级变量,同一次页面会话只拉一次。
|
||||||
|
|
||||||
|
**验证**(浏览器端到端):上传测试 PDF → 中文水印「内部机密禁止外传」→ 执行 → pdfjs 提取文本层 `HAS_CN=true`、无 `???`;pdftoppm 渲染截图确认斜向水印字形正常;英文水印「CONFIDENTIAL 2026」回归通过(走 Helvetica,输出 1.6KB 无字体子集)。
|
||||||
|
|
||||||
|
### 全站编辑状态自动保存(2026.11 新增)
|
||||||
|
|
||||||
|
在任意工具页编辑时,系统会自动把当前修改状态保存到服务器:
|
||||||
|
|
||||||
|
- **每 1 分钟自动保存**,无需手动操作
|
||||||
|
- **右下角状态条常驻显示**(2026-11-15 改进):打开任何工具页立即可见,idle 态显示绿点「自动保存已开启」;编辑后变 `未保存`,自动/手动保存后显示 `已保存 HH:MM`;恢复草稿时显示 `已恢复当前功能草稿 HH:MM · 体积`——**该提示常驻到你开始编辑**(不再几秒自动消失),随时可操作
|
||||||
|
- **「立即保存」按钮全程可点**(保存中除外):idle 态点一下即保存当前内容
|
||||||
|
- **离开拦截**:未保存就刷新、关闭、站内前进后退时提示「当前内容还没保存,离开会丢失」——点「确定」= 先保存再离开,点「取消」= 留在本页
|
||||||
|
- **刷新自动恢复**:重新进入工具页自动还原上次未保存的内容
|
||||||
|
- **找回历史版本**(2026-11-15 新增):状态条上的「找回」按钮列出该工具的保存历史(服务端留档 20 份,时间精确到秒),点任意一条立即把页面内容恢复成那一版,随后可继续编辑;内容没有变化的重复保存只更新时间,不会重复占档。面板顶部标明「当前功能:<工具名>」——草稿按工具隔离,只显示本工具的记录;历史首项若就是服务端当前草稿会标绿色「当前草稿」徽标
|
||||||
|
- **丢弃草稿**(2026-11-15 新增):恢复提示旁的「丢弃草稿」按钮删除服务端保存的这份草稿(当前页面内容与历史留档都不受影响),之后刷新不再自动恢复;想找回还能从历史列表里点回来
|
||||||
|
|
||||||
|
> 实现:通用 DOM 快照一次性覆盖全部工具(无需逐个改造),字段定位用 `name > tag:type:组内序号`(框架动态 id 每次刷新都会变,实测不能用);服务端四端点 `/draft/save|load|history|delete`,按机器码隔离。
|
||||||
|
|
||||||
|
### 图片处理历史五工具全覆盖(2026-11-15 新增)
|
||||||
|
|
||||||
|
AI 生图、AI 修图、AI 图片实验室、AI 海报、AI 换脸五个图片工具的**每个处理动作**都会自动落盘服务端,并显示在页面右侧 50×50 缩略图历史列(点缩略图回看大图,按机器/账号隔离,只看本人的):
|
||||||
|
|
||||||
|
- **AI 生图**:生成(gen-image)与编辑器导出(img-save);
|
||||||
|
- **AI 修图**:去水印/抠图/超分/人脸修复四个页签的提交结果统一落盘;
|
||||||
|
- **AI 图片实验室**:抠图、无损放大、证件照生成即落盘;**换底(白/红/蓝/绿)后点下载会把换底合成图一并存入历史**(2026-11-15 修复:原换底结果不落盘,且下载给的是透明原图与预览不符);证件照生成时已落盘,**下载不再二次存**(防重复条目);
|
||||||
|
- **AI 海报**:AI 配图(kind=poster)与画布导出 PNG;
|
||||||
|
- **AI 换脸**:换脸结果(kind=face-swap)。
|
||||||
|
|
||||||
|
> 验证:五工具各跑一次真实处理,relay `gen_images/*/index.json` 计数逐一增加(gen 71、face-swap 3、poster 4、ai-retouch 1、ai-image-lab 3),右栏缩略同步出现。
|
||||||
|
|
||||||
|
### 历史记录 100 条上限(2026.11 新增)
|
||||||
|
|
||||||
|
所有功能里的历史记录最多显示 100 条(按时间倒序取最新 100 条):
|
||||||
|
|
||||||
|
- 服务端 `GET /relay/ai/img-history` 与 `GET /admin/mcp-usage` 调用流水统一截断前 100 条(只影响展示条数,后台总记录数/总调用量统计不受影响);
|
||||||
|
- 前端图片历史共享层(`loadImgHist`)、AI 生图与海报生成的自建历史均带 100 条本地兜底;
|
||||||
|
- 已有上限低于 100 的(生成记录 50 条、网速测速 20 条等)保持原值。
|
||||||
|
|
||||||
|
### 后台文件管理(2026.11 新增)
|
||||||
|
|
||||||
|
管理后台「文件管理」页全面升级:
|
||||||
|
|
||||||
|
- **默认全量视图**:进入即显示**所有用户**上传的文件 + AI 生成图片(换脸/生图/海报/编辑)+ MCP 产出文件的聚合列表,无需先选用户;下拉仍可按「仅 AI 生成 / 仅某用户」过滤。
|
||||||
|
- **50 条/页自动分页**:超过 50 条自动分页,页头页尾都有翻页控件,**显示总记录数与总大小**(如「共 81 条记录 · 合计 31.5 MB」)。
|
||||||
|
- **图片 100×100 缩略图**:图片类型文件在「预览」列显示 100×100 缩略图,点击看原图;**其他文件显示文件类型徽标**(PDF/PNG/MP4…)。
|
||||||
|
- **单独下载**:每一行都有「下载」链接(`Content-Disposition: attachment` 带原文件名),与「删除」并列;删除按来源分流(用户文件走 files 表、AI 生成图同步删 index、MCP 文件防路径穿越)。
|
||||||
|
- **安全**:缩略图与下载走统一 `/relay/admin/file?path=…&token=…` 路由(`<img>`/`<a>` 无法携带 header,鉴权走 query token,与 header 双通道校验);路径白名单限定 `users/`、`gen_images/`、`mcp_files/` 三棵子树 + realpath 校验,防目录穿越;无 token 请求 403。
|
||||||
|
- 服务端按 mtime 全局排序后切片分页,每项附带 `source`(user/gen/mcp)、`file_type`、`is_image`、相对 `path` 字段。
|
||||||
|
|
||||||
|
### 管理后台·授权应用管理(2026.11 新增)
|
||||||
|
|
||||||
|
管理后台新增「🧩 授权应用」页,全部 18 个授权应用集中管控:
|
||||||
|
|
||||||
|
- **前台显示开关**:每个授权应用一键「显示/隐藏」;隐藏后从左侧菜单、收藏夹、定价页、首页推荐同步消失(保存后前台刷新生效),直连地址与试用逻辑不受影响。
|
||||||
|
- **每日免费试用时长**:按功能独立设置 1–1440 分钟(默认 30 分钟/天),保存后 relay 门禁与前端试用浮条同时生效(实测 5 分钟档:4 分 59 秒放行、5 分 01 秒拦截)。
|
||||||
|
- **入口类型标注**:`页面` 类可切换显示;`API` 类(截图问答、视频字幕提取)仅服务端门禁、无前台页面,开关置灰禁用。
|
||||||
|
- 配置落盘 relay `data/tool_config.json`;公开端点 `GET /relay/tool-config` 只回非默认项,前端带 localStorage 缓存兜底,拉取失败静默回落、不阻断功能。
|
||||||
|
- 顺带修复:`AI 无痕改字`(`/ai-text-edit`)此前 relay 已门禁但前端授权清单漏注册,现已补入定价页自动上架(付费功能数 15 → 16,浮条/购买页数量动态化,不再写死 13)。
|
||||||
|
|
||||||
## 优势
|
## 优势
|
||||||
|
|
||||||
|
|||||||
Vendored
+3
@@ -20,6 +20,7 @@ declare module '@vue/runtime-core' {
|
|||||||
App: typeof import('./src/App.vue')['default']
|
App: typeof import('./src/App.vue')['default']
|
||||||
AsciiTextDrawer: typeof import('./src/tools/ascii-text-drawer/ascii-text-drawer.vue')['default']
|
AsciiTextDrawer: typeof import('./src/tools/ascii-text-drawer/ascii-text-drawer.vue')['default']
|
||||||
AudioTools: typeof import('./src/tools/audio-tools/audio-tools.vue')['default']
|
AudioTools: typeof import('./src/tools/audio-tools/audio-tools.vue')['default']
|
||||||
|
AutosaveBar: typeof import('./src/components/AutosaveBar.vue')['default']
|
||||||
BarcodeBatchGenerator: typeof import('./src/tools/batch-barcode-generator/barcode-batch-generator.vue')['default']
|
BarcodeBatchGenerator: typeof import('./src/tools/batch-barcode-generator/barcode-batch-generator.vue')['default']
|
||||||
'Base.layout': typeof import('./src/layouts/base.layout.vue')['default']
|
'Base.layout': typeof import('./src/layouts/base.layout.vue')['default']
|
||||||
Base64FileConverter: typeof import('./src/tools/base64-file-converter/base64-file-converter.vue')['default']
|
Base64FileConverter: typeof import('./src/tools/base64-file-converter/base64-file-converter.vue')['default']
|
||||||
@@ -130,6 +131,8 @@ declare module '@vue/runtime-core' {
|
|||||||
IconMdiVideo: typeof import('~icons/mdi/video')['default']
|
IconMdiVideo: typeof import('~icons/mdi/video')['default']
|
||||||
ImageOcr: typeof import('./src/tools/image-ocr/image-ocr.vue')['default']
|
ImageOcr: typeof import('./src/tools/image-ocr/image-ocr.vue')['default']
|
||||||
ImageTools: typeof import('./src/tools/image-tools/image-tools.vue')['default']
|
ImageTools: typeof import('./src/tools/image-tools/image-tools.vue')['default']
|
||||||
|
ImgEditor: typeof import('./src/tools/ai-gen/img-editor.vue')['default']
|
||||||
|
ImgHist: typeof import('./src/tools/img-hist/ImgHist.vue')['default']
|
||||||
InputCopyable: typeof import('./src/components/InputCopyable.vue')['default']
|
InputCopyable: typeof import('./src/components/InputCopyable.vue')['default']
|
||||||
IntegerBaseConverter: typeof import('./src/tools/integer-base-converter/integer-base-converter.vue')['default']
|
IntegerBaseConverter: typeof import('./src/tools/integer-base-converter/integer-base-converter.vue')['default']
|
||||||
Ipv4AddressConverter: typeof import('./src/tools/ipv4-address-converter/ipv4-address-converter.vue')['default']
|
Ipv4AddressConverter: typeof import('./src/tools/ipv4-address-converter/ipv4-address-converter.vue')['default']
|
||||||
|
|||||||
@@ -76,7 +76,8 @@ def mcp_usage_query(days: int = 7) -> dict:
|
|||||||
conn = sqlite3.connect(_CTX["usage_db"])
|
conn = sqlite3.connect(_CTX["usage_db"])
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"SELECT token_tail, machine, tool, ok, err, dur_ms, at FROM mcp_usage "
|
"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(
|
by_tool = conn.execute(
|
||||||
"SELECT tool, COUNT(*), SUM(ok) FROM mcp_usage WHERE at>? GROUP BY tool ORDER BY COUNT(*) DESC",
|
"SELECT tool, COUNT(*), SUM(ok) FROM mcp_usage WHERE at>? GROUP BY tool ORDER BY COUNT(*) DESC",
|
||||||
(since,)).fetchall()
|
(since,)).fetchall()
|
||||||
|
|||||||
+668
-28
@@ -21,6 +21,7 @@ Trial state persisted to /app/data/trials.json (mounted volume).
|
|||||||
import cgi
|
import cgi
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
|
import mimetypes
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shutil
|
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
|
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:
|
def trial_allowed(machine: str, tool: str) -> bool:
|
||||||
key = f"{machine}|{tool}"
|
key = f"{machine}|{tool}"
|
||||||
now_ms = int(time.time() * 1000)
|
now_ms = int(time.time() * 1000)
|
||||||
@@ -196,7 +235,7 @@ def trial_allowed(machine: str, tool: str) -> bool:
|
|||||||
trials[key] = now_ms
|
trials[key] = now_ms
|
||||||
_save_trials(trials)
|
_save_trials(trials)
|
||||||
return True
|
return True
|
||||||
return (now_ms - start) < TRIAL_MS
|
return (now_ms - start) < trial_minutes_of(tool) * 60 * 1000
|
||||||
|
|
||||||
|
|
||||||
# ---------- AI 生图页:每日免费次数(未授权;北京时间 0 点重置,自带 KEY 不计次) ----------
|
# ---------- AI 生图页:每日免费次数(未授权;北京时间 0 点重置,自带 KEY 不计次) ----------
|
||||||
@@ -716,6 +755,7 @@ _FACE_LOCK = threading.Lock()
|
|||||||
_FACE_APP = None
|
_FACE_APP = None
|
||||||
_FACE_SWAP = None
|
_FACE_SWAP = None
|
||||||
_FACE_MODELS_DIR = os.environ.get("FACE_MODELS_DIR", "/app/face-models")
|
_FACE_MODELS_DIR = os.environ.get("FACE_MODELS_DIR", "/app/face-models")
|
||||||
|
_GFPGAN_SESS = None
|
||||||
|
|
||||||
|
|
||||||
def _face_engine():
|
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])))
|
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):
|
def _face_swap_run(src_img, dst_img):
|
||||||
"""源人脸 -> 目标照片。返回 (jpg字节|None, 错误信息, 耗时ms)。加锁串行避免并发吃满 CPU。"""
|
"""源人脸 -> 目标照片。返回 (jpg字节|None, 错误信息, 耗时ms)。加锁串行避免并发吃满 CPU。"""
|
||||||
import cv2 as _cv2
|
import cv2 as _cv2
|
||||||
@@ -750,6 +851,9 @@ def _face_swap_run(src_img, dst_img):
|
|||||||
if not dst_faces:
|
if not dst_faces:
|
||||||
return None, "目标图中未检测到人脸,请换一张含人物的照片", 0
|
return None, "目标图中未检测到人脸,请换一张含人物的照片", 0
|
||||||
out = swap.get(dst_img, _largest_face(dst_faces), _largest_face(src_faces), paste_back=True)
|
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])
|
ok, buf = _cv2.imencode(".jpg", out, [int(_cv2.IMWRITE_JPEG_QUALITY), 92])
|
||||||
if not ok:
|
if not ok:
|
||||||
return None, "结果编码失败", 0
|
return None, "结果编码失败", 0
|
||||||
@@ -1211,6 +1315,21 @@ def _admin_auth(handler) -> bool:
|
|||||||
tok = handler.headers.get("X-Admin-Token", "")
|
tok = handler.headers.get("X-Admin-Token", "")
|
||||||
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
|
if ADMIN_TOKEN and tok and tok == ADMIN_TOKEN:
|
||||||
return True
|
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
|
# channel 2: logged-in admin account
|
||||||
auth = handler.headers.get("Authorization", "")
|
auth = handler.headers.get("Authorization", "")
|
||||||
if auth.lower().startswith("bearer "):
|
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},
|
"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"):
|
if method == "GET" and sub.startswith("/files"):
|
||||||
qs = parse.parse_qs(parse.urlparse(handler.path).query)
|
qs = parse.parse_qs(parse.urlparse(handler.path).query)
|
||||||
username = (qs.get("username") or [""])[0]
|
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": "参数错误"}
|
return 400, {"code": 400, "message": "参数错误"}
|
||||||
fdir = os.path.join(_user_dir(username), "files")
|
IMG_EXT = {"png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "avif", "ico"}
|
||||||
files = []
|
items = []
|
||||||
total = 0
|
want_user = scope not in ("gen", "mcp")
|
||||||
for root, _d, fs in os.walk(fdir):
|
want_gen = scope in ("", "gen")
|
||||||
kind = os.path.basename(root) if root != fdir else ""
|
want_mcp = scope in ("", "mcp")
|
||||||
for f in fs:
|
if username: # 指定用户时只看该用户文件(兼容旧下拉语义)
|
||||||
fp = os.path.join(root, f)
|
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:
|
try:
|
||||||
st = os.stat(fp)
|
st = os.stat(fp)
|
||||||
except OSError:
|
except OSError:
|
||||||
continue
|
continue
|
||||||
total += st.st_size
|
ext = os.path.splitext(f)[1].lower().lstrip(".")
|
||||||
files.append({"id": f, "name": f, "kind": kind, "size": st.st_size, "mtime": int(st.st_mtime)})
|
items.append({
|
||||||
files.sort(key=lambda x: -x["mtime"])
|
"id": f, "name": f, "kind": "mcp", "size": st.st_size,
|
||||||
return 200, {"code": 200, "message": "ok", "data": {"files": files, "total_size": total, "count": len(files)}}
|
"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":
|
if method == "POST" and sub == "/cleanup":
|
||||||
before = int(payload.get("before") or 0)
|
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":
|
if method == "POST" and sub == "/delete-file":
|
||||||
file_id = str(payload.get("id") or "")
|
file_id = str(payload.get("id") or "")
|
||||||
username = str(payload.get("username") 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:
|
if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id) or not username:
|
||||||
return 400, {"code": 400, "message": "参数错误"}
|
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")
|
base = os.path.join(_user_dir(username), "files")
|
||||||
target = os.path.join(base, file_id)
|
target = os.path.join(base, file_id)
|
||||||
if not os.path.exists(target):
|
if not os.path.exists(target):
|
||||||
@@ -1488,8 +1788,48 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
|||||||
_save_feedback(items)
|
_save_feedback(items)
|
||||||
return 200, {"code": 200, "message": "ok"}
|
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":
|
if method == "GET" and sub == "/storage":
|
||||||
total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0
|
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"):
|
for extra in ("users.db", "usage.db", "trials.json"):
|
||||||
fp = os.path.join(DATA_DIR, extra)
|
fp = os.path.join(DATA_DIR, extra)
|
||||||
if os.path.exists(fp):
|
if os.path.exists(fp):
|
||||||
@@ -1531,10 +1871,10 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
|||||||
os.remove(probe)
|
os.remove(probe)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return 400, {"code": 400, "message": f"目标路径不可写: {e}"}
|
return 400, {"code": 400, "message": f"目标路径不可写: {e}"}
|
||||||
# migrate existing data (users dir + db files)
|
# migrate existing data (users dir + AI 生成图片 + db files)
|
||||||
moved = []
|
moved = []
|
||||||
old_root = DATA_DIR
|
old_root = DATA_DIR
|
||||||
for item in ("users",):
|
for item in ("users", "gen_images"):
|
||||||
src = os.path.join(old_root, item)
|
src = os.path.join(old_root, item)
|
||||||
dst = os.path.join(new_root, item)
|
dst = os.path.join(new_root, item)
|
||||||
if os.path.isdir(src) and not os.path.isdir(dst):
|
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")
|
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
|
||||||
return
|
return
|
||||||
status, body = admin_api(method, sub, payload, self)
|
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")
|
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":
|
if parsed.path == "/ai/img-history":
|
||||||
self._handle_img_history()
|
self._handle_img_history()
|
||||||
return
|
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/"):
|
if parsed.path.startswith("/ai/img/"):
|
||||||
self._handle_img_file(parsed)
|
self._handle_img_file(parsed)
|
||||||
return
|
return
|
||||||
@@ -2247,6 +2595,24 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||||
return
|
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":
|
if parsed.path == "/check":
|
||||||
machine = self.headers.get("X-Machine-Id", "")
|
machine = self.headers.get("X-Machine-Id", "")
|
||||||
tool = self.headers.get("X-Tool", "")
|
tool = self.headers.get("X-Tool", "")
|
||||||
@@ -3166,6 +3532,15 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if parsed.path == "/ai/gen-image":
|
if parsed.path == "/ai/gen-image":
|
||||||
self._handle_gen_image()
|
self._handle_gen_image()
|
||||||
return
|
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":
|
if parsed.path == "/ai/edit-image":
|
||||||
self._handle_edit_image()
|
self._handle_edit_image()
|
||||||
return
|
return
|
||||||
@@ -3395,11 +3770,18 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
msg = str(err or d.get("message") or "")
|
msg = str(err or d.get("message") or "")
|
||||||
raise RuntimeError(msg[:300] 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(任何失败返回空串)。"""
|
"""把生成结果落盘并写入该机器的历史索引;返回站内图片 URL(任何失败返回空串)。"""
|
||||||
try:
|
try:
|
||||||
if not self._gen_machine_ok(machine):
|
if not self._gen_machine_ok(machine):
|
||||||
return ""
|
return ""
|
||||||
|
if owner is None:
|
||||||
|
owner = self._hist_owner(machine)
|
||||||
items = (d or {}).get("data") or []
|
items = (d or {}).get("data") or []
|
||||||
if not items:
|
if not items:
|
||||||
return ""
|
return ""
|
||||||
@@ -3451,6 +3833,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
idx.insert(0, {"id": iid, "file": fname, "at": int(time.time()),
|
idx.insert(0, {"id": iid, "file": fname, "at": int(time.time()),
|
||||||
"model": str(model)[:60], "prompt": str(prompt)[:500],
|
"model": str(model)[:60], "prompt": str(prompt)[:500],
|
||||||
"kind": str(kind or "gen")[:20],
|
"kind": str(kind or "gen")[:20],
|
||||||
|
"owner": str(owner)[:64],
|
||||||
"w": w, "h": h})
|
"w": w, "h": h})
|
||||||
while len(idx) > 100:
|
while len(idx) > 100:
|
||||||
old = idx.pop() or {}
|
old = idx.pop() or {}
|
||||||
@@ -3541,26 +3924,257 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return
|
return
|
||||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": ids[:200]}, ensure_ascii=False).encode("utf-8"), "application/json")
|
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):
|
def _handle_img_history(self):
|
||||||
parsed = parse.urlparse(self.path)
|
parsed = parse.urlparse(self.path)
|
||||||
qs = parse.parse_qs(parsed.query)
|
qs = parse.parse_qs(parsed.query)
|
||||||
machine = str((qs.get("machine") or [""])[0] or "")
|
machine = str((qs.get("machine") or [""])[0] or "")
|
||||||
|
fkind = str((qs.get("kind") or [""])[0] or "")
|
||||||
if not self._gen_machine_ok(machine):
|
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")
|
self._reply(400, json.dumps({"code": 400, "message": "bad machine"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||||
return
|
return
|
||||||
idx_path = os.path.join(DATA_DIR, "gen_images", machine, "index.json")
|
# 铁规则:只看本人历史。登录=账号本人条目(跨设备)+ 本机匿名条目;
|
||||||
items = []
|
# 未登录=仅本机匿名条目(owner 为空或等于机器码,含迁移前旧记录)。
|
||||||
if os.path.exists(idx_path):
|
me = _auth_user(self)
|
||||||
|
root = os.path.join(DATA_DIR, "gen_images")
|
||||||
|
pairs = []
|
||||||
|
if me:
|
||||||
try:
|
try:
|
||||||
items = json.load(open(idx_path, encoding="utf-8"))
|
for name in sorted(os.listdir(root)):
|
||||||
if not isinstance(items, list):
|
ip = os.path.join(root, name, "index.json")
|
||||||
items = []
|
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:
|
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:
|
for it in items:
|
||||||
if isinstance(it, dict):
|
o = str(it.get("owner") or "")
|
||||||
it["img_url"] = f"/relay/ai/img/{machine}/{it.get('id', '')}"
|
d = str(it.get("_dir") or machine)
|
||||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": items}, ensure_ascii=False).encode("utf-8"), "application/json")
|
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):
|
def _handle_img_file(self, parsed):
|
||||||
# 兼容两条链路:直连 relay(/relay/ai/img/m/id)与经 nginx(/ai/img/m/id)
|
# 兼容两条链路:直连 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("Content-Length", str(len(raw)))
|
||||||
self.send_header("Cache-Control", "private, max-age=86400")
|
self.send_header("Cache-Control", "private, max-age=86400")
|
||||||
if dl == "1":
|
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()
|
self.end_headers()
|
||||||
try:
|
try:
|
||||||
self.wfile.write(raw)
|
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")
|
self._reply(502, json.dumps({"code": 502, "message": f"生图失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||||
return
|
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:
|
if isinstance(d, dict) and img_url:
|
||||||
d["img_url"] = img_url
|
d["img_url"] = img_url
|
||||||
if translated and isinstance(d, dict):
|
if translated and isinstance(d, dict):
|
||||||
@@ -3676,6 +4302,10 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
|
daily_consume(machine, model) # 内置渠道成功才扣次(机器计数 + CF 共享池)
|
||||||
if translated and isinstance(d, dict):
|
if translated and isinstance(d, dict):
|
||||||
d["prompt_en"] = gen_prompt
|
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)
|
self._img_reply_ok(d)
|
||||||
except Exception as e: # noqa: BLE001
|
except Exception as e: # noqa: BLE001
|
||||||
print(f"[img] edit failed: {e}", flush=True)
|
print(f"[img] edit failed: {e}", flush=True)
|
||||||
@@ -3997,6 +4627,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
idx = []
|
idx = []
|
||||||
idx.insert(0, {"id": iid, "file": iid + ".jpg", "at": int(time.time()),
|
idx.insert(0, {"id": iid, "file": iid + ".jpg", "at": int(time.time()),
|
||||||
"model": "AI换脸", "prompt": "face-swap",
|
"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])})
|
"w": int(dst_img.shape[1]), "h": int(dst_img.shape[0])})
|
||||||
while len(idx) > 100:
|
while len(idx) > 100:
|
||||||
old = idx.pop() or {}
|
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")
|
self._reply(502, json.dumps({"code": 502, "message": f"重绘失败:{e}"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||||
return
|
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]
|
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")
|
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"images": images, "edits": pub, "note": note}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
"release": "node ./scripts/release.mjs"
|
"release": "node ./scripts/release.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@cantoo/fontkit": "^2.0.12",
|
||||||
"@cantoo/pdf-lib": "^2.11.1",
|
"@cantoo/pdf-lib": "^2.11.1",
|
||||||
"@it-tools/bip39": "^0.0.4",
|
"@it-tools/bip39": "^0.0.4",
|
||||||
"@it-tools/oggen": "^1.3.0",
|
"@it-tools/oggen": "^1.3.0",
|
||||||
|
|||||||
Generated
+35
-4
@@ -11,6 +11,9 @@ importers:
|
|||||||
|
|
||||||
.:
|
.:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
'@cantoo/fontkit':
|
||||||
|
specifier: ^2.0.12
|
||||||
|
version: 2.0.12
|
||||||
'@cantoo/pdf-lib':
|
'@cantoo/pdf-lib':
|
||||||
specifier: ^2.11.1
|
specifier: ^2.11.1
|
||||||
version: 2.11.1(html-entities@2.6.0)
|
version: 2.11.1(html-entities@2.6.0)
|
||||||
@@ -1184,6 +1187,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
|
resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
|
||||||
engines: {node: '>=6.9.0'}
|
engines: {node: '>=6.9.0'}
|
||||||
|
|
||||||
|
'@cantoo/fontkit@2.0.12':
|
||||||
|
resolution: {integrity: sha512-B9ZE4pA3cUf3pzn7UaPCtjyejd1ie16SLquCqdlGQiDncFgn8iD29dU9vD3dSgKkxAUx2ttvjg/li9JVkj5+fQ==}
|
||||||
|
|
||||||
'@cantoo/pdf-lib@2.11.1':
|
'@cantoo/pdf-lib@2.11.1':
|
||||||
resolution: {integrity: sha512-lYuRJFfXgoP8WVE8HYSeoLfDcnSXmjMLmdZS7YvmYHngbcZfiqDOruHrZBqjYizkrNa4ad1yW4WCrPYyb26T3Q==}
|
resolution: {integrity: sha512-lYuRJFfXgoP8WVE8HYSeoLfDcnSXmjMLmdZS7YvmYHngbcZfiqDOruHrZBqjYizkrNa4ad1yW4WCrPYyb26T3Q==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@@ -2660,6 +2666,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
|
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
brotli@1.3.3:
|
||||||
|
resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==}
|
||||||
|
|
||||||
browserslist@4.21.9:
|
browserslist@4.21.9:
|
||||||
resolution: {integrity: sha512-M0MFoZzbUrRU4KNfCrDLnvyE7gub+peetoTid3TBIqtunaDJyXlwhakT+/VkvSXcfIzFfK/nkCs4nmyTmxdNSg==}
|
resolution: {integrity: sha512-M0MFoZzbUrRU4KNfCrDLnvyE7gub+peetoTid3TBIqtunaDJyXlwhakT+/VkvSXcfIzFfK/nkCs4nmyTmxdNSg==}
|
||||||
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
|
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
|
||||||
@@ -3114,6 +3123,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
|
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
dfa@1.2.0:
|
||||||
|
resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}
|
||||||
|
|
||||||
diff-sequences@29.4.3:
|
diff-sequences@29.4.3:
|
||||||
resolution: {integrity: sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==}
|
resolution: {integrity: sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==}
|
||||||
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
|
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
|
||||||
@@ -3849,6 +3861,7 @@ packages:
|
|||||||
image-size@0.5.5:
|
image-size@0.5.5:
|
||||||
resolution: {integrity: sha512-6TDAlDPZxUFCv+fuOkIoXT/V/f3Qbq8e37p+YOiYrUv3v9cc3/6x78VdfPgFVaB9dZYeLUfKgHRebpkm/oP2VQ==}
|
resolution: {integrity: sha512-6TDAlDPZxUFCv+fuOkIoXT/V/f3Qbq8e37p+YOiYrUv3v9cc3/6x78VdfPgFVaB9dZYeLUfKgHRebpkm/oP2VQ==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
|
deprecated: Please migrate to image-size@2.x
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
import-fresh@3.3.0:
|
import-fresh@3.3.0:
|
||||||
@@ -5064,6 +5077,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==}
|
resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
restructure@3.0.2:
|
||||||
|
resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==}
|
||||||
|
|
||||||
ret@0.1.15:
|
ret@0.1.15:
|
||||||
resolution: {integrity: sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==}
|
resolution: {integrity: sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==}
|
||||||
engines: {node: '>=0.12'}
|
engines: {node: '>=0.12'}
|
||||||
@@ -7295,6 +7311,13 @@ snapshots:
|
|||||||
'@babel/helper-string-parser': 7.29.7
|
'@babel/helper-string-parser': 7.29.7
|
||||||
'@babel/helper-validator-identifier': 7.29.7
|
'@babel/helper-validator-identifier': 7.29.7
|
||||||
|
|
||||||
|
'@cantoo/fontkit@2.0.12':
|
||||||
|
dependencies:
|
||||||
|
brotli: 1.3.3
|
||||||
|
dfa: 1.2.0
|
||||||
|
fflate: 0.8.3
|
||||||
|
restructure: 3.0.2
|
||||||
|
|
||||||
'@cantoo/pdf-lib@2.11.1(html-entities@2.6.0)':
|
'@cantoo/pdf-lib@2.11.1(html-entities@2.6.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
culori: 4.0.2
|
culori: 4.0.2
|
||||||
@@ -7461,7 +7484,7 @@ snapshots:
|
|||||||
'@eslint/eslintrc@2.1.2':
|
'@eslint/eslintrc@2.1.2':
|
||||||
dependencies:
|
dependencies:
|
||||||
ajv: 6.12.6
|
ajv: 6.12.6
|
||||||
debug: 4.3.4
|
debug: 4.4.0
|
||||||
espree: 9.6.1
|
espree: 9.6.1
|
||||||
globals: 13.20.0
|
globals: 13.20.0
|
||||||
ignore: 5.2.4
|
ignore: 5.2.4
|
||||||
@@ -7477,7 +7500,7 @@ snapshots:
|
|||||||
'@humanwhocodes/config-array@0.11.10':
|
'@humanwhocodes/config-array@0.11.10':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@humanwhocodes/object-schema': 1.2.1
|
'@humanwhocodes/object-schema': 1.2.1
|
||||||
debug: 4.3.4
|
debug: 4.4.0
|
||||||
minimatch: 3.1.2
|
minimatch: 3.1.2
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
@@ -9018,6 +9041,10 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
fill-range: 7.1.1
|
fill-range: 7.1.1
|
||||||
|
|
||||||
|
brotli@1.3.3:
|
||||||
|
dependencies:
|
||||||
|
base64-js: 1.5.1
|
||||||
|
|
||||||
browserslist@4.21.9:
|
browserslist@4.21.9:
|
||||||
dependencies:
|
dependencies:
|
||||||
caniuse-lite: 1.0.30001504
|
caniuse-lite: 1.0.30001504
|
||||||
@@ -9486,6 +9513,8 @@ snapshots:
|
|||||||
detect-libc@2.1.2:
|
detect-libc@2.1.2:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
dfa@1.2.0: {}
|
||||||
|
|
||||||
diff-sequences@29.4.3: {}
|
diff-sequences@29.4.3: {}
|
||||||
|
|
||||||
dijkstrajs@1.0.2: {}
|
dijkstrajs@1.0.2: {}
|
||||||
@@ -10345,14 +10374,14 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@tootallnate/once': 2.0.0
|
'@tootallnate/once': 2.0.0
|
||||||
agent-base: 6.0.2
|
agent-base: 6.0.2
|
||||||
debug: 4.3.4
|
debug: 4.4.0
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
https-proxy-agent@5.0.1:
|
https-proxy-agent@5.0.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
agent-base: 6.0.2
|
agent-base: 6.0.2
|
||||||
debug: 4.3.4
|
debug: 4.4.0
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
@@ -11690,6 +11719,8 @@ snapshots:
|
|||||||
onetime: 5.1.2
|
onetime: 5.1.2
|
||||||
signal-exit: 3.0.7
|
signal-exit: 3.0.7
|
||||||
|
|
||||||
|
restructure@3.0.2: {}
|
||||||
|
|
||||||
ret@0.1.15: {}
|
ret@0.1.15: {}
|
||||||
|
|
||||||
ret@0.2.2: {}
|
ret@0.2.2: {}
|
||||||
|
|||||||
Binary file not shown.
@@ -0,0 +1,374 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue';
|
||||||
|
|
||||||
|
import { curTs, discardDraft, loadHistory, restored, restoredBytes, restoreVersion, saveNow, savedAt, status } from '../composable/autosave';
|
||||||
|
|
||||||
|
/** 当前功能名:面板每次打开时实时取工具页标题(不用 computed 缓存 DOM,避免路由切换后过期) */
|
||||||
|
const curToolName = ref('当前工具');
|
||||||
|
function refreshToolName() {
|
||||||
|
const h1 = document.querySelector('.tool-content h1, .tool-content .tool-header h1, h1');
|
||||||
|
const t = (h1?.textContent || '').trim();
|
||||||
|
curToolName.value = t || '当前工具';
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = ref(Date.now());
|
||||||
|
setInterval(() => {
|
||||||
|
now.value = Date.now();
|
||||||
|
}, 10_000);
|
||||||
|
|
||||||
|
const timeLabel = computed(() => {
|
||||||
|
if (!savedAt.value) return '';
|
||||||
|
const d = new Date(savedAt.value);
|
||||||
|
const hh = String(d.getHours()).padStart(2, '0');
|
||||||
|
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||||
|
return `${hh}:${mm}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const saving = ref(false);
|
||||||
|
|
||||||
|
async function onSave() {
|
||||||
|
if (saving.value) return;
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
await saveNow();
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ---- 找回历史版本 ---- */
|
||||||
|
const histOpen = ref(false);
|
||||||
|
const histLoading = ref(false);
|
||||||
|
const histItems = ref<{ ts: number; bytes: number }[]>([]);
|
||||||
|
const picking = ref(false);
|
||||||
|
|
||||||
|
async function toggleHist() {
|
||||||
|
if (histOpen.value) {
|
||||||
|
histOpen.value = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
refreshToolName();
|
||||||
|
histOpen.value = true;
|
||||||
|
histLoading.value = true;
|
||||||
|
try {
|
||||||
|
histItems.value = await loadHistory();
|
||||||
|
} finally {
|
||||||
|
histLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 丢弃服务端当前草稿:状态条提示消失,历史列表同步刷新 */
|
||||||
|
const discarding = ref(false);
|
||||||
|
async function onDiscard() {
|
||||||
|
if (discarding.value) return;
|
||||||
|
discarding.value = true;
|
||||||
|
try {
|
||||||
|
const ok = await discardDraft();
|
||||||
|
if (ok && histOpen.value) histItems.value = await loadHistory();
|
||||||
|
} finally {
|
||||||
|
discarding.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onPick(ts: number) {
|
||||||
|
if (picking.value) return;
|
||||||
|
picking.value = true;
|
||||||
|
try {
|
||||||
|
const ok = await restoreVersion(ts);
|
||||||
|
if (ok) histOpen.value = false;
|
||||||
|
} finally {
|
||||||
|
picking.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtTime(ts: number): string {
|
||||||
|
const d = new Date(ts * 1000);
|
||||||
|
const p = (n: number) => String(n).padStart(2, '0');
|
||||||
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtSize(b: number): string {
|
||||||
|
if (b < 1024) return `${b} B`;
|
||||||
|
if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`;
|
||||||
|
return `${(b / 1024 / 1024).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前状态文案 —— 打开页面即常驻可见(idle = 自动保存已开启) */
|
||||||
|
const textLabel = computed(() => {
|
||||||
|
if (restored.value) {
|
||||||
|
const sz = restoredBytes.value ? ` · ${fmtSize(restoredBytes.value)}` : '';
|
||||||
|
return `已恢复当前功能草稿 ${timeLabel.value}${sz}`;
|
||||||
|
}
|
||||||
|
switch (status.value) {
|
||||||
|
case 'dirty':
|
||||||
|
return '未保存';
|
||||||
|
case 'saving':
|
||||||
|
return '保存中…';
|
||||||
|
case 'error':
|
||||||
|
return '保存失败';
|
||||||
|
case 'saved':
|
||||||
|
return `已保存 ${timeLabel.value}`;
|
||||||
|
default:
|
||||||
|
return '自动保存已开启';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const chipClass = computed(() => ({
|
||||||
|
'as-restore': restored.value,
|
||||||
|
'as-dirty': !restored.value && status.value === 'dirty',
|
||||||
|
'as-saving': status.value === 'saving',
|
||||||
|
'as-error': status.value === 'error',
|
||||||
|
'as-saved': status.value === 'saved',
|
||||||
|
'as-idle': !restored.value && status.value === 'idle',
|
||||||
|
}));
|
||||||
|
|
||||||
|
const dotClass = computed(() => {
|
||||||
|
if (restored.value) return 'green';
|
||||||
|
switch (status.value) {
|
||||||
|
case 'dirty':
|
||||||
|
return 'orange';
|
||||||
|
case 'saving':
|
||||||
|
return 'gray blink';
|
||||||
|
case 'error':
|
||||||
|
return 'red';
|
||||||
|
default:
|
||||||
|
return 'green';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const btnLabel = computed(() => (status.value === 'error' ? '重试' : '立即保存'));
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<!-- 常驻右下角:任何工具页打开即可见 -->
|
||||||
|
<div class="autosave-bar show">
|
||||||
|
<!-- 找回历史版本面板 -->
|
||||||
|
<div v-if="histOpen" class="as-panel">
|
||||||
|
<div class="as-panel-hd">
|
||||||
|
<span>找回历史版本</span>
|
||||||
|
<button class="as-x" @click="histOpen = false">×</button>
|
||||||
|
</div>
|
||||||
|
<div class="as-panel-body">
|
||||||
|
<div class="as-cur">
|
||||||
|
当前功能:<b>{{ curToolName }}</b>
|
||||||
|
<small>草稿按工具隔离,只显示本工具的保存记录</small>
|
||||||
|
</div>
|
||||||
|
<div v-if="histLoading" class="as-empty">加载中…</div>
|
||||||
|
<div v-else-if="!histItems.length" class="as-empty">暂无历史版本<br /><small>每次保存都会自动留档</small></div>
|
||||||
|
<button
|
||||||
|
v-for="(it, i) in histItems"
|
||||||
|
:key="it.ts"
|
||||||
|
class="as-hitem"
|
||||||
|
:class="{ 'as-cur-item': i === 0 && curTs > 0 && it.ts === curTs }"
|
||||||
|
:disabled="picking"
|
||||||
|
:title="`点击恢复到 ${fmtTime(it.ts)} 的内容`"
|
||||||
|
@click="onPick(it.ts)"
|
||||||
|
>
|
||||||
|
<span class="as-hdate">
|
||||||
|
<span v-if="i === 0 && curTs > 0 && it.ts === curTs" class="as-cur-tag">当前草稿</span>
|
||||||
|
{{ fmtTime(it.ts) }}
|
||||||
|
</span>
|
||||||
|
<span class="as-hsize">{{ fmtSize(it.bytes) }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="as-chip" :class="chipClass">
|
||||||
|
<span class="as-dot" :class="dotClass" />
|
||||||
|
<span class="as-text">{{ textLabel }}</span>
|
||||||
|
<button
|
||||||
|
v-if="restored"
|
||||||
|
class="as-btn ghost danger"
|
||||||
|
:disabled="discarding || saving"
|
||||||
|
title="丢弃服务端保存的这份草稿(当前页面内容不受影响)"
|
||||||
|
@click="onDiscard"
|
||||||
|
>
|
||||||
|
{{ discarding ? '丢弃中…' : '丢弃草稿' }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="as-btn ghost"
|
||||||
|
:disabled="saving || histLoading || picking"
|
||||||
|
title="找回历史保存的版本,点击恢复后可继续编辑"
|
||||||
|
@click="toggleHist"
|
||||||
|
>
|
||||||
|
{{ picking ? '恢复中…' : '找回' }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="status !== 'saving'"
|
||||||
|
class="as-btn"
|
||||||
|
:disabled="saving"
|
||||||
|
@click="onSave"
|
||||||
|
>
|
||||||
|
{{ saving ? '保存中…' : btnLabel }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.autosave-bar {
|
||||||
|
position: fixed;
|
||||||
|
right: 20px;
|
||||||
|
bottom: 20px;
|
||||||
|
z-index: 9999;
|
||||||
|
pointer-events: none;
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(8px);
|
||||||
|
transition: opacity .25s ease, transform .25s ease;
|
||||||
|
}
|
||||||
|
.autosave-bar.show {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
.as-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 7px 12px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(30, 30, 30, .92);
|
||||||
|
color: #eaeaea;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1;
|
||||||
|
box-shadow: 0 4px 16px rgba(0, 0, 0, .28);
|
||||||
|
backdrop-filter: blur(6px);
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
.as-text {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.as-dot {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.as-dot.green { background: #3ecf8e; }
|
||||||
|
.as-dot.orange { background: #f5a524; }
|
||||||
|
.as-dot.red { background: #f31260; }
|
||||||
|
.as-dot.gray { background: #a1a1aa; }
|
||||||
|
.blink { animation: as-blink 1s infinite; }
|
||||||
|
@keyframes as-blink {
|
||||||
|
0%, 100% { opacity: 1; }
|
||||||
|
50% { opacity: .25; }
|
||||||
|
}
|
||||||
|
.as-btn {
|
||||||
|
border: 0;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 5px 11px;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
background: #3ecf8e;
|
||||||
|
color: #08221a;
|
||||||
|
font-weight: 600;
|
||||||
|
transition: filter .15s ease;
|
||||||
|
}
|
||||||
|
.as-btn:hover { filter: brightness(1.08); }
|
||||||
|
.as-btn:disabled { opacity: .6; cursor: default; }
|
||||||
|
.as-btn.ghost {
|
||||||
|
background: transparent;
|
||||||
|
color: #cfcfcf;
|
||||||
|
border: 1px solid rgba(255, 255, 255, .28);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.as-btn.ghost:hover { border-color: rgba(255, 255, 255, .55); color: #fff; filter: none; }
|
||||||
|
.as-btn.ghost.danger { color: #f31260; border-color: rgba(243, 18, 96, .5); }
|
||||||
|
.as-btn.ghost.danger:hover { border-color: #f31260; color: #ff6b9d; }
|
||||||
|
.as-error .as-btn {
|
||||||
|
background: #f31260;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
/* 历史版本面板 */
|
||||||
|
.as-panel {
|
||||||
|
position: absolute;
|
||||||
|
right: 0;
|
||||||
|
bottom: calc(100% + 8px);
|
||||||
|
width: 258px;
|
||||||
|
background: rgba(30, 30, 30, .97);
|
||||||
|
border: 1px solid rgba(255, 255, 255, .12);
|
||||||
|
border-radius: 12px;
|
||||||
|
box-shadow: 0 8px 28px rgba(0, 0, 0, .4);
|
||||||
|
pointer-events: auto;
|
||||||
|
overflow: hidden;
|
||||||
|
color: #eaeaea;
|
||||||
|
}
|
||||||
|
.as-panel-hd {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 9px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, .1);
|
||||||
|
}
|
||||||
|
.as-x {
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: #a1a1aa;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0 2px;
|
||||||
|
}
|
||||||
|
.as-x:hover { color: #fff; }
|
||||||
|
.as-panel-body {
|
||||||
|
max-height: 250px;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 6px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
.as-empty {
|
||||||
|
text-align: center;
|
||||||
|
color: #a1a1aa;
|
||||||
|
font-size: 12px;
|
||||||
|
padding: 18px 8px;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
.as-empty small { opacity: .7; }
|
||||||
|
.as-hitem {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 7px 9px;
|
||||||
|
background: rgba(255, 255, 255, .06);
|
||||||
|
color: #eaeaea;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
transition: background .15s ease;
|
||||||
|
}
|
||||||
|
.as-hitem:hover { background: rgba(62, 207, 142, .22); }
|
||||||
|
.as-hitem:disabled { opacity: .6; cursor: default; }
|
||||||
|
.as-hdate { white-space: nowrap; display: inline-flex; align-items: center; gap: 6px; }
|
||||||
|
.as-hsize { color: #a1a1aa; white-space: nowrap; }
|
||||||
|
.as-cur {
|
||||||
|
padding: 6px 9px 7px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #eaeaea;
|
||||||
|
background: rgba(62, 207, 142, .12);
|
||||||
|
border-radius: 8px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
.as-cur b { color: #3ecf8e; }
|
||||||
|
.as-cur small { display: block; color: #a1a1aa; font-size: 11px; }
|
||||||
|
.as-cur-item { outline: 1px solid rgba(62, 207, 142, .45); }
|
||||||
|
.as-cur-tag {
|
||||||
|
background: #3ecf8e;
|
||||||
|
color: #08221a;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 700;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 1px 5px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.autosave-bar { right: 12px; bottom: 76px; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -4,7 +4,7 @@ import { useThemeVars } from 'naive-ui';
|
|||||||
import { RouterLink, useRoute, useRouter } from 'vue-router';
|
import { RouterLink, useRoute, useRouter } from 'vue-router';
|
||||||
import MenuIconItem from './MenuIconItem.vue';
|
import MenuIconItem from './MenuIconItem.vue';
|
||||||
import type { Tool, ToolCategory } from '@/tools/tools.types';
|
import type { Tool, ToolCategory } from '@/tools/tools.types';
|
||||||
import { PROTECTED_TOOLS } from '@/tools/license/license';
|
import { PROTECTED_TOOLS, toolVisible } from '@/tools/license/license';
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{ toolsByCategory?: ToolCategory[]; favoriteCategory?: ToolCategory | null }>(), { toolsByCategory: () => [], favoriteCategory: null });
|
const props = withDefaults(defineProps<{ toolsByCategory?: ToolCategory[]; favoriteCategory?: ToolCategory | null }>(), { toolsByCategory: () => [], favoriteCategory: null });
|
||||||
const { toolsByCategory } = toRefs(props);
|
const { toolsByCategory } = toRefs(props);
|
||||||
@@ -75,6 +75,7 @@ const menuOptions = computed(() => {
|
|||||||
.map(({ name, components }) => ({
|
.map(({ name, components }) => ({
|
||||||
name,
|
name,
|
||||||
components: components.filter((tool) => {
|
components: components.filter((tool) => {
|
||||||
|
if (!toolVisible(tool.path)) return false; // 管理后台关闭显示的应用:菜单隐藏
|
||||||
if (tool.path in PROTECTED_TOOLS) {
|
if (tool.path in PROTECTED_TOOLS) {
|
||||||
if (!paidPaths.has(tool.path)) {
|
if (!paidPaths.has(tool.path)) {
|
||||||
paidPaths.add(tool.path);
|
paidPaths.add(tool.path);
|
||||||
@@ -99,8 +100,9 @@ const menuOptions = computed(() => {
|
|||||||
|
|
||||||
const options = [];
|
const options = [];
|
||||||
// favorites first, shown as-is (user shortcuts must stay visible)
|
// favorites first, shown as-is (user shortcuts must stay visible)
|
||||||
if (props.favoriteCategory && props.favoriteCategory.components.length > 0) {
|
const favComps = (props.favoriteCategory?.components ?? []).filter(t => toolVisible(t.path));
|
||||||
options.push(toOption(props.favoriteCategory.name, props.favoriteCategory.components));
|
if (props.favoriteCategory && favComps.length > 0) {
|
||||||
|
options.push(toOption(props.favoriteCategory.name, favComps));
|
||||||
}
|
}
|
||||||
if (paidTools.length > 0) {
|
if (paidTools.length > 0) {
|
||||||
options.push(toOption(PAID_GROUP_NAME, paidTools));
|
options.push(toOption(PAID_GROUP_NAME, paidTools));
|
||||||
|
|||||||
@@ -0,0 +1,360 @@
|
|||||||
|
import { nextTick, ref } from 'vue';
|
||||||
|
|
||||||
|
import { getMachineId, licenseHeaders } from '../tools/license/license';
|
||||||
|
import { apiFetch } from './user-auth';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全站草稿自动保存(2026-11-15 用户需求):
|
||||||
|
* - 用户在任意工具页编辑时,每 1 分钟自动把当前修改状态保存到服务器
|
||||||
|
* - 右下角提供「立即保存」按钮
|
||||||
|
* - 未保存就刷新 / 关闭 / 前进后退时提示「当前内容还没保存离开会丢失,是否保存」
|
||||||
|
*
|
||||||
|
* 覆盖方式:通用 DOM 快照(抓取 .tool-content 内全部 input/textarea/select/contenteditable),
|
||||||
|
* 因此对全部工具生效,无需逐个工具改造。file 输入与超大数据跳过。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type AutosaveStatus = 'idle' | 'dirty' | 'saving' | 'saved' | 'error';
|
||||||
|
|
||||||
|
export const status = ref<AutosaveStatus>('idle');
|
||||||
|
export const savedAt = ref(0);
|
||||||
|
export const restored = ref(false);
|
||||||
|
/** 已恢复草稿的体积(字节,utf8),给状态条显示用 */
|
||||||
|
export const restoredBytes = ref(0);
|
||||||
|
/** 服务端当前草稿的时间戳(0 = 无当前草稿,如已丢弃),面板按它决定「当前草稿」徽标 */
|
||||||
|
export const curTs = ref(0);
|
||||||
|
export const hasUnsaved = ref(false);
|
||||||
|
|
||||||
|
const INTERVAL_MS = 60_000; // 每 1 分钟
|
||||||
|
const MAX_STATE_BYTES = 300 * 1024; // 与服务端限制一致
|
||||||
|
|
||||||
|
let toolKey = '';
|
||||||
|
let timer: number | null = null;
|
||||||
|
let dirty = false;
|
||||||
|
let bound = false;
|
||||||
|
let restoring = false;
|
||||||
|
|
||||||
|
const SKIP_TYPE = new Set(['file', 'image', 'button', 'submit', 'reset', 'color', 'range']);
|
||||||
|
|
||||||
|
function root(): HTMLElement | null {
|
||||||
|
return document.querySelector<HTMLElement>('.tool-content');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 稳定字段定位:name > tag:type:组内序号。
|
||||||
|
* 注意:不能用 element.id —— Naive UI 等框架的 id 每次刷新都会重新生成
|
||||||
|
* (实测 id-omyyvzbgz8 → id-h0mksbmep7),会导致草稿无法匹配回填。
|
||||||
|
*/
|
||||||
|
function fieldKey(e: Element, idx: number): string {
|
||||||
|
const el = e as HTMLInputElement;
|
||||||
|
const name = el.getAttribute?.('name');
|
||||||
|
if (name) return `[${name}]`;
|
||||||
|
const tag = e.tagName.toLowerCase();
|
||||||
|
const type = (el.type || '').toLowerCase();
|
||||||
|
return `${tag}:${type}:${idx}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 抓取当前工具页的可编辑状态 */
|
||||||
|
export function snapshot(): Record<string, any> | null {
|
||||||
|
const r = root();
|
||||||
|
if (!r) return null;
|
||||||
|
const out: Record<string, any> = {};
|
||||||
|
const counters: Record<string, number> = {};
|
||||||
|
let n = 0;
|
||||||
|
|
||||||
|
r.querySelectorAll('input, textarea, select').forEach(el => {
|
||||||
|
const e = el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
||||||
|
const tag = e.tagName.toLowerCase();
|
||||||
|
const type = tag === 'input' ? ((e as HTMLInputElement).type || 'text').toLowerCase() : '';
|
||||||
|
if (tag === 'input' && SKIP_TYPE.has(type)) return;
|
||||||
|
const grp = `${tag}:${type}`;
|
||||||
|
const idx = counters[grp] ?? 0;
|
||||||
|
counters[grp] = idx + 1;
|
||||||
|
const key = fieldKey(e, idx);
|
||||||
|
try {
|
||||||
|
if (tag === 'input' && (type === 'checkbox' || type === 'radio')) {
|
||||||
|
out[key] = (e as HTMLInputElement).checked;
|
||||||
|
} else if (tag === 'select' && (e as HTMLSelectElement).multiple) {
|
||||||
|
out[key] = Array.from((e as HTMLSelectElement).selectedOptions).map(o => o.value);
|
||||||
|
} else {
|
||||||
|
out[key] = (e as any).value;
|
||||||
|
}
|
||||||
|
n++;
|
||||||
|
} catch {
|
||||||
|
/* 某些自定义控件取值失败则跳过 */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let ce = 0;
|
||||||
|
r.querySelectorAll('[contenteditable="true"]').forEach(el => {
|
||||||
|
const html = (el as HTMLElement).innerHTML || '';
|
||||||
|
if (html) out[`ce:${ce}`] = html.slice(0, 50_000);
|
||||||
|
ce++;
|
||||||
|
n++;
|
||||||
|
});
|
||||||
|
|
||||||
|
return n > 0 ? out : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把服务器草稿写回页面(触发 input/change 让 v-model 同步) */
|
||||||
|
function applyState(state: Record<string, any>): number {
|
||||||
|
const r = root();
|
||||||
|
if (!r || !state) return 0;
|
||||||
|
let applied = 0;
|
||||||
|
restoring = true;
|
||||||
|
try {
|
||||||
|
const counters: Record<string, number> = {};
|
||||||
|
r.querySelectorAll('input, textarea, select').forEach(el => {
|
||||||
|
const e = el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
||||||
|
const tag = e.tagName.toLowerCase();
|
||||||
|
const type = tag === 'input' ? ((e as HTMLInputElement).type || 'text').toLowerCase() : '';
|
||||||
|
if (tag === 'input' && SKIP_TYPE.has(type)) return;
|
||||||
|
const grp = `${tag}:${type}`;
|
||||||
|
const idx = counters[grp] ?? 0;
|
||||||
|
counters[grp] = idx + 1;
|
||||||
|
const key = fieldKey(e, idx);
|
||||||
|
if (!(key in state)) return;
|
||||||
|
const v = state[key];
|
||||||
|
applied++;
|
||||||
|
try {
|
||||||
|
if (tag === 'input' && type === 'checkbox') {
|
||||||
|
(e as HTMLInputElement).checked = !!v;
|
||||||
|
} else if (tag === 'input' && type === 'radio') {
|
||||||
|
(e as HTMLInputElement).checked = v === true || v === (e as HTMLInputElement).value;
|
||||||
|
} else if (tag === 'select' && (e as HTMLSelectElement).multiple && Array.isArray(v)) {
|
||||||
|
const set = new Set(v.map(String));
|
||||||
|
Array.from((e as HTMLSelectElement).options).forEach(o => {
|
||||||
|
o.selected = set.has(o.value);
|
||||||
|
});
|
||||||
|
} else if (v !== undefined && v !== null) {
|
||||||
|
(e as any).value = String(v);
|
||||||
|
}
|
||||||
|
e.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
e.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
|
} catch {
|
||||||
|
/* 忽略单个字段失败 */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let ce = 0;
|
||||||
|
r.querySelectorAll('[contenteditable="true"]').forEach(el => {
|
||||||
|
const key = `ce:${ce}`;
|
||||||
|
ce++;
|
||||||
|
if (key in state && state[key]) {
|
||||||
|
(el as HTMLElement).innerHTML = String(state[key]);
|
||||||
|
applied++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
// 等 Vue 完成一轮渲染再解除抑制
|
||||||
|
setTimeout(() => {
|
||||||
|
restoring = false;
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
return applied;
|
||||||
|
}
|
||||||
|
|
||||||
|
function markDirty(): void {
|
||||||
|
if (restoring || !toolKey) return;
|
||||||
|
// 用户开始编辑后,「已恢复」提示立即让位给「未保存」
|
||||||
|
if (restored.value) restored.value = false;
|
||||||
|
if (!dirty) {
|
||||||
|
dirty = true;
|
||||||
|
hasUnsaved.value = true;
|
||||||
|
status.value = 'dirty';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onEdit(): void {
|
||||||
|
markDirty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 立即保存(右下角按钮 / 定时器 / 离开前调用) */
|
||||||
|
export async function saveNow(): Promise<boolean> {
|
||||||
|
if (!toolKey) return false;
|
||||||
|
const state = snapshot();
|
||||||
|
if (!state) return false;
|
||||||
|
const json = JSON.stringify({ machine: getMachineId(), tool: toolKey, state });
|
||||||
|
if (json.length > MAX_STATE_BYTES) {
|
||||||
|
status.value = 'error';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
status.value = 'saving';
|
||||||
|
try {
|
||||||
|
const { status: st } = await apiFetch('/draft/save', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders(toolKey) },
|
||||||
|
body: json,
|
||||||
|
});
|
||||||
|
if (st === 200) {
|
||||||
|
dirty = false;
|
||||||
|
hasUnsaved.value = false;
|
||||||
|
savedAt.value = Date.now();
|
||||||
|
status.value = 'saved';
|
||||||
|
restored.value = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
status.value = 'error';
|
||||||
|
return false;
|
||||||
|
} catch {
|
||||||
|
status.value = 'error';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 尝试恢复上次未保存的内容(仅当当前页面基本为空时,避免覆盖新输入) */
|
||||||
|
async function tryRestore(): Promise<void> {
|
||||||
|
if (!toolKey) return;
|
||||||
|
try {
|
||||||
|
const { status: st, body } = await apiFetch(
|
||||||
|
`/draft/load?machine=${encodeURIComponent(getMachineId())}&tool=${encodeURIComponent(toolKey)}`,
|
||||||
|
);
|
||||||
|
if (st !== 200 || !body?.data?.state) return;
|
||||||
|
// 往返期间用户已开始编辑则不打扰;进页面时页面值都是工具默认值,直接恢复
|
||||||
|
if (dirty) return;
|
||||||
|
await nextTick();
|
||||||
|
const applied = applyState(body.data.state);
|
||||||
|
if (applied <= 0) return; // 字段对不上(工具改版等)则不打扰用户
|
||||||
|
restored.value = true;
|
||||||
|
status.value = 'saved';
|
||||||
|
savedAt.value = Number(body.data.ts) * 1000 || Date.now();
|
||||||
|
try {
|
||||||
|
restoredBytes.value = new TextEncoder().encode(JSON.stringify(body.data.state)).length;
|
||||||
|
} catch {
|
||||||
|
restoredBytes.value = 0;
|
||||||
|
}
|
||||||
|
// 不做定时消失:恢复提示常驻到用户开始编辑(markDirty 会清掉),
|
||||||
|
// 让「当前功能的草稿」始终显示出来、随时可操作(丢弃 / 找回历史)。
|
||||||
|
} catch {
|
||||||
|
/* 静默失败,不阻断编辑 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 丢弃服务端当前草稿(页面上已显示的内容不动,只是不再保留该草稿) */
|
||||||
|
export async function discardDraft(): Promise<boolean> {
|
||||||
|
if (!toolKey) return false;
|
||||||
|
try {
|
||||||
|
const { status: st } = await apiFetch('/draft/delete', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders(toolKey) },
|
||||||
|
body: JSON.stringify({ machine: getMachineId(), tool: toolKey }),
|
||||||
|
});
|
||||||
|
if (st === 200) {
|
||||||
|
restored.value = false;
|
||||||
|
restoredBytes.value = 0;
|
||||||
|
savedAt.value = 0;
|
||||||
|
dirty = false;
|
||||||
|
hasUnsaved.value = false;
|
||||||
|
status.value = 'idle';
|
||||||
|
curTs.value = 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 历史版本清单(右下角「找回」面板用),失败返回空数组 */
|
||||||
|
export async function loadHistory(): Promise<{ ts: number; bytes: number }[]> {
|
||||||
|
if (!toolKey) return [];
|
||||||
|
try {
|
||||||
|
const { status: st, body } = await apiFetch(
|
||||||
|
`/draft/history?machine=${encodeURIComponent(getMachineId())}&tool=${encodeURIComponent(toolKey)}`,
|
||||||
|
);
|
||||||
|
if (st !== 200 || !Array.isArray(body?.data?.items)) return [];
|
||||||
|
curTs.value = Number(body.data.curTs) || 0;
|
||||||
|
return body.data.items;
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 回填指定历史版本到当前页面(找回重新编辑),返回是否成功 */
|
||||||
|
export async function restoreVersion(ts: number): Promise<boolean> {
|
||||||
|
if (!toolKey || !ts) return false;
|
||||||
|
try {
|
||||||
|
const { status: st, body } = await apiFetch(
|
||||||
|
`/draft/load?machine=${encodeURIComponent(getMachineId())}&tool=${encodeURIComponent(toolKey)}&ts=${ts}`,
|
||||||
|
);
|
||||||
|
if (st !== 200 || !body?.data?.state) return false;
|
||||||
|
await nextTick();
|
||||||
|
const applied = applyState(body.data.state);
|
||||||
|
if (applied <= 0) return false;
|
||||||
|
restored.value = true;
|
||||||
|
dirty = false;
|
||||||
|
hasUnsaved.value = false;
|
||||||
|
status.value = 'saved';
|
||||||
|
savedAt.value = ts * 1000 || Date.now();
|
||||||
|
try {
|
||||||
|
restoredBytes.value = new TextEncoder().encode(JSON.stringify(body.data.state)).length;
|
||||||
|
} catch {
|
||||||
|
restoredBytes.value = 0;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopTimer(): void {
|
||||||
|
if (timer !== null) {
|
||||||
|
window.clearInterval(timer);
|
||||||
|
timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 进入工具页:绑定事件 + 启动 1 分钟定时器 + 尝试恢复草稿 */
|
||||||
|
export function attach(tool: string): void {
|
||||||
|
toolKey = tool;
|
||||||
|
dirty = false;
|
||||||
|
hasUnsaved.value = false;
|
||||||
|
restored.value = false;
|
||||||
|
restoredBytes.value = 0;
|
||||||
|
curTs.value = 0;
|
||||||
|
status.value = 'idle';
|
||||||
|
savedAt.value = 0;
|
||||||
|
if (!bound) {
|
||||||
|
document.addEventListener('input', onEdit, true);
|
||||||
|
document.addEventListener('change', onEdit, true);
|
||||||
|
bound = true;
|
||||||
|
}
|
||||||
|
stopTimer();
|
||||||
|
timer = window.setInterval(() => {
|
||||||
|
if (dirty) void saveNow();
|
||||||
|
}, INTERVAL_MS);
|
||||||
|
void tryRestore();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 离开工具页:停表(未保存内容保留在服务器草稿里) */
|
||||||
|
export function detach(): void {
|
||||||
|
stopTimer();
|
||||||
|
toolKey = '';
|
||||||
|
dirty = false;
|
||||||
|
hasUnsaved.value = false;
|
||||||
|
status.value = 'idle';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 有未保存修改则提示,返回是否允许离开 */
|
||||||
|
export async function confirmLeave(): Promise<boolean> {
|
||||||
|
if (!dirty || !toolKey) return true;
|
||||||
|
const ok = window.confirm(
|
||||||
|
`当前内容还没保存,离开会丢失。\n\n是否保存后再离开?\n\n(点「确定」= 先保存再离开,点「取消」= 留在本页)`,
|
||||||
|
);
|
||||||
|
if (ok) {
|
||||||
|
const saved = await saveNow();
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 刷新 / 关闭标签页时的原生拦截 */
|
||||||
|
export function onBeforeUnload(e: BeforeUnloadEvent): void {
|
||||||
|
if (dirty && hasUnsaved.value) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.returnValue = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.addEventListener('beforeunload', onBeforeUnload);
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import { useHead } from '@vueuse/head';
|
|||||||
import type { HeadObject } from '@vueuse/head';
|
import type { HeadObject } from '@vueuse/head';
|
||||||
|
|
||||||
import BaseLayout from './base.layout.vue';
|
import BaseLayout from './base.layout.vue';
|
||||||
|
import AutosaveBar from '@/components/AutosaveBar.vue';
|
||||||
|
import { attach as autosaveAttach, detach as autosaveDetach } from '@/composable/autosave';
|
||||||
import FavoriteButton from '@/components/FavoriteButton.vue';
|
import FavoriteButton from '@/components/FavoriteButton.vue';
|
||||||
import LicenseGate from '@/tools/license/LicenseGate.vue';
|
import LicenseGate from '@/tools/license/LicenseGate.vue';
|
||||||
import type { Tool } from '@/tools/tools.types';
|
import type { Tool } from '@/tools/tools.types';
|
||||||
@@ -39,8 +41,22 @@ const head = computed<HeadObject>(() => ({
|
|||||||
useHead(head);
|
useHead(head);
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
// ===== 全站草稿自动保存:进入工具页绑定 1 分钟定时器,离开时停表 =====
|
||||||
|
watch(
|
||||||
|
() => route.path,
|
||||||
|
() => {
|
||||||
|
if (route.meta.isTool) {
|
||||||
|
autosaveAttach(route.path.replace(/^\//, ''));
|
||||||
|
} else {
|
||||||
|
autosaveDetach();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
onUnmounted(() => autosaveDetach());
|
||||||
|
|
||||||
// 宽屏工具:不受 600px 限宽,占满可用宽度(画布/多栏类工具)
|
// 宽屏工具:不受 600px 限宽,占满可用宽度(画布/多栏类工具)
|
||||||
const WIDE_TOOLS = new Set(['/label-designer', '/json-prettify', '/pdf-tools', '/image-tools', '/doc-convert', '/video-tools', '/seal-maker', '/signature-pad', '/ai-image-lab', '/ai-chat', '/copywriting', '/ai-gen', '/code-reader', '/my-ip', '/mcp-connect']);
|
const WIDE_TOOLS = new Set(['/label-designer', '/json-prettify', '/pdf-tools', '/image-tools', '/doc-convert', '/video-tools', '/seal-maker', '/signature-pad', '/ai-image-lab', '/ai-chat', '/copywriting', '/ai-gen', '/code-reader', '/my-ip', '/mcp-connect', '/poster-maker', '/ai-text-edit', '/ai-retouch']);
|
||||||
const isWide = computed(() => WIDE_TOOLS.has(route.path));
|
const isWide = computed(() => WIDE_TOOLS.has(route.path));
|
||||||
|
|
||||||
const i18nKey = computed<string>(() => route.path.trim().replace('/', ''));
|
const i18nKey = computed<string>(() => route.path.trim().replace('/', ''));
|
||||||
@@ -146,6 +162,9 @@ function retryAiHelp() {
|
|||||||
<slot />
|
<slot />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 右下角:自动保存状态 + 立即保存按钮 -->
|
||||||
|
<AutosaveBar />
|
||||||
|
|
||||||
<!-- 授权门:受控功能显示试用倒计时,到期锁定 -->
|
<!-- 授权门:受控功能显示试用倒计时,到期锁定 -->
|
||||||
<LicenseGate :path="route.path" />
|
<LicenseGate :path="route.path" />
|
||||||
</BaseLayout>
|
</BaseLayout>
|
||||||
|
|||||||
+328
-33
@@ -107,25 +107,77 @@ async function loadOverview() {
|
|||||||
overview.value = b.data;
|
overview.value = b.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============ 文件管理 ============
|
// ============ 文件管理(默认全量聚合,50 条/页自动分页)============
|
||||||
const fileUser = ref('');
|
const fileUser = ref(''); // ''=全部, '__gen__'=AI生成, 其他=指定用户
|
||||||
|
const fileKind = ref(''); // 按功能筛选:''=全部功能, '__none__'=未分类, 其他=kind 原值
|
||||||
|
const fileKinds = ref<{ k: string; n: number }[]>([]); // 后端返回的 kind 分布(带计数)
|
||||||
|
const KIND_LABELS: Record<string, string> = {
|
||||||
|
gen: 'AI 生图', edit: 'AI 图片编辑', 'face-swap': 'AI 换脸', retouch: 'AI 修图',
|
||||||
|
'text-edit': 'AI 文字编辑', poster: 'AI 海报', 'text-to-image': '文字生图',
|
||||||
|
'image-lab': 'AI 图片实验室', 'image-tools': '图片工具', 'label-designer': '标签设计',
|
||||||
|
'pdf-tools': 'PDF 工具', ocr: 'OCR 识别', mcp: 'MCP 产出', __none__: '未分类',
|
||||||
|
};
|
||||||
|
function kindLabel(k: string) {
|
||||||
|
return KIND_LABELS[k] || k || '未分类';
|
||||||
|
}
|
||||||
const fileList = ref<any[]>([]);
|
const fileList = ref<any[]>([]);
|
||||||
const fileTotal = ref(0);
|
const fileTotal = ref(0); // 合计字节数
|
||||||
|
const fileCount = ref(0); // 总记录数
|
||||||
|
const filePage = ref(1);
|
||||||
|
const filePages = ref(1);
|
||||||
|
const FILE_PAGE_SIZE = 50;
|
||||||
const cleanupDays = ref(7);
|
const cleanupDays = ref(7);
|
||||||
const cleanupUser = ref('');
|
const cleanupUser = ref('');
|
||||||
const cleanupResult = ref('');
|
const cleanupResult = ref('');
|
||||||
|
|
||||||
async function loadFiles() {
|
async function loadFiles() {
|
||||||
if (!fileUser.value) {
|
const q = new URLSearchParams();
|
||||||
return;
|
if (fileUser.value === '__gen__') q.set('scope', 'gen');
|
||||||
}
|
else if (fileUser.value) q.set('username', fileUser.value);
|
||||||
const b = await api(`/admin/files?username=${encodeURIComponent(fileUser.value)}`);
|
if (fileKind.value) q.set('kind', fileKind.value);
|
||||||
|
q.set('page', String(filePage.value));
|
||||||
|
q.set('page_size', String(FILE_PAGE_SIZE));
|
||||||
|
const b = await api(`/admin/files?${q}`);
|
||||||
fileList.value = b.data?.files ?? [];
|
fileList.value = b.data?.files ?? [];
|
||||||
|
fileKinds.value = b.data?.kinds ?? [];
|
||||||
fileTotal.value = b.data?.total_size ?? 0;
|
fileTotal.value = b.data?.total_size ?? 0;
|
||||||
|
fileCount.value = b.data?.total ?? 0;
|
||||||
|
filePages.value = b.data?.pages ?? 1;
|
||||||
|
filePage.value = b.data?.page ?? 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function delFile(id: string) {
|
function gotoFilePage(p: number) {
|
||||||
const b = await api('/admin/delete-file', { method: 'POST', body: JSON.stringify({ id, username: fileUser.value }) });
|
filePage.value = Math.min(Math.max(1, p), filePages.value);
|
||||||
|
loadFiles();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 文件直链:缩略图 <img> 与下载 <a> 无法携带 header,鉴权走 ?token=
|
||||||
|
function fileUrl(f: any, dl = false) {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
q.set('path', f.path || '');
|
||||||
|
if (f.name) q.set('name', f.name);
|
||||||
|
if (dl) q.set('dl', '1');
|
||||||
|
if (token.value) q.set('token', token.value);
|
||||||
|
return `/relay/admin/file?${q}`;
|
||||||
|
}
|
||||||
|
const preview = ref<any>(null); // 文件管理图片预览浮层(点缩略图站内打开,替代 window.open 弹窗)
|
||||||
|
function fileOwner(f: any) {
|
||||||
|
if (f.source === 'gen') return f.machine || 'AI';
|
||||||
|
if (f.source === 'mcp') return 'MCP';
|
||||||
|
return f.username || f.source || '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function delFile(f: any) {
|
||||||
|
const body: any = { id: f.id };
|
||||||
|
if (f.source === 'gen') {
|
||||||
|
body.username = '__gen__';
|
||||||
|
body.machine = f.machine;
|
||||||
|
} else if (f.source === 'mcp') {
|
||||||
|
body.username = '__mcp__';
|
||||||
|
} else {
|
||||||
|
body.username = f.username || fileUser.value;
|
||||||
|
}
|
||||||
|
const b = await api('/admin/delete-file', { method: 'POST', body: JSON.stringify(body) });
|
||||||
if (b.code === 200) {
|
if (b.code === 200) {
|
||||||
await loadFiles();
|
await loadFiles();
|
||||||
loadOverview();
|
loadOverview();
|
||||||
@@ -144,9 +196,8 @@ async function cleanup() {
|
|||||||
if (b.code === 200) {
|
if (b.code === 200) {
|
||||||
cleanupResult.value = `已删除 ${b.data.removed} 个文件,释放 ${fmtSize(b.data.freed)}`;
|
cleanupResult.value = `已删除 ${b.data.removed} 个文件,释放 ${fmtSize(b.data.freed)}`;
|
||||||
loadOverview();
|
loadOverview();
|
||||||
if (fileUser.value) {
|
filePage.value = 1;
|
||||||
loadFiles();
|
loadFiles();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,6 +205,7 @@ function pickUser(u: string) {
|
|||||||
fileUser.value = u;
|
fileUser.value = u;
|
||||||
cleanupUser.value = u;
|
cleanupUser.value = u;
|
||||||
tab.value = 'files';
|
tab.value = 'files';
|
||||||
|
filePage.value = 1;
|
||||||
loadFiles();
|
loadFiles();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -465,12 +517,77 @@ function recoMove(i: number, d: -1 | 1) {
|
|||||||
reco.value.splice(j, 0, it);
|
reco.value.splice(j, 0, it);
|
||||||
}
|
}
|
||||||
|
|
||||||
const tab = ref<'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'reco' | 'feedback'>('overview');
|
// ============ 授权应用(前台显示开关 + 每日试用时长) ============
|
||||||
|
/** relay PROTECTED_TOOLS 全量 18 项:中文名与入口类型(page=有前台页面可隐藏;api=纯服务端门禁) */
|
||||||
|
const TOOL_META: Record<string, { name: string; kind: 'page' | 'api' }> = {
|
||||||
|
translator: { name: '在线翻译', kind: 'page' },
|
||||||
|
'image-ocr': { name: '图片OCR文字识别', kind: 'page' },
|
||||||
|
'pdf-ocr': { name: 'PDF文字识别', kind: 'page' },
|
||||||
|
'ai-retouch': { name: 'AI修图', kind: 'page' },
|
||||||
|
'doc-convert': { name: '文档格式转换', kind: 'page' },
|
||||||
|
'image-tools': { name: '图片工具', kind: 'page' },
|
||||||
|
'pdf-tools': { name: 'PDF工具', kind: 'page' },
|
||||||
|
'video-tools': { name: '视频工具', kind: 'page' },
|
||||||
|
'audio-tools': { name: '音频工具', kind: 'page' },
|
||||||
|
'text-to-image': { name: '文字生成图片', kind: 'page' },
|
||||||
|
'ai-image-tools': { name: 'AI图片实验室', kind: 'page' },
|
||||||
|
copywriting: { name: '文案工具箱', kind: 'page' },
|
||||||
|
'screenshot-qa': { name: '截图问答', kind: 'api' },
|
||||||
|
'video-subtitle': { name: '视频字幕提取', kind: 'api' },
|
||||||
|
'ai-gen': { name: 'AI 生图', kind: 'page' },
|
||||||
|
'ai-text-edit': { name: 'AI 无痕改字', kind: 'page' },
|
||||||
|
'face-swap': { name: 'AI换脸', kind: 'page' },
|
||||||
|
'poster-maker': { name: 'AI海报生成', kind: 'page' },
|
||||||
|
};
|
||||||
|
const toolsList = ref<{ slug: string; visible: boolean; trial_minutes: number }[]>([]);
|
||||||
|
const toolsDefaultTrial = ref(30);
|
||||||
|
const toolsSaving = ref(false);
|
||||||
|
const toolsMsg = ref('');
|
||||||
|
|
||||||
|
async function loadTools() {
|
||||||
|
toolsMsg.value = '';
|
||||||
|
try {
|
||||||
|
const b = await api('/admin/tools');
|
||||||
|
if (b?.code === 200) {
|
||||||
|
toolsList.value = b.data.tools;
|
||||||
|
toolsDefaultTrial.value = b.data.default_trial;
|
||||||
|
} else {
|
||||||
|
toolsMsg.value = b?.message || '加载失败';
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
toolsMsg.value = e?.message || '加载失败';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveTools() {
|
||||||
|
toolsSaving.value = true;
|
||||||
|
toolsMsg.value = '';
|
||||||
|
try {
|
||||||
|
const body: Record<string, { visible: boolean; trial_minutes: number }> = {};
|
||||||
|
for (const t of toolsList.value) {
|
||||||
|
const m = Math.min(1440, Math.max(1, Math.round(Number(t.trial_minutes) || toolsDefaultTrial.value)));
|
||||||
|
body[t.slug] = { visible: t.visible, trial_minutes: m };
|
||||||
|
}
|
||||||
|
const b = await api('/admin/tools', { method: 'POST', body: JSON.stringify({ tools: body }) });
|
||||||
|
if (b?.code === 200) {
|
||||||
|
toolsMsg.value = '已保存,前台页面刷新后生效';
|
||||||
|
await loadTools();
|
||||||
|
} else {
|
||||||
|
toolsMsg.value = b?.message || '保存失败';
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
toolsMsg.value = e?.message || '保存失败';
|
||||||
|
} finally {
|
||||||
|
toolsSaving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const tab = ref<'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'reco' | 'feedback' | 'tools'>('overview');
|
||||||
|
|
||||||
// 在线人数 30s 自动刷新(切走用量页签即停)
|
// 在线人数 30s 自动刷新(切走用量页签即停)
|
||||||
let usageTimer: ReturnType<typeof setInterval> | null = null;
|
let usageTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'reco' | 'feedback') {
|
function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'reco' | 'feedback' | 'tools') {
|
||||||
if (usageTimer) {
|
if (usageTimer) {
|
||||||
clearInterval(usageTimer);
|
clearInterval(usageTimer);
|
||||||
usageTimer = null;
|
usageTimer = null;
|
||||||
@@ -489,12 +606,18 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
|
|||||||
if (id === 'mcp') {
|
if (id === 'mcp') {
|
||||||
loadMcpUsage();
|
loadMcpUsage();
|
||||||
}
|
}
|
||||||
|
if (id === 'tools') {
|
||||||
|
loadTools();
|
||||||
|
}
|
||||||
if (id === 'storage') {
|
if (id === 'storage') {
|
||||||
loadStorage();
|
loadStorage();
|
||||||
}
|
}
|
||||||
if (id === 'feedback') {
|
if (id === 'feedback') {
|
||||||
loadFeedback();
|
loadFeedback();
|
||||||
}
|
}
|
||||||
|
if (id === 'files') {
|
||||||
|
loadFiles();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -523,6 +646,7 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
|
|||||||
<div class="adm-nav">
|
<div class="adm-nav">
|
||||||
<div class="adm-nav-item" :class="{ active: tab === 'overview' }" @click="switchTab('overview')">📊 总览与用户</div>
|
<div class="adm-nav-item" :class="{ active: tab === 'overview' }" @click="switchTab('overview')">📊 总览与用户</div>
|
||||||
<div class="adm-nav-item" :class="{ active: tab === 'files' }" @click="switchTab('files')">📁 文件管理</div>
|
<div class="adm-nav-item" :class="{ active: tab === 'files' }" @click="switchTab('files')">📁 文件管理</div>
|
||||||
|
<div class="adm-nav-item" :class="{ active: tab === 'tools' }" @click="switchTab('tools')">🧩 授权应用</div>
|
||||||
<div class="adm-nav-item" :class="{ active: tab === 'usage' }" @click="switchTab('usage')">📈 使用统计</div>
|
<div class="adm-nav-item" :class="{ active: tab === 'usage' }" @click="switchTab('usage')">📈 使用统计</div>
|
||||||
<div class="adm-nav-item" :class="{ active: tab === 'mcp' }" @click="switchTab('mcp')">🤖 MCP 调用</div>
|
<div class="adm-nav-item" :class="{ active: tab === 'mcp' }" @click="switchTab('mcp')">🤖 MCP 调用</div>
|
||||||
<div class="adm-nav-item" :class="{ active: tab === 'storage' }" @click="switchTab('storage')">💾 存储设置</div>
|
<div class="adm-nav-item" :class="{ active: tab === 'storage' }" @click="switchTab('storage')">💾 存储设置</div>
|
||||||
@@ -592,11 +716,21 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
|
|||||||
<!-- files -->
|
<!-- files -->
|
||||||
<template v-if="tab === 'files'">
|
<template v-if="tab === 'files'">
|
||||||
<div class="adm-toolbar">
|
<div class="adm-toolbar">
|
||||||
<select v-model="fileUser" class="adm-select" @change="loadFiles">
|
<select v-model="fileUser" class="adm-select" @change="filePage = 1; loadFiles()">
|
||||||
<option value="">选择用户…</option>
|
<option value="">全部(所有用户 + AI 生成 + MCP)</option>
|
||||||
<option v-for="u in users" :key="u.username" :value="u.username">{{ u.username }}</option>
|
<option value="__gen__">仅 AI 生成图片(换脸/生图/海报)</option>
|
||||||
|
<option v-for="u in users" :key="u.username" :value="u.username">仅 {{ u.username }}</option>
|
||||||
</select>
|
</select>
|
||||||
<span v-if="fileList.length" class="adm-sub">{{ fileList.length }} 个文件 · 合计 {{ fmtSize(fileTotal) }}</span>
|
<select v-model="fileKind" class="adm-select" title="按功能查询文件" @change="filePage = 1; loadFiles()">
|
||||||
|
<option value="">全部功能</option>
|
||||||
|
<option v-for="k in fileKinds" :key="k.k" :value="k.k">{{ kindLabel(k.k) }}({{ k.n }})</option>
|
||||||
|
</select>
|
||||||
|
<span class="adm-sub">共 {{ fileCount }} 条记录 · 合计 {{ fmtSize(fileTotal) }}</span>
|
||||||
|
<span v-if="filePages > 1" class="adm-pager">
|
||||||
|
<button class="adm-btn adm-btn-sm" :disabled="filePage <= 1" @click="gotoFilePage(filePage - 1)">‹ 上一页</button>
|
||||||
|
<span class="adm-pageinfo">第 {{ filePage }} / {{ filePages }} 页</span>
|
||||||
|
<button class="adm-btn adm-btn-sm" :disabled="filePage >= filePages" @click="gotoFilePage(filePage + 1)">下一页 ›</button>
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="adm-cleanup">
|
<div class="adm-cleanup">
|
||||||
@@ -617,24 +751,86 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
|
|||||||
<span v-if="cleanupResult" class="adm-ok">{{ cleanupResult }}</span>
|
<span v-if="cleanupResult" class="adm-ok">{{ cleanupResult }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<table class="adm-table">
|
<div class="adm-fscroll">
|
||||||
<thead>
|
<table class="adm-table">
|
||||||
<tr><th>文件</th><th>类型</th><th>大小</th><th>时间</th><th></th></tr>
|
<thead>
|
||||||
</thead>
|
<tr><th class="adm-thumbcol">预览</th><th>文件</th><th>来源</th><th>类型</th><th>大小</th><th>时间</th><th></th></tr>
|
||||||
<tbody>
|
</thead>
|
||||||
<tr v-for="f in fileList" :key="f.id">
|
<tbody>
|
||||||
<td class="adm-fname">{{ f.name }}</td>
|
<tr v-for="f in fileList" :key="(f.source || '') + ':' + (f.machine || '') + ':' + f.id">
|
||||||
<td>{{ f.kind || '-' }}</td>
|
<td class="adm-thumbcell">
|
||||||
<td>{{ fmtSize(f.size) }}</td>
|
<img v-if="f.is_image" class="adm-thumb" :src="fileUrl(f)" alt="" @click="preview = f">
|
||||||
<td>{{ fmtTime(f.mtime) }}</td>
|
<span v-else class="adm-ftype">{{ f.file_type || '文件' }}</span>
|
||||||
<td><a href="javascript:;" class="adm-del" @click="delFile(f.id)">删除</a></td>
|
</td>
|
||||||
</tr>
|
<td class="adm-fname" :title="f.prompt || f.name">{{ f.name }}</td>
|
||||||
<tr v-if="!fileList.length"><td colspan="5" class="adm-none">{{ fileUser ? '该用户暂无文件' : '请先选择用户' }}</td></tr>
|
<td>{{ fileOwner(f) }}</td>
|
||||||
</tbody>
|
<td>{{ kindLabel(f.kind || '__none__') }}</td>
|
||||||
</table>
|
<td>{{ fmtSize(f.size) }}</td>
|
||||||
|
<td>{{ fmtTime(f.mtime) }}</td>
|
||||||
|
<td class="adm-ops">
|
||||||
|
<a :href="fileUrl(f, true)" class="adm-dl" download>下载</a>
|
||||||
|
<a href="javascript:;" class="adm-del" @click="delFile(f)">删除</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-if="!fileList.length"><td colspan="7" class="adm-none">暂无文件</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div v-if="filePages > 1" class="adm-pager adm-pager-b">
|
||||||
|
<button class="adm-btn adm-btn-sm" :disabled="filePage <= 1" @click="gotoFilePage(filePage - 1)">‹ 上一页</button>
|
||||||
|
<span class="adm-pageinfo">第 {{ filePage }} / {{ filePages }} 页 · 共 {{ fileCount }} 条</span>
|
||||||
|
<button class="adm-btn adm-btn-sm" :disabled="filePage >= filePages" @click="gotoFilePage(filePage + 1)">下一页 ›</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="preview" class="adm-preview" @click="preview = null">
|
||||||
|
<img :src="fileUrl(preview)" :alt="preview.name" @click.stop>
|
||||||
|
<div class="adm-preview-bar" @click.stop>
|
||||||
|
<span class="adm-preview-name">{{ preview.name }}</span>
|
||||||
|
<a :href="fileUrl(preview, true)" class="adm-dl" download>下载</a>
|
||||||
|
<button class="adm-btn adm-btn-sm" @click="preview = null">关闭</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- storage -->
|
<!-- storage -->
|
||||||
|
<!-- tools(授权应用:显示开关 + 试用时长) -->
|
||||||
|
<template v-if="tab === 'tools'">
|
||||||
|
<h3 class="adm-h3">🧩 授权应用管理 <span class="adm-sub">控制前台是否显示 + 每个功能每日免费试用时长(分钟),保存后前台刷新生效</span></h3>
|
||||||
|
<div class="adm-card">
|
||||||
|
<div class="adm-toolbar">
|
||||||
|
<span class="adm-sub">共 {{ toolsList.length }} 个授权应用 · 默认试用 {{ toolsDefaultTrial }} 分钟/天</span>
|
||||||
|
<div class="adm-actions">
|
||||||
|
<span v-if="toolsMsg" class="adm-ok">{{ toolsMsg }}</span>
|
||||||
|
<button class="adm-btn adm-btn-sm" :disabled="toolsSaving" @click="saveTools">{{ toolsSaving ? '保存中…' : '保存全部' }}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="adm-tools-scroll">
|
||||||
|
<table class="adm-table adm-tools-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>应用</th><th>标识</th><th>入口</th><th>前台显示</th><th>每日免费试用(分钟)</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="t in toolsList" :key="t.slug">
|
||||||
|
<td class="adm-tool-name">{{ TOOL_META[t.slug]?.name || t.slug }}</td>
|
||||||
|
<td><code class="adm-slug">{{ t.slug }}</code></td>
|
||||||
|
<td>{{ TOOL_META[t.slug]?.kind === 'page' ? '页面' : 'API' }}</td>
|
||||||
|
<td>
|
||||||
|
<label class="adm-switch" :class="{ off: !t.visible }">
|
||||||
|
<input type="checkbox" v-model="t.visible" :disabled="TOOL_META[t.slug]?.kind !== 'page'">
|
||||||
|
<span class="adm-switch-txt">{{ t.visible ? '显示' : '隐藏' }}</span>
|
||||||
|
</label>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<input type="number" class="adm-input adm-num" min="1" max="1440" v-model.number="t.trial_minutes">
|
||||||
|
<span class="adm-sub">1-1440</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="adm-sub" style="margin-top:8px">「入口=API」的条目没有前台页面(仅服务端门禁),显示开关不适用;试用时长对其门禁生效。隐藏的应用从菜单、收藏、定价与首页推荐同步消失(直连地址仍可用)。</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<template v-if="tab === 'storage'">
|
<template v-if="tab === 'storage'">
|
||||||
<h3 class="adm-h3">💾 文件存储设置 <span class="adm-sub">用户上传文件与云端数据的实际存放位置</span></h3>
|
<h3 class="adm-h3">💾 文件存储设置 <span class="adm-sub">用户上传文件与云端数据的实际存放位置</span></h3>
|
||||||
<div class="adm-storage-info" v-if="storage">
|
<div class="adm-storage-info" v-if="storage">
|
||||||
@@ -1248,6 +1444,93 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== 文件管理:缩略图/类型徽标/分页 ===== */
|
||||||
|
/* 图片预览浮层:点缩略图站内打开(不 window.open——popup 拦截会吞掉,且 token 不进新 tab 地址栏) */
|
||||||
|
.adm-preview { position: fixed; inset: 0; z-index: 10000; background: rgba(0, 0, 0, 0.88); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; cursor: zoom-out; }
|
||||||
|
.adm-preview img { max-width: 92vw; max-height: 78vh; object-fit: contain; background: #fff; border-radius: 8px; cursor: default; }
|
||||||
|
.adm-preview-bar { display: flex; align-items: center; gap: 14px; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 8px; padding: 8px 14px; cursor: default; }
|
||||||
|
.adm-preview-name { color: #fff; font-size: 13px; max-width: 52vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.adm-fscroll {
|
||||||
|
overflow-x: auto;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
|
||||||
|
.adm-table {
|
||||||
|
min-width: 860px;
|
||||||
|
|
||||||
|
th {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-thumbcol,
|
||||||
|
.adm-thumbcell {
|
||||||
|
width: 116px;
|
||||||
|
padding-top: 8px !important;
|
||||||
|
padding-bottom: 8px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-thumb {
|
||||||
|
width: 100px;
|
||||||
|
height: 100px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid rgba(128, 128, 128, 0.22);
|
||||||
|
background: rgba(128, 128, 128, 0.06);
|
||||||
|
display: block;
|
||||||
|
cursor: zoom-in;
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-ftype {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100px;
|
||||||
|
height: 64px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: rgba(128, 128, 128, 0.1);
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 13px;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
color: rgba(128, 128, 128, 0.95);
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-ops {
|
||||||
|
white-space: nowrap;
|
||||||
|
|
||||||
|
a + a {
|
||||||
|
margin-left: 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-dl {
|
||||||
|
color: #18a058;
|
||||||
|
text-decoration: none;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-pager {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-pager-b {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
margin-top: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.adm-pageinfo {
|
||||||
|
font-size: 12.5px;
|
||||||
|
opacity: 0.75;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
.adm-userbar {
|
.adm-userbar {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -1482,4 +1765,16 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'mcp' | 'storage' | 'rec
|
|||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== 授权应用管理(窄视口内滚,min-width+nowrap 防错行) ===== */
|
||||||
|
.adm-tools-scroll { overflow-x: auto; }
|
||||||
|
.adm-tools-table { min-width: 560px; }
|
||||||
|
.adm-tools-table th { white-space: nowrap; }
|
||||||
|
.adm-tool-name { white-space: nowrap; font-weight: 600; }
|
||||||
|
.adm-slug { font-size: 12px; opacity: .75; }
|
||||||
|
.adm-num { width: 92px; }
|
||||||
|
.adm-switch { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; }
|
||||||
|
.adm-switch input { width: 16px; height: 16px; cursor: pointer; }
|
||||||
|
.adm-switch.off { opacity: .6; }
|
||||||
|
.adm-switch-txt { font-size: 13px; }
|
||||||
</style>
|
</style>
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useHead } from '@vueuse/head';
|
import { useHead } from '@vueuse/head';
|
||||||
import { AUTH_BASE, getMachineId, licenseState, checkAuth, PROTECTED_TOOLS } from '@/tools/license/license';
|
import { computed } from 'vue';
|
||||||
|
import { AUTH_BASE, getMachineId, licenseState, checkAuth, PROTECTED_TOOLS, toolVisible } from '@/tools/license/license';
|
||||||
|
|
||||||
/** 授权功能数量:与 pricing/侧栏同源(license.ts PROTECTED_TOOLS),新授权应用上线自动 +1 */
|
/** 授权功能数量:与 pricing/侧栏同源(license.ts PROTECTED_TOOLS),新授权应用上线自动 +1 */
|
||||||
const paidCount = Object.keys(PROTECTED_TOOLS).length;
|
const paidCount = computed(() => Object.keys(PROTECTED_TOOLS).filter(toolVisible).length);
|
||||||
|
|
||||||
useHead({ title: '购买卡密 - IT-TOOLS-PRO' });
|
useHead({ title: '购买卡密 - IT-TOOLS-PRO' });
|
||||||
|
|
||||||
@@ -124,7 +125,7 @@ async function refreshAuth(): Promise<void> {
|
|||||||
authMsg.value = '正在核验授权…';
|
authMsg.value = '正在核验授权…';
|
||||||
try {
|
try {
|
||||||
const ok = await checkAuth();
|
const ok = await checkAuth();
|
||||||
authMsg.value = ok ? `授权已生效,${paidCount} 个高级功能已解锁` : '卡密已发放,授权暂未刷新,请点击下方重新核验';
|
authMsg.value = ok ? `授权已生效,${paidCount.value} 个高级功能已解锁` : '卡密已发放,授权暂未刷新,请点击下方重新核验';
|
||||||
} catch {
|
} catch {
|
||||||
authMsg.value = '授权核验失败,请稍后重试';
|
authMsg.value = '授权核验失败,请稍后重试';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,15 +7,18 @@ import ColoredCard from '../components/ColoredCard.vue';
|
|||||||
import ToolCard from '../components/ToolCard.vue';
|
import ToolCard from '../components/ToolCard.vue';
|
||||||
import { useToolStore } from '@/tools/tools.store';
|
import { useToolStore } from '@/tools/tools.store';
|
||||||
import { useRecentTools } from '@/composable/recent-tools';
|
import { useRecentTools } from '@/composable/recent-tools';
|
||||||
|
import { toolVisible } from '@/tools/license/license';
|
||||||
|
|
||||||
// 近期新功能亮点(手动维护,新工具上线时加一条)
|
// 近期新功能亮点(手动维护,新工具上线时加一条)
|
||||||
// ★铁规则:每完成一批新功能/新工具,必须在这里最前面加条目(新→旧),否则首页看不到
|
// ★铁规则:每完成一批新功能/新工具,必须在这里最前面加条目(新→旧),否则首页看不到
|
||||||
const NEW_FEATURES = [
|
const NEW_FEATURES = [
|
||||||
|
{ path: '/ai-image-lab', icon: '🧬', name: '图片处理历史全覆盖', desc: 'AI生图、AI修图、AI图片实验室、AI海报、AI换脸五个工具的每个处理动作(抠图换底、证件照、超分、画布导出等)全部自动存服务端历史,右侧50×50缩略图即时可见' },
|
||||||
|
{ path: '/qrcode-generator', icon: '🕘', name: '草稿找回历史版本', desc: '右下角自动保存条新增「找回」按钮,列出该工具近 20 份保存历史(时间精确到秒),点任意一条立即恢复成那一版继续编辑' },
|
||||||
|
{ path: '/ai-gen', icon: '🗂️', name: '图片历史铁规则', desc: '所有生图功能右侧 50×50 缩略图历史竖排、点击看大图,按登录账号/机器码只看本人的,生成即保存到后台指定目录,全部功能历史最多显示100条' },
|
||||||
{ path: '/face-swap', icon: '🎭', name: 'AI 换脸', desc: '上传源人脸与目标照片,本地 AI 一键换脸(insightface 人脸检测+inswapper),授权功能支持免费试用' },
|
{ path: '/face-swap', icon: '🎭', name: 'AI 换脸', desc: '上传源人脸与目标照片,本地 AI 一键换脸(insightface 人脸检测+inswapper),授权功能支持免费试用' },
|
||||||
{ path: '/poster-maker', icon: '🖼️', name: 'AI 海报生成', desc: '热门海报模板任选:改文字、换图片、AI 生成配图与背景,一键导出 PNG' },
|
{ path: '/poster-maker', icon: '🖼️', name: 'AI 海报生成', desc: '42套模板10分类(含校园师生款)、文字图片可旋转、整页自适应不滚动,改文字换图片AI生成配图,一键导出 PNG' },
|
||||||
{ path: '/ai-gen', icon: '🎨', name: 'AI 生图', desc: '10款内置模型一键出图,四组86个现成提示词(通用/自媒体/电商/软件类),中文自动转英文发送' },
|
{ path: '/ai-gen', icon: '🎨', name: 'AI 生图', desc: '10款内置模型一键出图,四组86个现成提示词(通用/自媒体/电商/软件类),中文自动转英文发送' },
|
||||||
{ path: '/mcp-connect', icon: '🔌', name: 'AI 接入 (MCP)', desc: '把本站能力接到任意 AI 客户端,13个工具、卡密令牌管理、调用记录后台可查' },
|
{ path: '/mcp-connect', icon: '🔌', name: 'AI 接入 (MCP)', desc: '把本站能力接到任意 AI 客户端,13个工具、卡密令牌管理、调用记录后台可查' },
|
||||||
{ path: '/admin', icon: '📊', name: '管理后台升级', desc: '使用统计含未登录访客、在线人数实时排行、留言反馈与公告推送、用户最后登录时间' },
|
|
||||||
{ path: '/my-ip', icon: '🌍', name: '本机IP查询', desc: '公网IPv4/IPv6地址与所属地一键查询,自动测9个热门地点延迟,一键测试当前下载上传网速' },
|
{ path: '/my-ip', icon: '🌍', name: '本机IP查询', desc: '公网IPv4/IPv6地址与所属地一键查询,自动测9个热门地点延迟,一键测试当前下载上传网速' },
|
||||||
{ path: '/code-reader', icon: '🧩', name: '二维码生成', desc: '识别工具内新能力:自定义颜色、中间插入本地 Logo 图,生成后自动自扫验证' },
|
{ path: '/code-reader', icon: '🧩', name: '二维码生成', desc: '识别工具内新能力:自定义颜色、中间插入本地 Logo 图,生成后自动自扫验证' },
|
||||||
{ path: '/base64-image-converter', icon: '🔁', name: 'Base64图片互转', desc: 'Base64转图片与图片转Base64合一页,三格式自动识别,纯浏览器本地不上传' },
|
{ path: '/base64-image-converter', icon: '🔁', name: 'Base64图片互转', desc: 'Base64转图片与图片转Base64合一页,三格式自动识别,纯浏览器本地不上传' },
|
||||||
@@ -39,6 +42,8 @@ const { recentTools } = useRecentTools();
|
|||||||
|
|
||||||
// 近期新功能:静态清单(新开发功能上线时手动加一条)
|
// 近期新功能:静态清单(新开发功能上线时手动加一条)
|
||||||
const newFeatures = ref<any[]>(NEW_FEATURES);
|
const newFeatures = ref<any[]>(NEW_FEATURES);
|
||||||
|
/** 管理后台关闭显示的条目不出现在首页推荐;/admin 后台功能一律不进「近期新功能」(用户 2026-11-16 要求) */
|
||||||
|
const visibleNewFeatures = computed(() => newFeatures.value.filter(f => toolVisible(f.path) && f.path !== '/admin'));
|
||||||
|
|
||||||
// 精选推荐:管理后台配置(/relay/reco),独立区块置顶显示;为空则隐藏该区块
|
// 精选推荐:管理后台配置(/relay/reco),独立区块置顶显示;为空则隐藏该区块
|
||||||
const recoList = ref<any[]>([]);
|
const recoList = ref<any[]>([]);
|
||||||
@@ -284,11 +289,11 @@ function onUpdateFavoriteTools() {
|
|||||||
<!-- 近期新功能 -->
|
<!-- 近期新功能 -->
|
||||||
<div class="nf-block">
|
<div class="nf-block">
|
||||||
<div class="nf-head">
|
<div class="nf-head">
|
||||||
<span class="nf-title">🆕 近期新功能 <em class="nf-count">{{ newFeatures.length }}</em></span>
|
<span class="nf-title">🆕 近期新功能 <em class="nf-count">{{ visibleNewFeatures.length }}</em></span>
|
||||||
<span class="nf-sub">持续更新中,登录后数据云端同步、授权跟随账号</span>
|
<span class="nf-sub">持续更新中,登录后数据云端同步、授权跟随账号</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="nf-grid">
|
<div class="nf-grid">
|
||||||
<RouterLink v-for="f in newFeatures" :key="f.path" :to="f.path" class="nf-card">
|
<RouterLink v-for="f in visibleNewFeatures" :key="f.path" :to="f.path" class="nf-card">
|
||||||
<span class="nf-icon">{{ f.icon }}</span>
|
<span class="nf-icon">{{ f.icon }}</span>
|
||||||
<span class="nf-body">
|
<span class="nf-body">
|
||||||
<span class="nf-name">{{ f.name }} <em class="nf-badge">新</em></span>
|
<span class="nf-name">{{ f.name }} <em class="nf-badge">新</em></span>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useHead } from '@vueuse/head';
|
import { useHead } from '@vueuse/head';
|
||||||
import { PROTECTED_TOOLS, getMachineId } from '@/tools/license/license';
|
import { PROTECTED_TOOLS, getMachineId, toolVisible } from '@/tools/license/license';
|
||||||
import { useToolStore } from '@/tools/tools.store';
|
import { useToolStore } from '@/tools/tools.store';
|
||||||
|
|
||||||
useHead({ title: '授权应用 - IT-TOOLS-PRO' });
|
useHead({ title: '授权应用 - IT-TOOLS-PRO' });
|
||||||
@@ -41,7 +41,7 @@ const MARKETING: Record<string, { icon: string; points: string[] }> = {
|
|||||||
|
|
||||||
/** 授权功能清单 = license.ts 的 PROTECTED_TOOLS(唯一权威源),本页零手工维护 */
|
/** 授权功能清单 = license.ts 的 PROTECTED_TOOLS(唯一权威源),本页零手工维护 */
|
||||||
const toolStore = useToolStore();
|
const toolStore = useToolStore();
|
||||||
const paidFeatures = computed<Feature[]>(() => Object.keys(PROTECTED_TOOLS).map((path) => {
|
const paidFeatures = computed<Feature[]>(() => Object.keys(PROTECTED_TOOLS).filter(toolVisible).map((path) => {
|
||||||
const tool = toolStore.tools.find(t => t.path === path);
|
const tool = toolStore.tools.find(t => t.path === path);
|
||||||
const m = MARKETING[path];
|
const m = MARKETING[path];
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import NotFound from './pages/404.page.vue';
|
|||||||
import { tools } from './tools';
|
import { tools } from './tools';
|
||||||
import { config } from './config';
|
import { config } from './config';
|
||||||
import { reportToolUsage, startOnlineHeartbeat } from './tools/license/license';
|
import { reportToolUsage, startOnlineHeartbeat } from './tools/license/license';
|
||||||
|
import { confirmLeave } from './composable/autosave';
|
||||||
import { routes as demoRoutes } from './ui/demo/demo.routes';
|
import { routes as demoRoutes } from './ui/demo/demo.routes';
|
||||||
|
|
||||||
const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({
|
const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({
|
||||||
@@ -68,4 +69,10 @@ router.afterEach((to) => {
|
|||||||
startOnlineHeartbeat();
|
startOnlineHeartbeat();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ===== 全站草稿保护:有未保存修改时拦截站内前进/后退/跳转 =====
|
||||||
|
// 「确定」= 先保存再离开;「取消」= 留在本页(返回 false 中断导航)
|
||||||
|
router.beforeEach(async () => {
|
||||||
|
return await confirmLeave();
|
||||||
|
});
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { getMachineId, licenseHeaders } from '@/tools/license/license';
|
import { getMachineId, licenseHeaders } from '@/tools/license/license';
|
||||||
|
import { authHdr } from '@/tools/img-hist/img-hist';
|
||||||
|
import ImgEditor from './img-editor.vue';
|
||||||
|
|
||||||
const models = ref<{ id: string; i2i: boolean; custom?: boolean }[]>([]);
|
const models = ref<{ id: string; i2i: boolean; custom?: boolean }[]>([]);
|
||||||
const model = ref(''); // 打开页面默认选中列表第一个模型
|
const model = ref(''); // 打开页面默认选中列表第一个模型
|
||||||
@@ -8,6 +10,9 @@ const loading = ref(false);
|
|||||||
const error = ref('');
|
const error = ref('');
|
||||||
const resultUrl = ref('');
|
const resultUrl = ref('');
|
||||||
const promptEn = ref(''); // 中文提示词自动转英文后的实际发送内容
|
const promptEn = ref(''); // 中文提示词自动转英文后的实际发送内容
|
||||||
|
const editorOpen = ref(false); // 图片编辑器(文字发光/旋转、图片叠加、拖角改大小)
|
||||||
|
// 编辑器导出保存成功 → 刷新右栏历史
|
||||||
|
function onEdited() { loadHistory(); }
|
||||||
|
|
||||||
// ---------- 自定义提供商(KEY 只存本机浏览器 localStorage) ----------
|
// ---------- 自定义提供商(KEY 只存本机浏览器 localStorage) ----------
|
||||||
const PROVIDER_KEY = 'it-tools-ai-provider';
|
const PROVIDER_KEY = 'it-tools-ai-provider';
|
||||||
@@ -101,9 +106,10 @@ function mergeModels() {
|
|||||||
const history = ref<{ id: string; at: number; model: string; prompt: string; img_url: string }[]>([]);
|
const history = ref<{ id: string; at: number; model: string; prompt: string; img_url: string }[]>([]);
|
||||||
async function loadHistory() {
|
async function loadHistory() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}`);
|
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=gen`, { headers: authHdr() });
|
||||||
const j = await res.json();
|
const j = await res.json();
|
||||||
if (j.code === 200 && Array.isArray(j.data)) history.value = j.data;
|
// 铁规则:所有功能历史最多显示 100 条
|
||||||
|
if (j.code === 200 && Array.isArray(j.data)) history.value = j.data.slice(0, 100);
|
||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
}
|
}
|
||||||
function openHist(it: any) {
|
function openHist(it: any) {
|
||||||
@@ -337,7 +343,7 @@ async function generate() {
|
|||||||
}
|
}
|
||||||
const res = await fetch('/relay/ai/gen-image', {
|
const res = await fetch('/relay/ai/gen-image', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen') },
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen'), ...authHdr() },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
});
|
});
|
||||||
const j = await res.json().catch(() => ({}));
|
const j = await res.json().catch(() => ({}));
|
||||||
@@ -477,6 +483,7 @@ async function generate() {
|
|||||||
<img :src="resultUrl" alt="生成结果">
|
<img :src="resultUrl" alt="生成结果">
|
||||||
<div class="gen-img-acts">
|
<div class="gen-img-acts">
|
||||||
<a class="gen-dl" :href="dlHref" target="_blank" rel="noopener" download>⬇ 下载图片</a>
|
<a class="gen-dl" :href="dlHref" target="_blank" rel="noopener" download>⬇ 下载图片</a>
|
||||||
|
<button class="gen-dl gen-edit" type="button" @click="editorOpen = true">✏️ 编辑图片</button>
|
||||||
<a class="gen-dl" :href="resultUrl" target="_blank" rel="noopener">🔗 新窗口打开</a>
|
<a class="gen-dl" :href="resultUrl" target="_blank" rel="noopener">🔗 新窗口打开</a>
|
||||||
<span v-if="promptEn" class="gen-tr" :title="promptEn">🌐 已自动转英文发送(悬停查看)</span>
|
<span v-if="promptEn" class="gen-tr" :title="promptEn">🌐 已自动转英文发送(悬停查看)</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -505,6 +512,15 @@ async function generate() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 图片编辑器:文字发光/旋转、自己的图片叠加、拖角改大小,导出原分辨率并落盘历史 -->
|
||||||
|
<ImgEditor
|
||||||
|
v-if="editorOpen && resultUrl"
|
||||||
|
:src="resultUrl"
|
||||||
|
:prompt="promptEn || prompt"
|
||||||
|
@close="editorOpen = false"
|
||||||
|
@saved="onEdited"
|
||||||
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped lang="less">
|
<style scoped lang="less">
|
||||||
@@ -1029,6 +1045,13 @@ async function generate() {
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.gen-edit {
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
font-family: inherit;
|
||||||
|
&:hover { background: rgba(14, 165, 160, 0.22); }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.gen-empty {
|
.gen-empty {
|
||||||
|
|||||||
@@ -0,0 +1,683 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||||
|
import { getMachineId, licenseHeaders } from '@/tools/license/license';
|
||||||
|
import { authHdr } from '@/tools/img-hist/img-hist';
|
||||||
|
|
||||||
|
// AI 生图结果编辑器:底图=生成图(锁定),叠加文字/图片图层
|
||||||
|
// 坐标系=底图原始像素,显示按 scale 缩放 → 导出即原图分辨率所见即所得
|
||||||
|
// 与海报编辑器的差异:拖右下角手柄直接改大小(文字改字号、图片等比),发光+旋转
|
||||||
|
const props = defineProps<{ src: string; prompt?: string }>();
|
||||||
|
const emit = defineEmits<{ close: []; saved: [url: string] }>();
|
||||||
|
|
||||||
|
const FONT_STACK = '"Microsoft YaHei", "PingFang SC", "Noto Sans SC", sans-serif';
|
||||||
|
type L = any; // 图层运行时对象(text / image 联合,编辑期动态增删)
|
||||||
|
|
||||||
|
const stageEl = ref<HTMLElement | null>(null);
|
||||||
|
const natW = ref(0);
|
||||||
|
const natH = ref(0);
|
||||||
|
const scale = ref(1);
|
||||||
|
const layers = ref<L[]>([]);
|
||||||
|
const selId = ref('');
|
||||||
|
const exporting = ref(false);
|
||||||
|
const edError = ref('');
|
||||||
|
const fileEl = ref<HTMLInputElement | null>(null);
|
||||||
|
let fileMode: 'add' | 'replace' = 'add';
|
||||||
|
let uid = 0;
|
||||||
|
let bgImg: HTMLImageElement | null = null;
|
||||||
|
const sel = computed(() => layers.value.find((l) => l.id === selId.value) || null);
|
||||||
|
|
||||||
|
// ---------- 底图加载 / 自适应缩放 ----------
|
||||||
|
function loadBg() {
|
||||||
|
const i = new Image();
|
||||||
|
i.onload = () => {
|
||||||
|
bgImg = i;
|
||||||
|
natW.value = i.naturalWidth;
|
||||||
|
natH.value = i.naturalHeight;
|
||||||
|
fit();
|
||||||
|
};
|
||||||
|
i.onerror = () => { edError.value = '底图加载失败'; };
|
||||||
|
i.src = props.src;
|
||||||
|
}
|
||||||
|
function fit() {
|
||||||
|
const el = stageEl.value;
|
||||||
|
if (!el || !natW.value) return;
|
||||||
|
const w = Math.max(el.clientWidth - 24, 120);
|
||||||
|
const h = Math.max(el.clientHeight - 24, 120);
|
||||||
|
scale.value = Math.max(Math.min(w / natW.value, h / natH.value), 0.05);
|
||||||
|
}
|
||||||
|
const handleStyle = computed(() => {
|
||||||
|
const s = scale.value || 1;
|
||||||
|
const sz = Math.max(14 / s, 10);
|
||||||
|
return { width: sz + 'px', height: sz + 'px', right: -sz / 2 + 'px', bottom: -sz / 2 + 'px', borderWidth: Math.max(2 / s, 1.5) + 'px' };
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- 文字排版(预览与导出共用,保证换行一致) ----------
|
||||||
|
const mc = document.createElement('canvas');
|
||||||
|
const mctx = mc.getContext('2d')!;
|
||||||
|
const wrapCache = new Map<string, string[]>();
|
||||||
|
const CLOSE_PUNCT = ',。、!?:;)】」』,.!?;:)';
|
||||||
|
|
||||||
|
function fontStr(l: L) { return `${l.weight ?? 700} ${l.size}px ${FONT_STACK}`; }
|
||||||
|
function linesOf(l: L): string[] {
|
||||||
|
const key = `${l.text}|${l.w}|${fontStr(l)}`;
|
||||||
|
const hit = wrapCache.get(key);
|
||||||
|
if (hit) return hit;
|
||||||
|
mctx.font = fontStr(l);
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const para of String(l.text ?? '').split('\n')) {
|
||||||
|
if (!para) { out.push(''); continue; }
|
||||||
|
let line = '';
|
||||||
|
for (const ch of para) {
|
||||||
|
const test = line + ch;
|
||||||
|
if (line && mctx.measureText(test).width > l.w && !CLOSE_PUNCT.includes(ch)) {
|
||||||
|
out.push(line); line = ch;
|
||||||
|
} else line = test;
|
||||||
|
}
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
const res = out.length ? out : [''];
|
||||||
|
wrapCache.set(key, res);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
const maxFontSize = computed(() => Math.max(80, Math.round((natW.value || 1024) * 0.25)));
|
||||||
|
|
||||||
|
// ---------- 样式 ----------
|
||||||
|
function boxStyle(l: L) {
|
||||||
|
return {
|
||||||
|
left: l.x + 'px', top: l.y + 'px', width: l.w + 'px',
|
||||||
|
height: l.type === 'text' ? 'auto' : l.h + 'px',
|
||||||
|
transform: l.rot ? `rotate(${l.rot}deg)` : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function fontStyle(l: L) {
|
||||||
|
return {
|
||||||
|
fontFamily: FONT_STACK,
|
||||||
|
fontSize: l.size + 'px',
|
||||||
|
fontWeight: String(l.weight ?? 700),
|
||||||
|
color: l.color,
|
||||||
|
textAlign: 'center' as const,
|
||||||
|
lineHeight: l.size * (l.lineHeight ?? 1.25) + 'px',
|
||||||
|
textShadow: l.glow ? `0 0 ${l.glowBlur ?? 14}px ${l.glowColor ?? '#000000'}` : 'none',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 选中 / 拖动移动 ----------
|
||||||
|
let drag: { l: L; sx: number; sy: number; lx: number; ly: number } | null = null;
|
||||||
|
function onDown(e: PointerEvent, l: L) {
|
||||||
|
selId.value = l.id;
|
||||||
|
drag = { l, sx: e.clientX, sy: e.clientY, lx: l.x, ly: l.y };
|
||||||
|
window.addEventListener('pointermove', onMove);
|
||||||
|
window.addEventListener('pointerup', onUp);
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
function onMove(e: PointerEvent) {
|
||||||
|
if (!drag) return;
|
||||||
|
const s = scale.value || 1;
|
||||||
|
const l = drag.l;
|
||||||
|
const nx = drag.lx + (e.clientX - drag.sx) / s;
|
||||||
|
const ny = drag.ly + (e.clientY - drag.sy) / s;
|
||||||
|
const estH = l.type === 'text' ? linesOf(l).length * l.size * (l.lineHeight ?? 1.25) : l.h;
|
||||||
|
l.x = Math.min(Math.max(nx, 0), Math.max(natW.value - l.w, 0));
|
||||||
|
l.y = Math.min(Math.max(ny, 0), Math.max(natH.value - estH, 0));
|
||||||
|
}
|
||||||
|
function onUp() {
|
||||||
|
drag = null;
|
||||||
|
window.removeEventListener('pointermove', onMove);
|
||||||
|
window.removeEventListener('pointerup', onUp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 拖右下角手柄改大小(位移旋转到图层局部轴,旋转后拖拽方向依然正确) ----------
|
||||||
|
let rz: { l: L; sx: number; sy: number; w0: number; h0: number; size0: number; rot: number } | null = null;
|
||||||
|
function onRzDown(e: PointerEvent, l: L) {
|
||||||
|
selId.value = l.id;
|
||||||
|
rz = { l, sx: e.clientX, sy: e.clientY, w0: l.w, h0: l.h ?? 0, size0: l.size ?? 48, rot: l.rot ?? 0 };
|
||||||
|
window.addEventListener('pointermove', onRzMove);
|
||||||
|
window.addEventListener('pointerup', onRzUp);
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
}
|
||||||
|
function onRzMove(e: PointerEvent) {
|
||||||
|
if (!rz) return;
|
||||||
|
const s = scale.value || 1;
|
||||||
|
const dx = (e.clientX - rz.sx) / s;
|
||||||
|
const dy = (e.clientY - rz.sy) / s;
|
||||||
|
const rad = (-rz.rot * Math.PI) / 180;
|
||||||
|
const ldx = dx * Math.cos(rad) - dy * Math.sin(rad);
|
||||||
|
const ldy = dx * Math.sin(rad) + dy * Math.cos(rad);
|
||||||
|
const l = rz.l;
|
||||||
|
if (l.type === 'image') {
|
||||||
|
// 拖横向/纵向取位移大的轴驱动,等比缩放(以左上角为锚)
|
||||||
|
const delta = Math.abs(ldx) >= Math.abs(ldy) ? ldx : ldy;
|
||||||
|
const nw = Math.max(24, rz.w0 + delta);
|
||||||
|
const ratio = nw / rz.w0;
|
||||||
|
l.w = nw;
|
||||||
|
l.h = Math.max(24, rz.h0 * ratio);
|
||||||
|
} else {
|
||||||
|
// 文字:水平拖动改字号,换行宽度同步缩放保持排版比例
|
||||||
|
const ns = Math.min(Math.max(rz.size0 + ldx, 8), maxFontSize.value);
|
||||||
|
const ratio = ns / Math.max(1, rz.size0);
|
||||||
|
l.size = Math.round(ns);
|
||||||
|
l.w = Math.max(40, Math.round(rz.w0 * ratio));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onRzUp() {
|
||||||
|
rz = null;
|
||||||
|
window.removeEventListener('pointermove', onRzMove);
|
||||||
|
window.removeEventListener('pointerup', onRzUp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 图层增删 ----------
|
||||||
|
function addText() {
|
||||||
|
const w = Math.round(natW.value * 0.8);
|
||||||
|
const l = {
|
||||||
|
id: 'l' + ++uid, type: 'text', text: '双击右侧修改文字',
|
||||||
|
x: Math.round((natW.value - w) / 2), y: Math.round(natH.value * 0.42), w,
|
||||||
|
size: Math.round(natW.value * 0.07) || 64, color: '#ffffff', weight: 700, lineHeight: 1.25,
|
||||||
|
glow: true, glowColor: '#000000', glowBlur: 14, rot: 0,
|
||||||
|
};
|
||||||
|
layers.value.push(l);
|
||||||
|
selId.value = l.id;
|
||||||
|
}
|
||||||
|
function pickImage() { fileMode = 'add'; fileEl.value?.click(); }
|
||||||
|
function replaceImage() { fileMode = 'replace'; fileEl.value?.click(); }
|
||||||
|
function onFile(e: Event) {
|
||||||
|
const f = (e.target as HTMLInputElement).files?.[0];
|
||||||
|
const input = e.target as HTMLInputElement;
|
||||||
|
input.value = '';
|
||||||
|
if (!f) return;
|
||||||
|
const url = URL.createObjectURL(f);
|
||||||
|
const probe = new Image();
|
||||||
|
probe.onload = () => {
|
||||||
|
if (fileMode === 'replace') {
|
||||||
|
const l = sel.value;
|
||||||
|
if (l && l.type === 'image') l.src = url;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const w = Math.round(natW.value * 0.4) || 400;
|
||||||
|
const h = Math.round((w * probe.naturalHeight) / Math.max(1, probe.naturalWidth));
|
||||||
|
const l = {
|
||||||
|
id: 'l' + ++uid, type: 'image', src: url,
|
||||||
|
x: Math.round((natW.value - w) / 2), y: Math.round((natH.value - h) / 2),
|
||||||
|
w, h, rot: 0,
|
||||||
|
};
|
||||||
|
layers.value.push(l);
|
||||||
|
selId.value = l.id;
|
||||||
|
};
|
||||||
|
probe.src = url;
|
||||||
|
}
|
||||||
|
function delSel() {
|
||||||
|
const i = layers.value.findIndex((l) => l.id === selId.value);
|
||||||
|
if (i >= 0) layers.value.splice(i, 1);
|
||||||
|
selId.value = '';
|
||||||
|
}
|
||||||
|
function moveLayer(dz: number) {
|
||||||
|
const i = layers.value.findIndex((l) => l.id === selId.value);
|
||||||
|
const j = i + dz;
|
||||||
|
if (i < 0 || j < 0 || j >= layers.value.length) return;
|
||||||
|
const [l] = layers.value.splice(i, 1);
|
||||||
|
layers.value.splice(j, 0, l);
|
||||||
|
}
|
||||||
|
const selName = computed(() => {
|
||||||
|
const l = sel.value;
|
||||||
|
if (!l) return '';
|
||||||
|
return l.type === 'text' ? String(l.text || '文字').slice(0, 12) : '图片';
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- 导出原分辨率 PNG:下载 + 落盘历史(失败不阻断下载) ----------
|
||||||
|
function loadImg(src: string): Promise<HTMLImageElement | null> {
|
||||||
|
return new Promise((res) => {
|
||||||
|
const i = new Image();
|
||||||
|
i.onload = () => res(i);
|
||||||
|
i.onerror = () => res(null);
|
||||||
|
i.src = src;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function rotAround(ctx: CanvasRenderingContext2D, cx: number, cy: number, deg: number) {
|
||||||
|
ctx.translate(cx, cy);
|
||||||
|
ctx.rotate((deg * Math.PI) / 180);
|
||||||
|
ctx.translate(-cx, -cy);
|
||||||
|
}
|
||||||
|
async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
|
||||||
|
if (l.type === 'image') {
|
||||||
|
const img = l.src ? await loadImg(l.src) : null;
|
||||||
|
if (!img || !img.naturalWidth) return;
|
||||||
|
ctx.save();
|
||||||
|
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
|
||||||
|
ctx.drawImage(img, l.x, l.y, l.w, l.h);
|
||||||
|
ctx.restore();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 文字
|
||||||
|
ctx.font = fontStr(l);
|
||||||
|
ctx.fillStyle = l.color;
|
||||||
|
const lh = l.size * (l.lineHeight ?? 1.25);
|
||||||
|
const m = ctx.measureText('字');
|
||||||
|
const asc = (m as any).fontBoundingBoxAscent ?? l.size * 0.8;
|
||||||
|
const desc = (m as any).fontBoundingBoxDescent ?? l.size * 0.2;
|
||||||
|
const lines = linesOf(l);
|
||||||
|
ctx.save();
|
||||||
|
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + (lines.length * lh) / 2, l.rot);
|
||||||
|
ctx.textAlign = 'center';
|
||||||
|
const tx = l.x + l.w / 2;
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const y = l.y + i * lh + (lh - (asc + desc)) / 2 + asc;
|
||||||
|
if (l.glow) {
|
||||||
|
ctx.shadowColor = l.glowColor ?? '#000000';
|
||||||
|
ctx.shadowBlur = l.glowBlur ?? 14;
|
||||||
|
ctx.shadowOffsetX = 0;
|
||||||
|
ctx.shadowOffsetY = 0;
|
||||||
|
} else {
|
||||||
|
ctx.shadowColor = 'transparent';
|
||||||
|
ctx.shadowBlur = 0;
|
||||||
|
}
|
||||||
|
ctx.fillText(lines[i], tx, y);
|
||||||
|
}
|
||||||
|
ctx.restore();
|
||||||
|
}
|
||||||
|
async function exportPng() {
|
||||||
|
if (!natW.value || !bgImg) return;
|
||||||
|
exporting.value = true;
|
||||||
|
edError.value = '';
|
||||||
|
try {
|
||||||
|
const c = document.createElement('canvas');
|
||||||
|
c.width = natW.value;
|
||||||
|
c.height = natH.value;
|
||||||
|
const ctx = c.getContext('2d')!;
|
||||||
|
ctx.drawImage(bgImg, 0, 0, natW.value, natH.value);
|
||||||
|
for (const l of layers.value) await drawLayer(ctx, l);
|
||||||
|
const blob: Blob | null = await new Promise((res) => c.toBlob(res, 'image/png'));
|
||||||
|
if (!blob) throw new Error('画布导出失败');
|
||||||
|
// 1) 先落盘历史(kind=gen → 出现在本工具右栏),拿站内图链;失败不阻断下载
|
||||||
|
let savedUrl = '';
|
||||||
|
try {
|
||||||
|
const b64 = await new Promise<string>((res, rej) => {
|
||||||
|
const fr = new FileReader();
|
||||||
|
fr.onload = () => res(String(fr.result || ''));
|
||||||
|
fr.onerror = () => rej(new Error('读取失败'));
|
||||||
|
fr.readAsDataURL(blob);
|
||||||
|
});
|
||||||
|
const res = await fetch('/relay/ai/img-save', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders('ai-gen'), ...authHdr() },
|
||||||
|
body: JSON.stringify({
|
||||||
|
machine: getMachineId(), b64, tool: 'ai-gen', kind: 'gen',
|
||||||
|
model: 'AI生图', prompt: String(props.prompt || '').slice(0, 200) || '图片编辑导出',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const j = await res.json().catch(() => ({}) as any);
|
||||||
|
if (res.ok && j.code === 200) {
|
||||||
|
savedUrl = String(j.data?.img_url || '');
|
||||||
|
emit('saved', savedUrl);
|
||||||
|
}
|
||||||
|
} catch { /* 保存失败不阻断下载 */ }
|
||||||
|
// 2) 下载:优先站内图链(服务端 Content-Disposition 双保险文件名,不依赖浏览器 download 属性),
|
||||||
|
// 保存失败时回退 blob 本地下载
|
||||||
|
const NAME = 'AI生图-编辑.png';
|
||||||
|
const a = document.createElement('a');
|
||||||
|
if (savedUrl) {
|
||||||
|
a.href = savedUrl + '?dl=1&name=' + encodeURIComponent(NAME);
|
||||||
|
} else {
|
||||||
|
a.href = URL.createObjectURL(blob);
|
||||||
|
setTimeout(() => URL.revokeObjectURL(a.href), 8000);
|
||||||
|
}
|
||||||
|
a.download = NAME;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = String(err?.message || err);
|
||||||
|
edError.value = msg.includes('SecurityError') || msg.includes('tainted')
|
||||||
|
? '该图片来自外链,浏览器禁止导出(跨域)。请先下载图片,再用「+图片」上传后编辑'
|
||||||
|
: '导出失败:' + msg;
|
||||||
|
} finally {
|
||||||
|
exporting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKey(e: KeyboardEvent) {
|
||||||
|
if (e.key === 'Escape') emit('close');
|
||||||
|
const t = e.target as HTMLElement | null;
|
||||||
|
const typing = !!t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA');
|
||||||
|
if (!typing && (e.key === 'Delete' || e.key === 'Backspace') && selId.value) {
|
||||||
|
e.preventDefault();
|
||||||
|
delSel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ro: ResizeObserver | null = null;
|
||||||
|
onMounted(() => {
|
||||||
|
loadBg();
|
||||||
|
window.addEventListener('keydown', onKey);
|
||||||
|
window.addEventListener('resize', fit);
|
||||||
|
ro = new ResizeObserver(fit);
|
||||||
|
if (stageEl.value) ro.observe(stageEl.value);
|
||||||
|
});
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
ro?.disconnect();
|
||||||
|
window.removeEventListener('keydown', onKey);
|
||||||
|
window.removeEventListener('resize', fit);
|
||||||
|
onUp();
|
||||||
|
onRzUp();
|
||||||
|
layers.value.forEach((l) => { if (l.type === 'image' && l.src?.startsWith('blob:')) URL.revokeObjectURL(l.src); });
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="ed-root">
|
||||||
|
<div class="ed-top">
|
||||||
|
<span class="ed-title">✏️ 编辑图片</span>
|
||||||
|
<span class="ed-hint">拖动图层移动 · 拖右下角圆点改大小 · Delete 删除 · Esc 关闭</span>
|
||||||
|
<div class="ed-acts">
|
||||||
|
<button class="ed-btn" @click="addText">+ 文字</button>
|
||||||
|
<button class="ed-btn" @click="pickImage">+ 图片</button>
|
||||||
|
<button class="ed-btn primary" :disabled="exporting" @click="exportPng">
|
||||||
|
{{ exporting ? '导出中…' : '⬇ 导出 PNG' }}
|
||||||
|
</button>
|
||||||
|
<button class="ed-btn ghost" @click="emit('close')">✕ 关闭</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="edError" class="ed-error">⚠️ {{ edError }}</div>
|
||||||
|
|
||||||
|
<div class="ed-main">
|
||||||
|
<section ref="stageEl" class="ed-stage" @click.self="selId = ''">
|
||||||
|
<div
|
||||||
|
v-if="natW"
|
||||||
|
class="ed-frame"
|
||||||
|
:style="{ width: natW * scale + 'px', height: natH * scale + 'px' }"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="ed-canvas"
|
||||||
|
:style="{ width: natW + 'px', height: natH + 'px', transform: `scale(${scale})` }"
|
||||||
|
@click.self="selId = ''"
|
||||||
|
>
|
||||||
|
<img class="ed-bg" :src="src" alt="" draggable="false">
|
||||||
|
<div
|
||||||
|
v-for="l in layers"
|
||||||
|
:key="l.id"
|
||||||
|
class="ed-layer"
|
||||||
|
:class="{ sel: selId === l.id }"
|
||||||
|
:style="boxStyle(l)"
|
||||||
|
@pointerdown.stop="onDown($event, l)"
|
||||||
|
>
|
||||||
|
<div v-if="l.type === 'text'" :style="fontStyle(l)">
|
||||||
|
<div v-for="(ln, i) in linesOf(l)" :key="i">{{ ln || '\u00a0' }}</div>
|
||||||
|
</div>
|
||||||
|
<img v-else-if="l.src" class="ed-img" :src="l.src" alt="" draggable="false">
|
||||||
|
<i
|
||||||
|
v-if="selId === l.id"
|
||||||
|
class="ed-rh"
|
||||||
|
:style="handleStyle"
|
||||||
|
@pointerdown.stop="onRzDown($event, l)"
|
||||||
|
></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="ed-empty"><n-spin size="large" /><p>底图加载中…</p></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<aside class="ed-panel">
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">图层(上层在前)</div>
|
||||||
|
<div v-if="!layers.length" class="ed-tip">点上方「+ 文字」「+ 图片」开始编辑,文字可发光、可旋转,拖右下角圆点改大小</div>
|
||||||
|
<div
|
||||||
|
v-for="l in [...layers].reverse()"
|
||||||
|
:key="l.id"
|
||||||
|
class="ed-li"
|
||||||
|
:class="{ on: selId === l.id }"
|
||||||
|
@click="selId = l.id"
|
||||||
|
>
|
||||||
|
<span class="ed-li-ico">{{ l.type === 'text' ? 'T' : '🖼' }}</span>
|
||||||
|
<span class="ed-li-name">{{ l.type === 'text' ? String(l.text || '文字').slice(0, 10) : '图片' }}</span>
|
||||||
|
<span class="ed-li-ops">
|
||||||
|
<button title="上移" @click.stop="selId = l.id; moveLayer(1)">▲</button>
|
||||||
|
<button title="下移" @click.stop="selId = l.id; moveLayer(-1)">▼</button>
|
||||||
|
<button title="删除" @click.stop="selId = l.id; delSel()">✕</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="sel && sel.type === 'text'">
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">文字「{{ selName }}」</div>
|
||||||
|
<textarea v-model="sel.text" class="ed-textarea" rows="3" placeholder="输入文字内容"></textarea>
|
||||||
|
<label class="ed-row">
|
||||||
|
<span>字号</span>
|
||||||
|
<input v-model.number="sel.size" type="range" min="8" :max="maxFontSize">
|
||||||
|
<em>{{ sel.size }}</em>
|
||||||
|
</label>
|
||||||
|
<label class="ed-row">
|
||||||
|
<span>颜色</span>
|
||||||
|
<input v-model="sel.color" type="color" class="ed-color">
|
||||||
|
<span class="ed-flex"></span>
|
||||||
|
<span>旋转</span>
|
||||||
|
<input v-model.number="sel.rot" type="range" min="-180" max="180">
|
||||||
|
<em>{{ sel.rot ?? 0 }}°</em>
|
||||||
|
<button class="ed-mini" @click="sel.rot = 0">复位</button>
|
||||||
|
</label>
|
||||||
|
<label class="ed-row">
|
||||||
|
<span>发光</span>
|
||||||
|
<input v-model="sel.glow" type="checkbox">
|
||||||
|
<input v-if="sel.glow" v-model="sel.glowColor" type="color" class="ed-color">
|
||||||
|
<template v-if="sel.glow">
|
||||||
|
<span>强度</span>
|
||||||
|
<input v-model.number="sel.glowBlur" type="range" min="2" max="60">
|
||||||
|
<em>{{ sel.glowBlur ?? 14 }}</em>
|
||||||
|
</template>
|
||||||
|
</label>
|
||||||
|
<div class="ed-tip">拖右下角圆点直接改字号;发光为文字外光晕,颜色强度可调</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-if="sel && sel.type === 'image'">
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">图片</div>
|
||||||
|
<label class="ed-row">
|
||||||
|
<span>旋转</span>
|
||||||
|
<input v-model.number="sel.rot" type="range" min="-180" max="180">
|
||||||
|
<em>{{ sel.rot ?? 0 }}°</em>
|
||||||
|
<button class="ed-mini" @click="sel.rot = 0">复位</button>
|
||||||
|
</label>
|
||||||
|
<button class="ed-btn wide" @click="replaceImage">替换图片</button>
|
||||||
|
<div class="ed-tip">拖右下角圆点等比改大小;拖动图层移动位置</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="ed-sec">
|
||||||
|
<div class="ed-sec-title">说明</div>
|
||||||
|
<div class="ed-tip">导出为底图原始分辨率 PNG,同时保存到右侧历史(按你的账号隔离)。底图本身锁定不可删。</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input ref="fileEl" type="file" accept="image/*" class="ed-hidden" @change="onFile">
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped lang="less">
|
||||||
|
.ed-root {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 5000;
|
||||||
|
background: rgba(14, 16, 18, 0.97);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
color: #e8e8e8;
|
||||||
|
}
|
||||||
|
.ed-top {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 12px 18px;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
flex-shrink: 0;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.ed-title { font-size: 16px; font-weight: 700; }
|
||||||
|
.ed-hint { font-size: 12px; opacity: 0.55; flex: 1; min-width: 160px; }
|
||||||
|
.ed-acts { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.ed-btn {
|
||||||
|
padding: 8px 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.18);
|
||||||
|
background: rgba(255, 255, 255, 0.08);
|
||||||
|
color: #e8e8e8;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
&:hover { background: rgba(255, 255, 255, 0.16); }
|
||||||
|
&:disabled { opacity: 0.55; cursor: wait; }
|
||||||
|
&.primary { background: #0ea5a0; border-color: #0ea5a0; color: #fff; }
|
||||||
|
&.primary:hover { background: #0c8f8a; }
|
||||||
|
&.ghost { background: transparent; }
|
||||||
|
&.wide { width: 100%; margin-top: 6px; }
|
||||||
|
}
|
||||||
|
.ed-error {
|
||||||
|
padding: 8px 18px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #ffb4a2;
|
||||||
|
background: rgba(255, 120, 100, 0.1);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.ed-main { flex: 1; min-height: 0; display: flex; }
|
||||||
|
|
||||||
|
.ed-stage {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
overflow: hidden;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
.ed-empty { text-align: center; opacity: 0.6; font-size: 13.5px; p { margin-top: 12px; } }
|
||||||
|
.ed-frame {
|
||||||
|
position: relative;
|
||||||
|
flex-shrink: 0;
|
||||||
|
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
|
||||||
|
border-radius: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.ed-canvas { position: absolute; left: 0; top: 0; transform-origin: 0 0; overflow: hidden; }
|
||||||
|
.ed-bg {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: fill;
|
||||||
|
pointer-events: none;
|
||||||
|
user-select: none;
|
||||||
|
-webkit-user-drag: none;
|
||||||
|
}
|
||||||
|
.ed-layer {
|
||||||
|
position: absolute;
|
||||||
|
box-sizing: border-box;
|
||||||
|
user-select: none;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
touch-action: none;
|
||||||
|
cursor: move;
|
||||||
|
}
|
||||||
|
.ed-layer.sel { outline: 3px dashed #38bdf8; outline-offset: 2px; }
|
||||||
|
.ed-img { width: 100%; height: 100%; object-fit: fill; display: block; pointer-events: none; }
|
||||||
|
.ed-rh {
|
||||||
|
position: absolute;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background: #38bdf8;
|
||||||
|
border: 2px solid #fff;
|
||||||
|
border-radius: 50%;
|
||||||
|
cursor: nwse-resize;
|
||||||
|
z-index: 5;
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ed-panel {
|
||||||
|
width: 320px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
min-height: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
border-left: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
padding: 14px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
.ed-sec { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.ed-sec-title { font-size: 13px; font-weight: 700; opacity: 0.85; }
|
||||||
|
.ed-tip { font-size: 12.5px; opacity: 0.6; line-height: 1.7; }
|
||||||
|
.ed-li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 13px;
|
||||||
|
background: rgba(255, 255, 255, 0.06);
|
||||||
|
&:hover { background: rgba(255, 255, 255, 0.1); }
|
||||||
|
&.on { border-color: #38bdf8; background: rgba(56, 189, 248, 0.14); }
|
||||||
|
}
|
||||||
|
.ed-li-ico { width: 18px; text-align: center; opacity: 0.8; }
|
||||||
|
.ed-li-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.ed-li-ops { display: inline-flex; gap: 2px; }
|
||||||
|
.ed-li-ops button {
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
color: inherit;
|
||||||
|
padding: 2px 5px;
|
||||||
|
font-size: 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
&:hover { background: rgba(255, 255, 255, 0.16); }
|
||||||
|
}
|
||||||
|
.ed-textarea {
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
resize: vertical;
|
||||||
|
min-height: 64px;
|
||||||
|
background: rgba(255, 255, 255, 0.07);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.16);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: inherit;
|
||||||
|
padding: 8px 10px;
|
||||||
|
font-size: 13.5px;
|
||||||
|
font-family: inherit;
|
||||||
|
&:focus { outline: none; border-color: #38bdf8; }
|
||||||
|
}
|
||||||
|
.ed-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
opacity: 0.92;
|
||||||
|
input[type='range'] { flex: 1; min-width: 60px; accent-color: #38bdf8; }
|
||||||
|
input[type='checkbox'] { accent-color: #38bdf8; width: 16px; height: 16px; }
|
||||||
|
em { font-style: normal; min-width: 40px; text-align: right; opacity: 0.75; font-size: 12.5px; }
|
||||||
|
}
|
||||||
|
.ed-flex { flex: 1; }
|
||||||
|
.ed-color {
|
||||||
|
width: 42px;
|
||||||
|
height: 26px;
|
||||||
|
padding: 0;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.ed-mini {
|
||||||
|
padding: 3px 8px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
|
background: rgba(255, 255, 255, 0.08);
|
||||||
|
color: inherit;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
&:hover { background: rgba(255, 255, 255, 0.16); }
|
||||||
|
}
|
||||||
|
.ed-hidden { display: none; }
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.ed-main { flex-direction: column; overflow-y: auto; }
|
||||||
|
.ed-stage { flex: none; height: 48vh; }
|
||||||
|
.ed-panel { width: 100%; border-left: none; border-top: 1px solid rgba(255, 255, 255, 0.1); overflow: visible; }
|
||||||
|
.ed-hint { display: none; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -2,11 +2,22 @@
|
|||||||
import { onMounted, ref } from 'vue';
|
import { onMounted, ref } from 'vue';
|
||||||
import { useHead } from '@vueuse/head';
|
import { useHead } from '@vueuse/head';
|
||||||
import { licenseHeaders } from '@/tools/license/license';
|
import { licenseHeaders } from '@/tools/license/license';
|
||||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
import ImgHist from '@/tools/img-hist/ImgHist.vue';
|
||||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
import { blobToB64, dataUrlToB64, saveImgHist } from '@/tools/img-hist/img-hist';
|
||||||
|
|
||||||
useHead({ title: 'AI 图片实验室 - IT-TOOLS-PRO' });
|
useHead({ title: 'AI 图片实验室 - IT-TOOLS-PRO' });
|
||||||
const genHist = useGenHistory('ai-image-lab');
|
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
|
||||||
|
|
||||||
|
/** 处理结果保存到服务器历史(失败静默,不影响下载) */
|
||||||
|
async function saveLab(model: string, prompt: string, src: Blob | string) {
|
||||||
|
try {
|
||||||
|
const b64 = typeof src === 'string' ? dataUrlToB64(src) : await blobToB64(src);
|
||||||
|
if (!b64) return;
|
||||||
|
const ok = await saveImgHist({ kind: 'ai-image-lab', tool: 'ai-image-tools', b64, model, prompt });
|
||||||
|
if (ok) histRef.value?.reload();
|
||||||
|
}
|
||||||
|
catch { /* 静默 */ }
|
||||||
|
}
|
||||||
|
|
||||||
type TabKey = 'matting' | 'upscale' | 'idphoto';
|
type TabKey = 'matting' | 'upscale' | 'idphoto';
|
||||||
const tab = ref<TabKey>('matting');
|
const tab = ref<TabKey>('matting');
|
||||||
@@ -83,7 +94,7 @@ async function doMatting() {
|
|||||||
}
|
}
|
||||||
outUrl.value = URL.createObjectURL(blob);
|
outUrl.value = URL.createObjectURL(blob);
|
||||||
outBlob.value = blob;
|
outBlob.value = blob;
|
||||||
genHist.add({ title: `AI 抠图: ${curFile.value.name}`, detail: `${(blob.size / 1024).toFixed(0)}KB` });
|
saveLab('AI抠图', curFile.value?.name || '', blob);
|
||||||
}
|
}
|
||||||
catch (e: any) {
|
catch (e: any) {
|
||||||
error.value = String(e?.message || e);
|
error.value = String(e?.message || e);
|
||||||
@@ -156,7 +167,7 @@ async function doUpscale() {
|
|||||||
await new Promise<void>((r) => {
|
await new Promise<void>((r) => {
|
||||||
img.onload = () => r();
|
img.onload = () => r();
|
||||||
});
|
});
|
||||||
genHist.add({ title: `AI 放大 ${upScale.value}x: ${curFile.value.name}`, detail: `${img.naturalWidth}×${img.naturalHeight} · ${(blob.size / 1024).toFixed(0)}KB` });
|
saveLab(`AI放大${upScale.value}x`, curFile.value?.name || '', blob);
|
||||||
}
|
}
|
||||||
catch (e: any) {
|
catch (e: any) {
|
||||||
error.value = String(e?.message || e);
|
error.value = String(e?.message || e);
|
||||||
@@ -211,7 +222,7 @@ async function makeIdPhoto() {
|
|||||||
URL.revokeObjectURL(idResult.value);
|
URL.revokeObjectURL(idResult.value);
|
||||||
}
|
}
|
||||||
idResult.value = c.toDataURL('image/png');
|
idResult.value = c.toDataURL('image/png');
|
||||||
genHist.add({ title: `证件照: ${spec.name} ${idBg.value === 'white' ? '白底' : idBg.value === 'red' ? '红底' : '蓝底'}`, detail: `${spec.w}×${spec.h}` });
|
saveLab('证件照', `${spec.name} ${idBg.value === 'white' ? '白底' : idBg.value === 'red' ? '红底' : '蓝底'}`, idResult.value || '');
|
||||||
}
|
}
|
||||||
|
|
||||||
function downloadUrl(url: string, name: string) {
|
function downloadUrl(url: string, name: string) {
|
||||||
@@ -221,6 +232,18 @@ function downloadUrl(url: string, name: string) {
|
|||||||
a.click();
|
a.click();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 下载处理结果:抠图换底后下载合成图并在换底时落盘(透明原图由 doMatting 生成时已存,不重复) */
|
||||||
|
function dlResult() {
|
||||||
|
if (tab.value === 'matting') {
|
||||||
|
const composited = bgMode.value !== 'transparent' && !!compositeUrl.value;
|
||||||
|
const url = composited ? compositeUrl.value : outUrl.value;
|
||||||
|
if (composited) saveLab('抠图换底', `${bgMode.value}底`, url);
|
||||||
|
downloadUrl(url, '抠图.png');
|
||||||
|
} else {
|
||||||
|
downloadUrl(outUrl.value, `放大${upScale.value}x.${(curFile.value?.name || '').split('.').pop() || 'jpg'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function switchTab(k: TabKey) {
|
function switchTab(k: TabKey) {
|
||||||
tab.value = k;
|
tab.value = k;
|
||||||
error.value = '';
|
error.value = '';
|
||||||
@@ -320,7 +343,7 @@ onMounted(() => {});
|
|||||||
<div class="al-sec">
|
<div class="al-sec">
|
||||||
{{ tab === 'idphoto' ? '证件照预览' : outUrl ? '处理结果' : '原图预览' }}
|
{{ tab === 'idphoto' ? '证件照预览' : outUrl ? '处理结果' : '原图预览' }}
|
||||||
<button v-if="tab === 'idphoto' && idResult" class="al-dl" @click="downloadUrl(idResult, '证件照.png')">⬇ 下载证件照</button>
|
<button v-if="tab === 'idphoto' && idResult" class="al-dl" @click="downloadUrl(idResult, '证件照.png')">⬇ 下载证件照</button>
|
||||||
<button v-else-if="outUrl && tab !== 'idphoto'" class="al-dl" @click="downloadUrl(outUrl, tab === 'matting' ? '抠图.png' : `放大${upScale}x.${(curFile?.name || '').split('.').pop() || 'jpg'}`)">⬇ 下载结果</button>
|
<button v-else-if="outUrl && tab !== 'idphoto'" class="al-dl" @click="dlResult">⬇ 下载结果</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="al-preview">
|
<div class="al-preview">
|
||||||
<img v-if="tab === 'idphoto' && idResult" :src="idResult" class="al-img al-img-id" alt="id photo">
|
<img v-if="tab === 'idphoto' && idResult" :src="idResult" class="al-img al-img-id" alt="id photo">
|
||||||
@@ -328,8 +351,8 @@ onMounted(() => {});
|
|||||||
<img v-else-if="srcUrl" :src="srcUrl" class="al-img" alt="source">
|
<img v-else-if="srcUrl" :src="srcUrl" class="al-img" alt="source">
|
||||||
<div v-else class="al-empty">上传图片后在这里预览</div>
|
<div v-else class="al-empty">上传图片后在这里预览</div>
|
||||||
</div>
|
</div>
|
||||||
<GenHistory tool="ai-image-lab" label="AI 图片记录" class="mt-10px" />
|
|
||||||
</div>
|
</div>
|
||||||
|
<ImgHist ref="histRef" kind="ai-image-lab" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useUserAuth } from '@/composable/user-auth';
|
import { useUserAuth } from '@/composable/user-auth';
|
||||||
import { licenseHeaders } from '../license/license';
|
import { licenseHeaders } from '../license/license';
|
||||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
import ImgHist from '@/tools/img-hist/ImgHist.vue';
|
||||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
import { blobToB64, saveImgHist } from '@/tools/img-hist/img-hist';
|
||||||
|
|
||||||
const genHist = useGenHistory('ai-retouch');
|
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
|
||||||
|
|
||||||
|
/** 修图结果保存到服务器历史(失败静默,不影响下载) */
|
||||||
|
async function saveRetouch(blob: Blob) {
|
||||||
|
try {
|
||||||
|
const b64 = await blobToB64(blob);
|
||||||
|
if (!b64) return;
|
||||||
|
const ok = await saveImgHist({ kind: 'ai-retouch', tool: 'ai-retouch', b64, model: tab.value.label, prompt: fileName.value || '' });
|
||||||
|
if (ok) histRef.value?.reload();
|
||||||
|
}
|
||||||
|
catch { /* 静默 */ }
|
||||||
|
}
|
||||||
|
|
||||||
interface TabDef {
|
interface TabDef {
|
||||||
key: string;
|
key: string;
|
||||||
@@ -211,6 +222,7 @@ async function submit() {
|
|||||||
}
|
}
|
||||||
const blob = await res.blob();
|
const blob = await res.blob();
|
||||||
resultUrl.value = URL.createObjectURL(blob);
|
resultUrl.value = URL.createObjectURL(blob);
|
||||||
|
saveRetouch(blob);
|
||||||
if (tab.value.key === 'inpaint') clearMask();
|
if (tab.value.key === 'inpaint') clearMask();
|
||||||
}
|
}
|
||||||
catch (e: any) {
|
catch (e: any) {
|
||||||
@@ -219,12 +231,7 @@ async function submit() {
|
|||||||
finally {
|
finally {
|
||||||
elapsed.value = Math.round(performance.now() - start);
|
elapsed.value = Math.round(performance.now() - start);
|
||||||
processing.value = false;
|
processing.value = false;
|
||||||
if (resultUrl.value) {
|
|
||||||
genHist.add({
|
|
||||||
title: tab.value.label,
|
|
||||||
detail: `原图 ${imgNatural.value.w}×${imgNatural.value.h} · 耗时 ${elapsed.value}ms`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,6 +418,7 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</n-spin>
|
</n-spin>
|
||||||
</div>
|
</div>
|
||||||
|
<ImgHist ref="histRef" kind="ai-retouch" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- bottom bar -->
|
<!-- bottom bar -->
|
||||||
@@ -432,7 +440,6 @@ onUnmounted(() => {
|
|||||||
</c-button>
|
</c-button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<GenHistory tool="ai-retouch" position="right" label="修图记录" />
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { getMachineId, licenseHeaders } from '@/tools/license/license';
|
import { getMachineId, licenseHeaders } from '@/tools/license/license';
|
||||||
|
import ImgHist from '@/tools/img-hist/ImgHist.vue';
|
||||||
|
import { authHdr } from '@/tools/img-hist/img-hist';
|
||||||
|
|
||||||
// ---------- 状态 ----------
|
// ---------- 状态 ----------
|
||||||
const file = ref<File | null>(null);
|
const file = ref<File | null>(null);
|
||||||
@@ -51,6 +53,7 @@ onMounted(async () => {
|
|||||||
// ---------- 最近任务(localStorage 缩略图) ----------
|
// ---------- 最近任务(localStorage 缩略图) ----------
|
||||||
interface SETask { id: string; time: number; prompt: string; before: string; after: string; count: number }
|
interface SETask { id: string; time: number; prompt: string; before: string; after: string; count: number }
|
||||||
const tasks = ref<SETask[]>([]);
|
const tasks = ref<SETask[]>([]);
|
||||||
|
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
|
||||||
const LS_KEY = 'it-ai-text-edit:tasks';
|
const LS_KEY = 'it-ai-text-edit:tasks';
|
||||||
|
|
||||||
function loadTasks() {
|
function loadTasks() {
|
||||||
@@ -145,7 +148,7 @@ async function submit() {
|
|||||||
}
|
}
|
||||||
const res = await fetch('/relay/ai/seamless-edit', {
|
const res = await fetch('/relay/ai/seamless-edit', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: licenseHeaders('ai-text-edit'),
|
headers: { ...licenseHeaders('ai-text-edit'), ...authHdr() },
|
||||||
body: fd,
|
body: fd,
|
||||||
});
|
});
|
||||||
const j = await res.json().catch(() => ({}));
|
const j = await res.json().catch(() => ({}));
|
||||||
@@ -167,6 +170,7 @@ async function submit() {
|
|||||||
tasks.value = tasks.value.slice(0, 12);
|
tasks.value = tasks.value.slice(0, 12);
|
||||||
saveTasks();
|
saveTasks();
|
||||||
}
|
}
|
||||||
|
histRef.value?.reload();
|
||||||
else if (!note.value) {
|
else if (!note.value) {
|
||||||
note.value = '未产生结果,请调整描述后重试';
|
note.value = '未产生结果,请调整描述后重试';
|
||||||
}
|
}
|
||||||
@@ -339,6 +343,7 @@ function clearAll() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<ImgHist ref="histRef" kind="seamless" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -349,7 +354,7 @@ function clearAll() {
|
|||||||
.se-title { font-size: 30px; font-weight: 800; letter-spacing: 2px; }
|
.se-title { font-size: 30px; font-weight: 800; letter-spacing: 2px; }
|
||||||
.se-sub { margin-top: 6px; font-size: 13px; opacity: 0.6; }
|
.se-sub { margin-top: 6px; font-size: 13px; opacity: 0.6; }
|
||||||
|
|
||||||
.se-grid { display: grid; grid-template-columns: 380px 1fr; gap: 16px; align-items: start; }
|
.se-grid { display: grid; grid-template-columns: 380px 1fr 76px; gap: 16px; align-items: start; }
|
||||||
@media (max-width: 900px) { .se-grid { grid-template-columns: 1fr; } }
|
@media (max-width: 900px) { .se-grid { grid-template-columns: 1fr; } }
|
||||||
|
|
||||||
.se-ctrl { background: #fff; border: 1px solid rgba(128,128,128,0.18); border-radius: 12px; padding: 16px; display: flex; flex-direction: column; gap: 14px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
|
.se-ctrl { background: #fff; border: 1px solid rgba(128,128,128,0.18); border-radius: 12px; padding: 16px; display: flex; flex-direction: column; gap: 14px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
import { onUnmounted, ref } from 'vue';
|
import { onUnmounted, ref } from 'vue';
|
||||||
import { useHead } from '@vueuse/head';
|
import { useHead } from '@vueuse/head';
|
||||||
import { licenseHeaders } from '@/tools/license/license';
|
import { licenseHeaders } from '@/tools/license/license';
|
||||||
|
import ImgHist from '@/tools/img-hist/ImgHist.vue';
|
||||||
|
import { authHdr } from '@/tools/img-hist/img-hist';
|
||||||
|
|
||||||
useHead({ title: 'AI 换脸 - IT-TOOLS-PRO' });
|
useHead({ title: 'AI 换脸 - IT-TOOLS-PRO' });
|
||||||
|
|
||||||
@@ -10,6 +12,7 @@ const dstUrl = ref('');
|
|||||||
const srcFile = ref<File | null>(null);
|
const srcFile = ref<File | null>(null);
|
||||||
const dstFile = ref<File | null>(null);
|
const dstFile = ref<File | null>(null);
|
||||||
const consent = ref(false);
|
const consent = ref(false);
|
||||||
|
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
|
||||||
const busy = ref(false);
|
const busy = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const resultUrl = ref('');
|
const resultUrl = ref('');
|
||||||
@@ -71,7 +74,7 @@ async function doSwap() {
|
|||||||
try {
|
try {
|
||||||
const res = await fetch('/relay/ai/face-swap', {
|
const res = await fetch('/relay/ai/face-swap', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: licenseHeaders('face-swap'),
|
headers: { ...licenseHeaders('face-swap'), ...authHdr() },
|
||||||
body: fd,
|
body: fd,
|
||||||
signal: ctrl.signal,
|
signal: ctrl.signal,
|
||||||
});
|
});
|
||||||
@@ -84,6 +87,7 @@ async function doSwap() {
|
|||||||
if (!resultUrl.value) {
|
if (!resultUrl.value) {
|
||||||
throw new Error('服务端未返回结果图片');
|
throw new Error('服务端未返回结果图片');
|
||||||
}
|
}
|
||||||
|
histRef.value?.reload();
|
||||||
}
|
}
|
||||||
catch (e: any) {
|
catch (e: any) {
|
||||||
error.value = e?.name === 'AbortError' ? '处理超时,请稍后重试' : String(e?.message || e);
|
error.value = e?.name === 'AbortError' ? '处理超时,请稍后重试' : String(e?.message || e);
|
||||||
@@ -118,6 +122,7 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="fs-root">
|
<div class="fs-root">
|
||||||
|
<div class="fs-main">
|
||||||
<div class="fs-head">
|
<div class="fs-head">
|
||||||
<h1>🎭 AI 换脸</h1>
|
<h1>🎭 AI 换脸</h1>
|
||||||
<span class="fs-note">insightface 人脸检测 + inswapper 本地 CPU 推理 · 照片不离开服务器</span>
|
<span class="fs-note">insightface 人脸检测 + inswapper 本地 CPU 推理 · 照片不离开服务器</span>
|
||||||
@@ -184,15 +189,28 @@ onUnmounted(() => {
|
|||||||
<p class="fs-tips">
|
<p class="fs-tips">
|
||||||
提示:两张图都需包含清晰人脸;源脸与目标脸角度、光线越接近效果越好。图片仅在服务器本地处理,不对外分享。
|
提示:两张图都需包含清晰人脸;源脸与目标脸角度、光线越接近效果越好。图片仅在服务器本地处理,不对外分享。
|
||||||
</p>
|
</p>
|
||||||
|
</div>
|
||||||
|
<ImgHist ref="histRef" kind="face-swap" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.fs-root {
|
.fs-root {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 8px 4px;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
.fs-main {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 16px;
|
gap: 16px;
|
||||||
padding: 8px 4px;
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.fs-root { flex-direction: column; }
|
||||||
}
|
}
|
||||||
.fs-head {
|
.fs-head {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue';
|
||||||
|
import { loadImgHist, type HistItem } from './img-hist';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图片历史右栏(铁规则统一实现):
|
||||||
|
* 50×50 缩略图右侧竖排、点击查看大图、按本人隔离(登录=账号/未登录=机器码)。
|
||||||
|
* 父级把本组件放在布局最右侧即可;生成成功后调用父组件暴露的 reload()。
|
||||||
|
*/
|
||||||
|
const props = withDefaults(defineProps<{ kind: string; label?: string }>(), {
|
||||||
|
label: '历史',
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = ref<HistItem[]>([]);
|
||||||
|
const viewUrl = ref('');
|
||||||
|
|
||||||
|
async function reload() {
|
||||||
|
items.value = await loadImgHist(props.kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({ reload });
|
||||||
|
onMounted(reload);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<aside class="ih">
|
||||||
|
<div class="ih-t">
|
||||||
|
{{ label }}<em v-if="items.length">{{ items.length }}</em>
|
||||||
|
</div>
|
||||||
|
<div v-if="items.length" class="ih-list">
|
||||||
|
<img
|
||||||
|
v-for="it in items"
|
||||||
|
:key="it.id"
|
||||||
|
:src="it.img_url"
|
||||||
|
:title="it.prompt || '点击查看大图'"
|
||||||
|
class="ih-thumb"
|
||||||
|
@click="viewUrl = it.img_url"
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div v-else class="ih-empty">
|
||||||
|
还没有<br>生成记录
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div v-if="viewUrl" class="ih-view" @click="viewUrl = ''">
|
||||||
|
<img :src="viewUrl" alt="历史图片">
|
||||||
|
<span class="ih-view-tip">点击任意处关闭</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped lang="less">
|
||||||
|
.ih {
|
||||||
|
flex: 0 0 76px;
|
||||||
|
width: 76px;
|
||||||
|
border: 1px solid rgba(128, 128, 128, 0.25);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: rgba(128, 128, 128, 0.04);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
align-self: flex-start;
|
||||||
|
max-height: calc(100vh - 230px);
|
||||||
|
|
||||||
|
.ih-t {
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-align: center;
|
||||||
|
padding: 9px 4px 7px;
|
||||||
|
border-bottom: 1px solid rgba(128, 128, 128, 0.18);
|
||||||
|
opacity: 0.75;
|
||||||
|
flex-shrink: 0;
|
||||||
|
|
||||||
|
em {
|
||||||
|
font-style: normal;
|
||||||
|
color: #0ea5a0;
|
||||||
|
margin-left: 4px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ih-list {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
overflow-x: hidden;
|
||||||
|
padding: 9px 13px 12px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ih-thumb {
|
||||||
|
width: 50px;
|
||||||
|
height: 50px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 7px;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
cursor: zoom-in;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
|
||||||
|
transition: all 0.15s;
|
||||||
|
display: block;
|
||||||
|
flex-shrink: 0;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
border-color: #0ea5a0;
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ih-empty {
|
||||||
|
font-size: 11px;
|
||||||
|
text-align: center;
|
||||||
|
opacity: 0.45;
|
||||||
|
padding: 16px 4px;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ih-view {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 9999;
|
||||||
|
background: rgba(0, 0, 0, 0.86);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
cursor: zoom-out;
|
||||||
|
|
||||||
|
img {
|
||||||
|
max-width: 92vw;
|
||||||
|
max-height: 88vh;
|
||||||
|
object-fit: contain;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ih-view-tip {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 26px;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
text-align: center;
|
||||||
|
color: rgba(255, 255, 255, 0.65);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.ih {
|
||||||
|
flex: none;
|
||||||
|
width: 100%;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
max-height: none;
|
||||||
|
|
||||||
|
.ih-t {
|
||||||
|
border-bottom: none;
|
||||||
|
border-right: 1px solid rgba(128, 128, 128, 0.18);
|
||||||
|
padding: 8px 10px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ih-list {
|
||||||
|
flex-direction: row;
|
||||||
|
overflow-x: auto;
|
||||||
|
overflow-y: hidden;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { getMachineId } from '@/tools/license/license';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图片历史共享层(铁规则):
|
||||||
|
* - 历史右栏 50×50 缩略图竖排 + 点击查看大图(ImgHist.vue)
|
||||||
|
* - 按本人隔离:登录带 Authorization(服务端按账号归属过滤),未登录按机器码
|
||||||
|
* - 生成结果保存到服务器后台「存储设置」目录(/relay/ai/img-save → DATA_DIR/gen_images)
|
||||||
|
* 历史拉取/保存失败一律静默,不阻断生成与下载。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** 登录态 Authorization(无登录返回空对象) */
|
||||||
|
export function authHdr(): Record<string, string> {
|
||||||
|
try {
|
||||||
|
const a = JSON.parse(localStorage.getItem('it-tools-auth') ?? 'null');
|
||||||
|
if (a && typeof a.token === 'string' && a.token) {
|
||||||
|
const h: Record<string, string> = {};
|
||||||
|
h['Authorization'] = 'Bearer ' + a.token;
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { /* ignore */ }
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HistItem {
|
||||||
|
id: string;
|
||||||
|
at: number;
|
||||||
|
model?: string;
|
||||||
|
prompt?: string;
|
||||||
|
kind?: string;
|
||||||
|
img_url: string;
|
||||||
|
w?: number;
|
||||||
|
h?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取本人某 kind 的图片历史(静默失败返回 []) */
|
||||||
|
export async function loadImgHist(kind: string): Promise<HistItem[]> {
|
||||||
|
try {
|
||||||
|
const url = `/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=${encodeURIComponent(kind)}`;
|
||||||
|
const res = await fetch(url, { headers: authHdr() });
|
||||||
|
const j = await res.json();
|
||||||
|
// 铁规则:所有功能历史最多显示 100 条(服务端已截断,此处兜底)
|
||||||
|
if (j.code === 200 && Array.isArray(j.data)) return j.data.slice(0, 100);
|
||||||
|
}
|
||||||
|
catch { /* 静默 */ }
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SaveImgOpts {
|
||||||
|
kind: string;
|
||||||
|
tool: string;
|
||||||
|
b64: string;
|
||||||
|
model?: string;
|
||||||
|
prompt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 保存生成结果到服务器(后台 storage_root/gen_images),静默失败返回 false */
|
||||||
|
export async function saveImgHist(o: SaveImgOpts): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const h = authHdr();
|
||||||
|
h['Content-Type'] = 'application/json';
|
||||||
|
const res = await fetch('/relay/ai/img-save', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: h,
|
||||||
|
body: JSON.stringify({
|
||||||
|
machine: getMachineId(),
|
||||||
|
b64: o.b64,
|
||||||
|
kind: o.kind,
|
||||||
|
tool: o.tool,
|
||||||
|
model: o.model || '',
|
||||||
|
prompt: o.prompt || '',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const j = await res.json().catch(() => ({}));
|
||||||
|
return j.code === 200;
|
||||||
|
}
|
||||||
|
catch { /* 静默,不阻断下载 */ }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Blob → 纯 base64(不含 data: 前缀) */
|
||||||
|
export function blobToB64(blob: Blob): Promise<string> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const fr = new FileReader();
|
||||||
|
fr.onload = () => {
|
||||||
|
const s = String(fr.result || '');
|
||||||
|
resolve(s.includes(',') ? s.split(',', 2)[1] : s);
|
||||||
|
};
|
||||||
|
fr.onerror = () => resolve('');
|
||||||
|
fr.readAsDataURL(blob);
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
resolve('');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** dataURL → 纯 base64 */
|
||||||
|
export function dataUrlToB64(u: string): string {
|
||||||
|
return u.includes(',') ? u.split(',', 2)[1] : u;
|
||||||
|
}
|
||||||
@@ -3,6 +3,9 @@ import {
|
|||||||
BUY_URL,
|
BUY_URL,
|
||||||
PROTECTED_TOOLS,
|
PROTECTED_TOOLS,
|
||||||
TRIAL_MS,
|
TRIAL_MS,
|
||||||
|
ensureToolCfg,
|
||||||
|
toolVisible,
|
||||||
|
trialMsOf,
|
||||||
activateCard,
|
activateCard,
|
||||||
checkAuth,
|
checkAuth,
|
||||||
deactivateLicense,
|
deactivateLicense,
|
||||||
@@ -24,6 +27,7 @@ function goBuy(): void {
|
|||||||
|
|
||||||
const displayName = computed(() => PROTECTED_TOOLS[props.path] ?? '');
|
const displayName = computed(() => PROTECTED_TOOLS[props.path] ?? '');
|
||||||
const protectedTool = computed(() => !!PROTECTED_TOOLS[props.path]);
|
const protectedTool = computed(() => !!PROTECTED_TOOLS[props.path]);
|
||||||
|
const paidCount = computed(() => Object.keys(PROTECTED_TOOLS).filter(toolVisible).length);
|
||||||
|
|
||||||
const now = ref(Date.now());
|
const now = ref(Date.now());
|
||||||
const showCardInput = ref(false);
|
const showCardInput = ref(false);
|
||||||
@@ -33,8 +37,10 @@ const activateMsg = ref('');
|
|||||||
const copied = ref(false);
|
const copied = ref(false);
|
||||||
let timer: ReturnType<typeof setInterval> | undefined;
|
let timer: ReturnType<typeof setInterval> | undefined;
|
||||||
|
|
||||||
const remaining = computed(() => (protectedTool.value ? remainingMs(props.path, now.value) : TRIAL_MS));
|
const limitMs = computed(() => trialMsOf(props.path) * 60 * 1000);
|
||||||
const trialUsed = computed(() => protectedTool.value && remaining.value < TRIAL_MS);
|
const limitMin = computed(() => Math.round(limitMs.value / 60000));
|
||||||
|
const remaining = computed(() => (protectedTool.value ? remainingMs(props.path, now.value) : limitMs.value));
|
||||||
|
const trialUsed = computed(() => protectedTool.value && remaining.value < limitMs.value);
|
||||||
const expired = computed(() => protectedTool.value && !licenseState.authorized && remaining.value <= 0);
|
const expired = computed(() => protectedTool.value && !licenseState.authorized && remaining.value <= 0);
|
||||||
|
|
||||||
const mmss = computed(() => {
|
const mmss = computed(() => {
|
||||||
@@ -88,7 +94,7 @@ async function revokeLicense() {
|
|||||||
const r = await deactivateLicense();
|
const r = await deactivateLicense();
|
||||||
revokeMsg.value = r.msg;
|
revokeMsg.value = r.msg;
|
||||||
if (r.ok) {
|
if (r.ok) {
|
||||||
startTrial(props.path); // 回到试用:从现在起重新计 30 分钟
|
startTrial(props.path); // 回到试用:按后台配置时长重新计时
|
||||||
now.value = Date.now();
|
now.value = Date.now();
|
||||||
}
|
}
|
||||||
setTimeout(() => (revokeMsg.value = ''), 5000);
|
setTimeout(() => (revokeMsg.value = ''), 5000);
|
||||||
@@ -109,6 +115,7 @@ function copyMachine() {
|
|||||||
|
|
||||||
/** 每次进入受控功能页时检查授权并启动该功能的独立试用计时 */
|
/** 每次进入受控功能页时检查授权并启动该功能的独立试用计时 */
|
||||||
async function init() {
|
async function init() {
|
||||||
|
ensureToolCfg(true); // 后台刷新显示开关/试用时长配置(异步,不阻断)
|
||||||
activateMsg.value = '';
|
activateMsg.value = '';
|
||||||
showCardInput.value = false;
|
showCardInput.value = false;
|
||||||
if (!protectedTool.value) return;
|
if (!protectedTool.value) return;
|
||||||
@@ -160,16 +167,16 @@ onUnmounted(() => {
|
|||||||
{{ displayName }} · 今日免费 <b>{{ mmss }}</b>({{ resetTag }})
|
{{ displayName }} · 今日免费 <b>{{ mmss }}</b>({{ resetTag }})
|
||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
{{ displayName }} · 今日免费 30 分钟({{ resetTag }})
|
{{ displayName }} · 今日免费 {{ limitMin }} 分钟({{ resetTag }})
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template v-if="!licenseState.authorized">
|
<template v-if="!licenseState.authorized">
|
||||||
<a
|
<a
|
||||||
:href="BUY_URL"
|
:href="BUY_URL"
|
||||||
class="lg-buy"
|
class="lg-buy"
|
||||||
title="买断制授权,不按次不按月;一次激活,13 个高级功能全部解锁,授权跟随账号、换电脑可恢复"
|
:title="`买断制授权,不按次不按月;一次激活,${paidCount} 个高级功能全部解锁,授权跟随账号、换电脑可恢复`"
|
||||||
@click.prevent="goBuy"
|
@click.prevent="goBuy"
|
||||||
>永久解锁 13 个功能</a>
|
>永久解锁 {{ paidCount }} 个功能</a>
|
||||||
<a href="javascript:;" class="lg-link" @click="showCardInput = !showCardInput">卡密</a>
|
<a href="javascript:;" class="lg-link" @click="showCardInput = !showCardInput">卡密</a>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
@@ -202,7 +209,7 @@ onUnmounted(() => {
|
|||||||
🔒 {{ displayName }} 今日免费试用已用完
|
🔒 {{ displayName }} 今日免费试用已用完
|
||||||
</div>
|
</div>
|
||||||
<p class="lg-modal-desc">
|
<p class="lg-modal-desc">
|
||||||
该功能今日 30 分钟免费试用已用完<template v-if="resetHint">,{{ resetHint }} 可再试</template>。购买授权后全部功能立即解锁,或输入卡密激活。
|
该功能今日 {{ limitMin }} 分钟免费试用已用完<template v-if="resetHint">,{{ resetHint }} 可再试</template>。购买授权后全部功能立即解锁,或输入卡密激活。
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div class="lg-modal-actions">
|
<div class="lg-modal-actions">
|
||||||
|
|||||||
@@ -18,12 +18,67 @@ export const PROTECTED_TOOLS: Record<string, string> = {
|
|||||||
'/text-to-image': '文字生成图片',
|
'/text-to-image': '文字生成图片',
|
||||||
'/ai-image-lab': 'AI图片实验室',
|
'/ai-image-lab': 'AI图片实验室',
|
||||||
'/copywriting': '文案工具箱',
|
'/copywriting': '文案工具箱',
|
||||||
|
'/ai-text-edit': 'AI 无痕改字',
|
||||||
'/ai-gen': 'AI 生图',
|
'/ai-gen': 'AI 生图',
|
||||||
'/face-swap': 'AI换脸',
|
'/face-swap': 'AI换脸',
|
||||||
'/poster-maker': 'AI海报生成',
|
'/poster-maker': 'AI海报生成',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const TRIAL_MS = 30 * 60 * 1000; // 每个功能每天免费 30 分钟
|
export const TRIAL_MS = 30 * 60 * 1000; // 每个功能每天免费 30 分钟(管理后台可按功能覆盖)
|
||||||
|
|
||||||
|
// ====== 授权应用配置(管理后台「授权应用」页:前台显示开关 + 每日试用时长) ======
|
||||||
|
const TOOL_CFG_KEY = 'it-tools-tool-cfg';
|
||||||
|
export const toolCfg = reactive({
|
||||||
|
loaded: false,
|
||||||
|
visible: {} as Record<string, boolean>,
|
||||||
|
trial_minutes: {} as Record<string, number>,
|
||||||
|
});
|
||||||
|
|
||||||
|
function applyToolCfg(j: any): void {
|
||||||
|
if (!j || typeof j !== 'object') return;
|
||||||
|
toolCfg.visible = { ...(j.visible || {}) };
|
||||||
|
toolCfg.trial_minutes = { ...(j.trial_minutes || {}) };
|
||||||
|
toolCfg.loaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取管理后台配置;失败静默(回落缓存或默认值),不阻断功能 */
|
||||||
|
export function ensureToolCfg(force = false): void {
|
||||||
|
if (toolCfg.loaded && !force) return;
|
||||||
|
fetch('/relay/tool-config')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then((j) => {
|
||||||
|
if (j?.code === 200) {
|
||||||
|
applyToolCfg(j.data);
|
||||||
|
try { localStorage.setItem(TOOL_CFG_KEY, JSON.stringify(j.data)); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => { /* 静默:网络失败用缓存/默认 */ });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面加载即用缓存兜底 + 后台刷新(SPA 模块顶层执行)
|
||||||
|
try {
|
||||||
|
const cached = JSON.parse(localStorage.getItem(TOOL_CFG_KEY) ?? 'null');
|
||||||
|
if (cached) applyToolCfg(cached);
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
if (typeof window !== 'undefined') ensureToolCfg(true);
|
||||||
|
|
||||||
|
/** path → relay 侧标识(配置/X-Tool key;仅 AI图片实验室两头不同名) */
|
||||||
|
function slugOf(path: string): string {
|
||||||
|
const s = path.replace(/^\/+/, '');
|
||||||
|
return s === 'ai-image-lab' ? 'ai-image-tools' : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 管理后台开关:该路径前台是否显示(未配置=显示) */
|
||||||
|
export function toolVisible(path: string): boolean {
|
||||||
|
return toolCfg.visible[slugOf(path)] !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 管理后台配置:该功能每日免费试用时长(分钟;未配置=默认 30) */
|
||||||
|
export function trialMsOf(path: string): number {
|
||||||
|
const n = toolCfg.trial_minutes[slugOf(path)];
|
||||||
|
return typeof n === 'number' && n >= 1 ? n : TRIAL_MS / 60000;
|
||||||
|
}
|
||||||
|
|
||||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
const TZ_OFFSET_MS = 8 * 60 * 60 * 1000; // 北京时间 UTC+8 —— 重置对齐自然日 0 点
|
const TZ_OFFSET_MS = 8 * 60 * 60 * 1000; // 北京时间 UTC+8 —— 重置对齐自然日 0 点
|
||||||
|
|
||||||
@@ -78,12 +133,13 @@ export function startTrial(path: string): void {
|
|||||||
|
|
||||||
export function remainingMs(path: string, now: number): number {
|
export function remainingMs(path: string, now: number): number {
|
||||||
const start = getTrialStart(path);
|
const start = getTrialStart(path);
|
||||||
|
const limit = trialMsOf(path) * 60 * 1000; // 管理后台可按功能覆盖试用时长
|
||||||
if (start === null) {
|
if (start === null) {
|
||||||
return TRIAL_MS; // 尚未开始计时
|
return limit; // 尚未开始计时
|
||||||
}
|
}
|
||||||
// 起点不早于今天 0 点:昨天的起点在跨天后自动失效
|
// 起点不早于今天 0 点:昨天的起点在跨天后自动失效
|
||||||
const s = Math.max(start, todayStartOf(now));
|
const s = Math.max(start, todayStartOf(now));
|
||||||
return Math.max(0, TRIAL_MS - (now - s));
|
return Math.max(0, limit - (now - s));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 下一次重置时刻(恒为次日 00:00 北京时间);未开始计时返回 null */
|
/** 下一次重置时刻(恒为次日 00:00 北京时间);未开始计时返回 null */
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useUserAuth } from '@/composable/user-auth';
|
import { useUserAuth } from '@/composable/user-auth';
|
||||||
import { degrees, PDFDocument, rgb } from '@cantoo/pdf-lib';
|
import { degrees, PDFDocument, rgb } from '@cantoo/pdf-lib';
|
||||||
|
import fontkit from '@cantoo/fontkit';
|
||||||
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist';
|
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist';
|
||||||
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.js?url';
|
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.js?url';
|
||||||
import { zipSync } from 'fflate';
|
import { zipSync } from 'fflate';
|
||||||
@@ -387,16 +388,36 @@ async function doDecrypt() {
|
|||||||
statusMsg.value = '解密完成(输出为高清图片版,无密码),点击下载';
|
statusMsg.value = '解密完成(输出为高清图片版,无密码),点击下载';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 中文字体(Droid Sans Fallback,覆盖 CJK):仅含非西文水印时按需加载,模块级缓存字节
|
||||||
|
let cjkFontBytes: ArrayBuffer | null = null;
|
||||||
|
async function getCjkFontBytes(): Promise<ArrayBuffer> {
|
||||||
|
if (!cjkFontBytes) {
|
||||||
|
const res = await fetch(`${import.meta.env.BASE_URL}fonts/DroidSansFallback.ttf`);
|
||||||
|
if (!res.ok) throw new Error('中文字体加载失败');
|
||||||
|
cjkFontBytes = await res.arrayBuffer();
|
||||||
|
}
|
||||||
|
return cjkFontBytes;
|
||||||
|
}
|
||||||
|
|
||||||
async function doWatermark() {
|
async function doWatermark() {
|
||||||
if (!wmText.value.trim()) {
|
if (!wmText.value.trim()) {
|
||||||
throw new Error('请输入水印文字');
|
throw new Error('请输入水印文字');
|
||||||
}
|
}
|
||||||
const src = await loadDoc(files.value[0]);
|
const src = await loadDoc(files.value[0]);
|
||||||
const pages = src.getPages();
|
const pages = src.getPages();
|
||||||
const font = await src.embedFont('Helvetica');
|
const text = wmText.value.slice(0, 30);
|
||||||
|
// Helvetica(WinAnsi) 无法编码中文,会被替换成 ?;含非西文字符时嵌入中文字体子集
|
||||||
|
const needCjk = [...text].some(ch => ch.charCodeAt(0) > 0xff);
|
||||||
|
let font;
|
||||||
|
if (needCjk) {
|
||||||
|
src.registerFontkit(fontkit);
|
||||||
|
font = await src.embedFont(await getCjkFontBytes(), { subset: true });
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
font = await src.embedFont('Helvetica');
|
||||||
|
}
|
||||||
for (const page of pages) {
|
for (const page of pages) {
|
||||||
const { width, height } = page.getSize();
|
const { width, height } = page.getSize();
|
||||||
const text = wmText.value.slice(0, 30);
|
|
||||||
const tw = font.widthOfTextAtSize(text, wmSize.value);
|
const tw = font.widthOfTextAtSize(text, wmSize.value);
|
||||||
page.drawText(text, {
|
page.drawText(text, {
|
||||||
x: (width - tw) / 2,
|
x: (width - tw) / 2,
|
||||||
|
|||||||
+140
-17
@@ -1,6 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
|
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
|
||||||
import { getMachineId, licenseHeaders } from '@/tools/license/license';
|
import { getMachineId, licenseHeaders } from '@/tools/license/license';
|
||||||
|
import { authHdr } from '@/tools/img-hist/img-hist';
|
||||||
import {
|
import {
|
||||||
POSTER_TEMPLATES, POSTER_CATS, BG_PRESETS, POSTER_W, POSTER_H,
|
POSTER_TEMPLATES, POSTER_CATS, BG_PRESETS, POSTER_W, POSTER_H,
|
||||||
type PosterTemplate, type PosterBg, type PosterImageLayer,
|
type PosterTemplate, type PosterBg, type PosterImageLayer,
|
||||||
@@ -19,6 +20,8 @@ const bg = ref<PosterBg>({});
|
|||||||
const selId = ref('');
|
const selId = ref('');
|
||||||
const scale = ref(0.5);
|
const scale = ref(0.5);
|
||||||
const stageEl = ref<HTMLElement | null>(null);
|
const stageEl = ref<HTMLElement | null>(null);
|
||||||
|
const pmRoot = ref<HTMLElement | null>(null);
|
||||||
|
const pmH = ref(0); // 视口自适应高度:根不滚动,滚动只发生在内部区域
|
||||||
const fileEl = ref<HTMLInputElement | null>(null);
|
const fileEl = ref<HTMLInputElement | null>(null);
|
||||||
const pmError = ref('');
|
const pmError = ref('');
|
||||||
const models = ref<{ id: string; name?: string }[]>([]);
|
const models = ref<{ id: string; name?: string }[]>([]);
|
||||||
@@ -26,8 +29,24 @@ const model = ref('');
|
|||||||
const genBusy = ref(false);
|
const genBusy = ref(false);
|
||||||
const bgPrompt = ref('');
|
const bgPrompt = ref('');
|
||||||
const exporting = ref(false);
|
const exporting = ref(false);
|
||||||
|
// ---------- 生成历史(服务端落盘,右侧 50×50 缩略图竖排) ----------
|
||||||
|
const hist = ref<{ id: string; img_url: string; prompt?: string; kind?: string; at?: number }[]>([]);
|
||||||
|
const histBusy = ref(false);
|
||||||
|
const histView = ref(''); // 大图查看(点击缩略图打开,点空白关闭)
|
||||||
|
async function loadHist() {
|
||||||
|
histBusy.value = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/relay/ai/img-history?machine=${encodeURIComponent(getMachineId())}&kind=poster`, {
|
||||||
|
headers: { ...licenseHeaders('poster-maker'), ...authHdr() },
|
||||||
|
});
|
||||||
|
const j = await res.json().catch(() => ({}) as any);
|
||||||
|
// 铁规则:所有功能历史最多显示 100 条
|
||||||
|
if (res.ok && j.code === 200 && Array.isArray(j.data)) hist.value = j.data.slice(0, 100);
|
||||||
|
} catch { /* 历史拉取失败静默,不影响编辑 */ } finally { histBusy.value = false; }
|
||||||
|
}
|
||||||
let uid = 0;
|
let uid = 0;
|
||||||
let ro: ResizeObserver | null = null;
|
let ro: ResizeObserver | null = null;
|
||||||
|
let scRO: ResizeObserver | null = null;
|
||||||
|
|
||||||
const filtered = computed(() =>
|
const filtered = computed(() =>
|
||||||
cat.value === 'hot' ? POSTER_TEMPLATES : POSTER_TEMPLATES.filter((t) => t.category === cat.value));
|
cat.value === 'hot' ? POSTER_TEMPLATES : POSTER_TEMPLATES.filter((t) => t.category === cat.value));
|
||||||
@@ -97,6 +116,7 @@ function boxStyle(l: L) {
|
|||||||
return {
|
return {
|
||||||
left: l.x + 'px', top: l.y + 'px', width: l.w + 'px',
|
left: l.x + 'px', top: l.y + 'px', width: l.w + 'px',
|
||||||
height: l.type === 'text' ? 'auto' : l.h + 'px',
|
height: l.type === 'text' ? 'auto' : l.h + 'px',
|
||||||
|
transform: l.rot ? `rotate(${l.rot}deg)` : undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function fontStyle(l: L) {
|
function fontStyle(l: L) {
|
||||||
@@ -121,6 +141,7 @@ function shapeStyle(l: L) {
|
|||||||
function miniBoxStyle(l: L) { return boxStyle(l); }
|
function miniBoxStyle(l: L) { return boxStyle(l); }
|
||||||
const tplLayers = (t: PosterTemplate): L[] => t.layers as any;
|
const tplLayers = (t: PosterTemplate): L[] => t.layers as any;
|
||||||
function onFill(e: Event) { const l = sel.value; if (l) l.fill = (e.target as HTMLInputElement).value; }
|
function onFill(e: Event) { const l = sel.value; if (l) l.fill = (e.target as HTMLInputElement).value; }
|
||||||
|
function onRot(e: Event) { const l = sel.value; if (l) l.rot = Number((e.target as HTMLInputElement).value); }
|
||||||
|
|
||||||
// ---------- 选中 / 拖动 ----------
|
// ---------- 选中 / 拖动 ----------
|
||||||
function onDown(e: PointerEvent, l: L) {
|
function onDown(e: PointerEvent, l: L) {
|
||||||
@@ -198,14 +219,15 @@ async function genFor(l: PosterImageLayer) {
|
|||||||
else if (ar < 0.8) { width = 1024; height = 1792; }
|
else if (ar < 0.8) { width = 1024; height = 1792; }
|
||||||
const res = await fetch('/relay/ai/gen-image', {
|
const res = await fetch('/relay/ai/gen-image', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker') },
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
|
||||||
body: JSON.stringify({ machine: getMachineId(), prompt, model: model.value, width, height }),
|
body: JSON.stringify({ machine: getMachineId(), prompt, model: model.value, width, height, kind: 'poster' }),
|
||||||
});
|
});
|
||||||
const j = await res.json().catch(() => ({}) as any);
|
const j = await res.json().catch(() => ({}) as any);
|
||||||
if (!res.ok || j.code !== 200) throw new Error(j.message || `HTTP ${res.status}`);
|
if (!res.ok || j.code !== 200) throw new Error(j.message || `HTTP ${res.status}`);
|
||||||
const url = j.data?.img_url || (j.data?.b64 ? b64DataUrl(j.data.b64) : '') || j.data?.url || '';
|
const url = j.data?.img_url || (j.data?.b64 ? b64DataUrl(j.data.b64) : '') || j.data?.url || '';
|
||||||
if (!url) throw new Error('未返回图片');
|
if (!url) throw new Error('未返回图片');
|
||||||
l.src = url;
|
l.src = url;
|
||||||
|
loadHist(); // 服务端已落盘,刷新右侧历史
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
pmError.value = 'AI 生成失败:' + (err?.message || String(err));
|
pmError.value = 'AI 生成失败:' + (err?.message || String(err));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -224,9 +246,25 @@ async function genBg() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 缩放 ----------
|
// ---------- 缩放 ----------
|
||||||
|
// 宽高双向适配:画布始终完整落在舞台内,舞台自身不出滚动条
|
||||||
function fit() {
|
function fit() {
|
||||||
const w = stageEl.value?.clientWidth || 600;
|
measure(); // 舞台尺寸一变就顺带复测根高度(仅值变化才写,稳定后自收敛)
|
||||||
scale.value = Math.min(Math.max(w / POSTER_W, 0.18), 0.85);
|
const el = stageEl.value;
|
||||||
|
const w = Math.max((el?.clientWidth || 600) - 20, 120);
|
||||||
|
const h = Math.max((el?.clientHeight || 760) - 20, 160);
|
||||||
|
scale.value = Math.min(Math.max(Math.min(w / POSTER_W, h / POSTER_H), 0.1), 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测量所在滚动容器:根高度 = 容器可视高 - 上方占用,页面级永不出现滚动条
|
||||||
|
function measure() {
|
||||||
|
const el = pmRoot.value;
|
||||||
|
if (!el) return;
|
||||||
|
// 必须取最内层滚动容器:外层是套壳,高度口径不同,用外层算出来的值会错
|
||||||
|
const sc = el.closest('.n-layout-scroll-container') as HTMLElement | null;
|
||||||
|
if (!sc) return;
|
||||||
|
const above = el.getBoundingClientRect().top - sc.getBoundingClientRect().top + sc.scrollTop;
|
||||||
|
const h = Math.floor(sc.clientHeight - above - 18);
|
||||||
|
if (h >= 160 && h !== pmH.value) pmH.value = h;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 导出 PNG ----------
|
// ---------- 导出 PNG ----------
|
||||||
@@ -264,9 +302,16 @@ function loadImg(src: string): Promise<HTMLImageElement | null> {
|
|||||||
i.src = src;
|
i.src = src;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// 绕 (cx, cy) 旋转画布坐标系:预览走 CSS transform、导出走 canvas,中心一致才不跑位
|
||||||
|
function rotAround(ctx: CanvasRenderingContext2D, cx: number, cy: number, deg: number) {
|
||||||
|
ctx.translate(cx, cy);
|
||||||
|
ctx.rotate((deg * Math.PI) / 180);
|
||||||
|
ctx.translate(-cx, -cy);
|
||||||
|
}
|
||||||
async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
|
async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
|
||||||
if (l.type === 'shape') {
|
if (l.type === 'shape') {
|
||||||
ctx.save();
|
ctx.save();
|
||||||
|
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
|
||||||
ctx.globalAlpha = l.opacity ?? 1;
|
ctx.globalAlpha = l.opacity ?? 1;
|
||||||
ctx.fillStyle = l.fill;
|
ctx.fillStyle = l.fill;
|
||||||
if (l.shape === 'ellipse') {
|
if (l.shape === 'ellipse') {
|
||||||
@@ -282,6 +327,7 @@ async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
|
|||||||
}
|
}
|
||||||
if (l.type === 'image') {
|
if (l.type === 'image') {
|
||||||
ctx.save();
|
ctx.save();
|
||||||
|
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + l.h / 2, l.rot);
|
||||||
rrPath(ctx, l.x, l.y, l.w, l.h, l.radius ?? 0);
|
rrPath(ctx, l.x, l.y, l.w, l.h, l.radius ?? 0);
|
||||||
ctx.clip();
|
ctx.clip();
|
||||||
const img = l.src ? await loadImg(l.src) : null;
|
const img = l.src ? await loadImg(l.src) : null;
|
||||||
@@ -310,6 +356,8 @@ async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
|
|||||||
const asc = (m as any).fontBoundingBoxAscent ?? l.size * 0.8;
|
const asc = (m as any).fontBoundingBoxAscent ?? l.size * 0.8;
|
||||||
const desc = (m as any).fontBoundingBoxDescent ?? l.size * 0.2;
|
const desc = (m as any).fontBoundingBoxDescent ?? l.size * 0.2;
|
||||||
const lines = linesOf(l);
|
const lines = linesOf(l);
|
||||||
|
ctx.save();
|
||||||
|
if (l.rot) rotAround(ctx, l.x + l.w / 2, l.y + (lines.length * lh) / 2, l.rot);
|
||||||
ctx.textAlign = l.align === 'center' ? 'center' : l.align === 'right' ? 'right' : 'left';
|
ctx.textAlign = l.align === 'center' ? 'center' : l.align === 'right' ? 'right' : 'left';
|
||||||
const tx = l.align === 'center' ? l.x + l.w / 2 : l.align === 'right' ? l.x + l.w : l.x;
|
const tx = l.align === 'center' ? l.x + l.w / 2 : l.align === 'right' ? l.x + l.w : l.x;
|
||||||
for (let i = 0; i < lines.length; i++) {
|
for (let i = 0; i < lines.length; i++) {
|
||||||
@@ -321,7 +369,7 @@ async function drawLayer(ctx: CanvasRenderingContext2D, l: L) {
|
|||||||
}
|
}
|
||||||
ctx.fillText(lines[i], tx, y);
|
ctx.fillText(lines[i], tx, y);
|
||||||
}
|
}
|
||||||
ctx.shadowColor = 'transparent'; ctx.shadowBlur = 0; ctx.shadowOffsetY = 0;
|
ctx.restore();
|
||||||
}
|
}
|
||||||
async function exportPng() {
|
async function exportPng() {
|
||||||
exporting.value = true; pmError.value = '';
|
exporting.value = true; pmError.value = '';
|
||||||
@@ -338,6 +386,21 @@ async function exportPng() {
|
|||||||
a.download = `${cur.value?.name || '海报'}.png`;
|
a.download = `${cur.value?.name || '海报'}.png`;
|
||||||
a.click();
|
a.click();
|
||||||
setTimeout(() => URL.revokeObjectURL(a.href), 8000);
|
setTimeout(() => URL.revokeObjectURL(a.href), 8000);
|
||||||
|
// 同步保存到服务器后台存储目录(后台「存储设置」的 gen_images),失败不阻断下载
|
||||||
|
try {
|
||||||
|
const b64 = await new Promise<string>((res, rej) => {
|
||||||
|
const fr = new FileReader();
|
||||||
|
fr.onload = () => res(String(fr.result || ''));
|
||||||
|
fr.onerror = () => rej(new Error('读取失败'));
|
||||||
|
fr.readAsDataURL(blob);
|
||||||
|
});
|
||||||
|
await fetch('/relay/ai/img-save', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders('poster-maker'), ...authHdr() },
|
||||||
|
body: JSON.stringify({ machine: getMachineId(), b64, kind: 'poster', model: 'AI海报', prompt: cur.value?.name || '海报导出' }),
|
||||||
|
});
|
||||||
|
loadHist();
|
||||||
|
} catch { /* 保存失败不影响本地下载 */ }
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
pmError.value = '导出失败:' + (err?.message || String(err));
|
pmError.value = '导出失败:' + (err?.message || String(err));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -346,10 +409,20 @@ async function exportPng() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
|
selectTemplate(POSTER_TEMPLATES[0]);
|
||||||
|
loadHist();
|
||||||
|
measure();
|
||||||
fit();
|
fit();
|
||||||
ro = new ResizeObserver(fit);
|
ro = new ResizeObserver(fit);
|
||||||
if (stageEl.value) ro.observe(stageEl.value);
|
if (stageEl.value) ro.observe(stageEl.value);
|
||||||
selectTemplate(POSTER_TEMPLATES[0]);
|
const sc = pmRoot.value?.closest('.n-layout-scroll-container');
|
||||||
|
if (sc) { scRO = new ResizeObserver(measure); scRO.observe(sc); }
|
||||||
|
window.addEventListener('resize', measure);
|
||||||
|
window.addEventListener('focus', measure);
|
||||||
|
document.addEventListener('visibilitychange', measure);
|
||||||
|
// 头部字体/公告条加载完高度会微变,延迟复测两次
|
||||||
|
setTimeout(measure, 400);
|
||||||
|
setTimeout(measure, 1500);
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/relay/ai/image-models', { headers: licenseHeaders('poster-maker') });
|
const res = await fetch('/relay/ai/image-models', { headers: licenseHeaders('poster-maker') });
|
||||||
const j = await res.json().catch(() => ({}) as any);
|
const j = await res.json().catch(() => ({}) as any);
|
||||||
@@ -359,11 +432,18 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
} catch { /* 模型列表拉取失败时用默认空值 */ }
|
} catch { /* 模型列表拉取失败时用默认空值 */ }
|
||||||
});
|
});
|
||||||
onBeforeUnmount(() => { ro?.disconnect(); onUp(); });
|
onBeforeUnmount(() => {
|
||||||
|
ro?.disconnect();
|
||||||
|
scRO?.disconnect();
|
||||||
|
window.removeEventListener('resize', measure);
|
||||||
|
window.removeEventListener('focus', measure);
|
||||||
|
document.removeEventListener('visibilitychange', measure);
|
||||||
|
onUp();
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="pm-root">
|
<div ref="pmRoot" class="pm-root" :style="pmH ? { height: pmH + 'px' } : undefined">
|
||||||
<div class="pm-top">
|
<div class="pm-top">
|
||||||
<div class="pm-cats">
|
<div class="pm-cats">
|
||||||
<button
|
<button
|
||||||
@@ -490,6 +570,13 @@ onBeforeUnmount(() => { ro?.disconnect(); onUp(); });
|
|||||||
<div v-if="sel" class="pm-sec">
|
<div v-if="sel" class="pm-sec">
|
||||||
<div class="pm-sec-title">编辑「{{ selName }}」</div>
|
<div class="pm-sec-title">编辑「{{ selName }}」</div>
|
||||||
|
|
||||||
|
<div class="pm-row">
|
||||||
|
<label>旋转</label>
|
||||||
|
<input :value="sel.rot ?? 0" type="range" min="-180" max="180" step="1" @input="onRot" />
|
||||||
|
<span>{{ sel.rot ?? 0 }}°</span>
|
||||||
|
<button class="pm-mini-btn" @click="sel.rot = 0">复位</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<template v-if="sel.type === 'text'">
|
<template v-if="sel.type === 'text'">
|
||||||
<textarea v-model="sel.text" class="pm-input ta" rows="3" placeholder="文字内容,支持换行"></textarea>
|
<textarea v-model="sel.text" class="pm-input ta" rows="3" placeholder="文字内容,支持换行"></textarea>
|
||||||
<div class="pm-row">
|
<div class="pm-row">
|
||||||
@@ -556,13 +643,33 @@ onBeforeUnmount(() => { ro?.disconnect(); onUp(); });
|
|||||||
</div>
|
</div>
|
||||||
<div v-else class="pm-tip">点击画布中的元素进行编辑,拖动可移动位置;右侧图层可排序、删除。</div>
|
<div v-else class="pm-tip">点击画布中的元素进行编辑,拖动可移动位置;右侧图层可排序、删除。</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
|
<!-- 最右:生成历史(50×50 缩略图竖排,点击查看大图) -->
|
||||||
|
<aside class="pm-hist">
|
||||||
|
<div class="pm-hist-t">历史<em v-if="hist.length">{{ hist.length }}</em></div>
|
||||||
|
<div v-if="hist.length" class="pm-hist-list">
|
||||||
|
<img
|
||||||
|
v-for="it in hist" :key="it.id"
|
||||||
|
class="pm-hist-thumb"
|
||||||
|
:src="it.img_url"
|
||||||
|
:title="it.prompt || '点击查看大图'"
|
||||||
|
@click="histView = it.img_url"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div v-else class="pm-hist-empty">还没有<br />生成记录</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 大图查看 -->
|
||||||
|
<div v-if="histView" class="pm-hist-view" @click="histView = ''">
|
||||||
|
<img :src="histView" alt="生成图片大图" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.pm-root { display: flex; flex-direction: column; gap: 10px; padding: 12px; box-sizing: border-box; min-height: 100%; }
|
.pm-root { display: flex; flex-direction: column; gap: 10px; padding: 12px; box-sizing: border-box; height: 100%; overflow: hidden; }
|
||||||
.pm-top { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
|
.pm-top { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; flex-shrink: 0; }
|
||||||
.pm-cats { display: flex; flex-wrap: wrap; gap: 6px; }
|
.pm-cats { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
.pm-cat { padding: 5px 12px; border-radius: 14px; border: 1px solid var(--n-border-color, #d9d9d9); background: transparent; color: inherit; cursor: pointer; font-size: 13px; }
|
.pm-cat { padding: 5px 12px; border-radius: 14px; border: 1px solid var(--n-border-color, #d9d9d9); background: transparent; color: inherit; cursor: pointer; font-size: 13px; }
|
||||||
.pm-cat.on { background: #3b82f6; border-color: #3b82f6; color: #fff; }
|
.pm-cat.on { background: #3b82f6; border-color: #3b82f6; color: #fff; }
|
||||||
@@ -573,11 +680,11 @@ onBeforeUnmount(() => { ro?.disconnect(); onUp(); });
|
|||||||
.pm-btn.primary:hover { background: #2563eb; color: #fff; }
|
.pm-btn.primary:hover { background: #2563eb; color: #fff; }
|
||||||
.pm-btn.wide { width: 100%; margin-top: 6px; }
|
.pm-btn.wide { width: 100%; margin-top: 6px; }
|
||||||
.pm-btn:disabled { opacity: .55; cursor: not-allowed; }
|
.pm-btn:disabled { opacity: .55; cursor: not-allowed; }
|
||||||
.pm-error { padding: 8px 12px; border-radius: 8px; background: #fef2f2; border: 1px solid #fecaca; color: #dc2626; font-size: 13px; }
|
.pm-error { flex-shrink: 0; padding: 8px 12px; border-radius: 8px; background: #fef2f2; border: 1px solid #fecaca; color: #dc2626; font-size: 13px; }
|
||||||
.pm-main { display: flex; gap: 12px; align-items: flex-start; flex: 1; min-height: 0; }
|
.pm-main { display: flex; gap: 12px; align-items: stretch; flex: 1; min-height: 0; }
|
||||||
|
|
||||||
/* 模板库 */
|
/* 模板库 */
|
||||||
.pm-tpls { width: 292px; flex-shrink: 0; max-height: calc(100vh - 170px); overflow: auto; }
|
.pm-tpls { width: 292px; flex-shrink: 0; min-height: 0; overflow-y: auto; overflow-x: hidden; }
|
||||||
.pm-sec-title { font-size: 13px; font-weight: 700; opacity: .75; margin-bottom: 8px; }
|
.pm-sec-title { font-size: 13px; font-weight: 700; opacity: .75; margin-bottom: 8px; }
|
||||||
.pm-tpl-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
|
.pm-tpl-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
|
||||||
.pm-tpl-card { border: 2px solid transparent; border-radius: 10px; padding: 6px; cursor: pointer; background: rgba(127,127,127,.07); }
|
.pm-tpl-card { border: 2px solid transparent; border-radius: 10px; padding: 6px; cursor: pointer; background: rgba(127,127,127,.07); }
|
||||||
@@ -588,7 +695,7 @@ onBeforeUnmount(() => { ro?.disconnect(); onUp(); });
|
|||||||
.pm-tpl-name { font-size: 12px; text-align: center; margin-top: 4px; }
|
.pm-tpl-name { font-size: 12px; text-align: center; margin-top: 4px; }
|
||||||
|
|
||||||
/* 画布 */
|
/* 画布 */
|
||||||
.pm-stage { flex: 1; min-width: 0; display: flex; justify-content: center; overflow: auto; max-height: calc(100vh - 150px); padding-bottom: 8px; }
|
.pm-stage { flex: 1; min-width: 0; min-height: 0; display: flex; justify-content: center; overflow: auto; padding-bottom: 8px; }
|
||||||
.pm-frame { position: relative; flex-shrink: 0; box-shadow: 0 6px 24px rgba(0,0,0,.18); border-radius: 4px; overflow: hidden; }
|
.pm-frame { position: relative; flex-shrink: 0; box-shadow: 0 6px 24px rgba(0,0,0,.18); border-radius: 4px; overflow: hidden; }
|
||||||
.pm-canvas { position: absolute; left: 0; top: 0; transform-origin: 0 0; overflow: hidden; }
|
.pm-canvas { position: absolute; left: 0; top: 0; transform-origin: 0 0; overflow: hidden; }
|
||||||
.pm-layer { position: absolute; box-sizing: border-box; user-select: none; -webkit-user-select: none; touch-action: none; }
|
.pm-layer { position: absolute; box-sizing: border-box; user-select: none; -webkit-user-select: none; touch-action: none; }
|
||||||
@@ -599,7 +706,18 @@ onBeforeUnmount(() => { ro?.disconnect(); onUp(); });
|
|||||||
.pm-mini .pm-ph { font-size: 40px; }
|
.pm-mini .pm-ph { font-size: 40px; }
|
||||||
|
|
||||||
/* 面板 */
|
/* 面板 */
|
||||||
.pm-panel { width: 316px; flex-shrink: 0; max-height: calc(100vh - 150px); overflow: auto; display: flex; flex-direction: column; gap: 14px; }
|
.pm-panel { width: 316px; flex-shrink: 0; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; }
|
||||||
|
|
||||||
|
/* 生成历史(右栏 76px,50×50 缩略图竖排) */
|
||||||
|
.pm-hist { width: 76px; flex-shrink: 0; min-height: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.pm-hist-t { font-size: 12px; font-weight: 700; opacity: .75; text-align: center; }
|
||||||
|
.pm-hist-t em { font-style: normal; color: #3b82f6; margin-left: 3px; }
|
||||||
|
.pm-hist-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: center; gap: 6px; padding-bottom: 8px; }
|
||||||
|
.pm-hist-thumb { width: 50px; height: 50px; object-fit: cover; border-radius: 8px; cursor: zoom-in; border: 2px solid transparent; background: rgba(127,127,127,.12); flex-shrink: 0; transition: border-color .15s; }
|
||||||
|
.pm-hist-thumb:hover { border-color: #3b82f6; }
|
||||||
|
.pm-hist-empty { font-size: 11px; opacity: .55; text-align: center; line-height: 1.6; padding-top: 10px; }
|
||||||
|
.pm-hist-view { position: fixed; inset: 0; z-index: 9999; background: rgba(0,0,0,.78); display: flex; align-items: center; justify-content: center; cursor: zoom-out; padding: 24px; }
|
||||||
|
.pm-hist-view img { max-width: 92vw; max-height: 92vh; object-fit: contain; border-radius: 8px; background: #fff; box-shadow: 0 10px 40px rgba(0,0,0,.4); }
|
||||||
.pm-sec { padding: 10px 12px; border: 1px solid var(--n-border-color, #e5e5e5); border-radius: 10px; background: rgba(127,127,127,.04); }
|
.pm-sec { padding: 10px 12px; border: 1px solid var(--n-border-color, #e5e5e5); border-radius: 10px; background: rgba(127,127,127,.04); }
|
||||||
.pm-bgs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 6px; }
|
.pm-bgs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 6px; }
|
||||||
.pm-bg-sw { height: 26px; border-radius: 6px; border: 1px solid rgba(127,127,127,.35); cursor: pointer; }
|
.pm-bg-sw { height: 26px; border-radius: 6px; border: 1px solid rgba(127,127,127,.35); cursor: pointer; }
|
||||||
@@ -624,8 +742,13 @@ onBeforeUnmount(() => { ro?.disconnect(); onUp(); });
|
|||||||
.pm-tip { font-size: 13px; opacity: .65; line-height: 1.7; padding: 8px 4px; }
|
.pm-tip { font-size: 13px; opacity: .65; line-height: 1.7; padding: 8px 4px; }
|
||||||
.pm-hidden { display: none; }
|
.pm-hidden { display: none; }
|
||||||
@media (max-width: 1180px) {
|
@media (max-width: 1180px) {
|
||||||
.pm-main { flex-direction: column; }
|
.pm-main { flex-direction: column; overflow-y: auto; }
|
||||||
.pm-tpls, .pm-panel { width: 100%; max-height: none; }
|
.pm-tpls, .pm-panel { width: 100%; max-height: none; overflow: visible; }
|
||||||
|
.pm-stage { flex: none; height: 56vh; }
|
||||||
.pm-tpl-grid { grid-template-columns: repeat(4, 1fr); }
|
.pm-tpl-grid { grid-template-columns: repeat(4, 1fr); }
|
||||||
|
/* 窄屏:历史栏改为横排(缩略图仍 50×50) */
|
||||||
|
.pm-hist { width: 100%; flex-direction: row; align-items: center; gap: 8px; }
|
||||||
|
.pm-hist-t { flex-shrink: 0; }
|
||||||
|
.pm-hist-list { flex-direction: row; overflow-x: auto; overflow-y: hidden; padding-bottom: 0; }
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -15,12 +15,14 @@ export interface PosterTextLayer {
|
|||||||
lineHeight?: number; // 倍数,默认 1.25
|
lineHeight?: number; // 倍数,默认 1.25
|
||||||
italic?: boolean;
|
italic?: boolean;
|
||||||
shadow?: PosterTextShadow;
|
shadow?: PosterTextShadow;
|
||||||
|
rot?: number; // 旋转角度(度,绕图层中心,可为负)
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PosterImageLayer {
|
export interface PosterImageLayer {
|
||||||
type: 'image';
|
type: 'image';
|
||||||
x: number; y: number; w: number; h: number;
|
x: number; y: number; w: number; h: number;
|
||||||
radius?: number;
|
radius?: number;
|
||||||
|
rot?: number; // 旋转角度(度)
|
||||||
src?: string; // 当前图片(上传或 AI 生成后写入)
|
src?: string; // 当前图片(上传或 AI 生成后写入)
|
||||||
prompt?: string; // AI 生成默认提示词
|
prompt?: string; // AI 生成默认提示词
|
||||||
}
|
}
|
||||||
@@ -32,6 +34,7 @@ export interface PosterShapeLayer {
|
|||||||
fill: string;
|
fill: string;
|
||||||
radius?: number;
|
radius?: number;
|
||||||
opacity?: number;
|
opacity?: number;
|
||||||
|
rot?: number; // 旋转角度(度)
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PosterLayer = PosterTextLayer | PosterImageLayer | PosterShapeLayer;
|
export type PosterLayer = PosterTextLayer | PosterImageLayer | PosterShapeLayer;
|
||||||
@@ -62,6 +65,7 @@ export const POSTER_CATS = [
|
|||||||
{ id: 'event', name: '活动' },
|
{ id: 'event', name: '活动' },
|
||||||
{ id: 'food', name: '美食' },
|
{ id: 'food', name: '美食' },
|
||||||
{ id: 'edu', name: '教育' },
|
{ id: 'edu', name: '教育' },
|
||||||
|
{ id: 'school', name: '校园' },
|
||||||
{ id: 'sport', name: '健身' },
|
{ id: 'sport', name: '健身' },
|
||||||
{ id: 'recruit', name: '招聘' },
|
{ id: 'recruit', name: '招聘' },
|
||||||
{ id: 'birthday', name: '生日' },
|
{ id: 'birthday', name: '生日' },
|
||||||
@@ -293,6 +297,151 @@ export const POSTER_TEMPLATES: PosterTemplate[] = [
|
|||||||
sh('rect', 340, 1345, 400, 76, 'rgba(255,255,255,0.92)', { radius: 38 }),
|
sh('rect', 340, 1345, 400, 76, 'rgba(255,255,255,0.92)', { radius: 38 }),
|
||||||
tx('了解更多', 340, 1363, 400, 36, '#004d40', { weight: 700 }),
|
tx('了解更多', 340, 1363, 400, 36, '#004d40', { weight: 700 }),
|
||||||
]),
|
]),
|
||||||
|
|
||||||
|
// ---------------- 校园(学校/老师/学生) ----------------
|
||||||
|
mk('jiaoshijie', '教师节快乐', 'school', grad(135, '#ff8f00', '#ffd54f'), [
|
||||||
|
sh('ellipse', 660, 70, 380, 380, 'rgba(255,255,255,0.16)'),
|
||||||
|
tx('教师节快乐', 50, 330, 980, 150, '#ffffff', { weight: 900, shadow: { color: 'rgba(180,80,0,0.4)', blur: 20, y: 6 } }),
|
||||||
|
tx('三尺讲台 · 一生耕耘', 50, 540, 980, 56, '#fff3e0', { weight: 700 }),
|
||||||
|
im(140, 670, 800, 470, '老师在黑板前讲课,明亮温暖教室,教师节主题摄影', { radius: 24 }),
|
||||||
|
sh('rect', 340, 1195, 400, 96, '#c62828', { radius: 48 }),
|
||||||
|
tx('感恩有您', 340, 1217, 400, 44, '#ffd54f'),
|
||||||
|
tx('9月10日 · 致敬每一位恩师', 50, 1345, 980, 40, '#fff8e1', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('kaixue1', '开学第一课', 'school', grad(120, '#1565c0', '#42a5f5'), [
|
||||||
|
tx('开学第一课', 50, 260, 980, 150, '#ffd60a', { weight: 900 }),
|
||||||
|
tx('新学期 · 新起点 · 新目标', 50, 470, 980, 54, '#ffffff', { weight: 700 }),
|
||||||
|
im(130, 620, 820, 480, '黑板与书本开学场景,粉笔字新学期,明亮教室', { radius: 24 }),
|
||||||
|
sh('rect', 300, 1180, 480, 100, '#ffd60a', { radius: 50 }),
|
||||||
|
tx('收心启航 立即返校', 300, 1206, 480, 44, '#1565c0'),
|
||||||
|
tx('XX学校 9月1日正式上课', 50, 1340, 980, 40, '#bbdefb', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('jiazhanghui', '家长会通知', 'school', solid('#1a237e'), [
|
||||||
|
sh('rect', 0, 0, 1080, 14, '#ffd60a'),
|
||||||
|
tx('家长会通知', 60, 130, 960, 130, '#ffffff', { align: 'left', weight: 900 }),
|
||||||
|
tx('时间:本周六 09:00\n地点:三年级(2)班教室\n主讲:班主任 王老师', 60, 350, 960, 46, '#c5cae9', { align: 'left', weight: 400, lineHeight: 1.7 }),
|
||||||
|
im(60, 660, 960, 430, '教室家长会现场,课桌整齐排列,明亮校园教室', { radius: 16 }),
|
||||||
|
sh('rect', 60, 1170, 480, 96, '#ffd60a', { radius: 48 }),
|
||||||
|
tx('敬请准时出席', 60, 1193, 480, 44, '#1a237e'),
|
||||||
|
tx('XX小学 三年级(2)班 家委会', 60, 1330, 960, 38, '#90a4ae', { align: 'left', weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('yundonghui', '秋季运动会', 'school', grad(135, '#d32f2f', '#ff7043'), [
|
||||||
|
sh('ellipse', -80, 180, 320, 320, 'rgba(255,255,255,0.12)'),
|
||||||
|
tx('秋季运动会', 50, 300, 980, 165, '#ffd54f', { weight: 900 }),
|
||||||
|
tx('激情飞扬 · 超越自我', 50, 520, 980, 56, '#ffffff', { weight: 700 }),
|
||||||
|
im(120, 660, 840, 470, '学校操场红色跑道与运动健儿,运动会场景', { radius: 24 }),
|
||||||
|
sh('rect', 340, 1200, 400, 96, '#ffffff', { radius: 48 }),
|
||||||
|
tx('报名参赛', 340, 1224, 400, 44, '#d32f2f'),
|
||||||
|
tx('10月16日 · 学校操场', 50, 1345, 980, 40, '#ffe0b2', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('biyeji', '毕业季', 'school', grad(160, '#0d47a1', '#26c6da'), [
|
||||||
|
tx('毕业快乐', 50, 250, 980, 175, '#ffffff', { weight: 900, shadow: { color: 'rgba(0,40,90,0.45)', blur: 22, y: 8 } }),
|
||||||
|
tx('愿你前程似锦 · 顶峰相见', 50, 470, 980, 54, '#b3e5fc', { weight: 700 }),
|
||||||
|
im(190, 620, 700, 640, '学士帽抛向蓝天,毕业季庆祝,青春校园', { radius: 32 }),
|
||||||
|
tx('2026届 · 青春不散场', 50, 1350, 980, 42, '#e1f5fe', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('shezhaoxin', '社团招新', 'school', grad(135, '#8e24aa', '#ff6d00'), [
|
||||||
|
tx('社团招新', 50, 270, 980, 170, '#ffffff', { weight: 900 }),
|
||||||
|
tx('百团大战 · 就等你来', 50, 490, 980, 58, '#ffe0b2', { weight: 700 }),
|
||||||
|
im(140, 640, 800, 470, '大学生社团活动,街舞音乐绘画丰富多彩,校园招新', { radius: 28 }),
|
||||||
|
sh('ellipse', 370, 1180, 340, 170, '#ffd60a'),
|
||||||
|
tx('加入我们', 370, 1228, 340, 48, '#6a1b9a', { weight: 900 }),
|
||||||
|
tx('本周五中午 · 食堂广场', 50, 1380, 980, 38, '#ffffff', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('biaozhang', '优秀学生表彰', 'school', solid('#fff8e1'), [
|
||||||
|
sh('rect', 36, 36, 1008, 1368, '#c62828'),
|
||||||
|
sh('rect', 60, 60, 960, 1320, '#fff8e1'),
|
||||||
|
tx('光荣榜', 50, 170, 980, 150, '#c62828', { weight: 900 }),
|
||||||
|
tx('优秀学生表彰', 50, 370, 980, 96, '#d32f2f', { weight: 900, rot: -4 }),
|
||||||
|
tx('张同学 · 李同学 · 王同学\n品学兼优 · 全面发展', 140, 570, 800, 52, '#5d4037', { weight: 700, lineHeight: 1.8 }),
|
||||||
|
im(240, 810, 600, 380, '金色奖杯与奖状证书特写,表彰大会氛围', { radius: 20 }),
|
||||||
|
tx('XX学校 教务处', 50, 1270, 980, 44, '#8d6e63', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('ertongjie', '快乐六一', 'school', grad(135, '#00bcd4', '#8bc34a'), [
|
||||||
|
tx('快乐六一', 50, 270, 980, 165, '#ffffff', { weight: 900, shadow: { color: 'rgba(0,90,110,0.35)', blur: 18, y: 6 } }),
|
||||||
|
tx('阳光自信 · 快乐成长', 50, 485, 980, 54, '#e0f7fa', { weight: 700 }),
|
||||||
|
im(160, 630, 760, 550, '小学校园儿童欢笑庆祝,彩色气球彩带,六一儿童节', { radius: 32 }),
|
||||||
|
sh('ellipse', 390, 1230, 300, 160, '#ff5722'),
|
||||||
|
tx('6·1', 390, 1272, 300, 62, '#ffffff', { weight: 900 }),
|
||||||
|
tx('XX小学 庆六一文艺汇演', 50, 1395, 980, 36, '#ffffff', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('kaoshi', '考试加油', 'school', solid('#b71c1c'), [
|
||||||
|
sh('ellipse', 340, 90, 400, 400, 'rgba(255,213,79,0.92)'),
|
||||||
|
tx('必胜', 340, 210, 400, 150, '#b71c1c', { weight: 900 }),
|
||||||
|
tx('考试加油', 50, 560, 980, 165, '#ffd54f', { weight: 900 }),
|
||||||
|
tx('以梦为马 · 不负韶华', 50, 780, 980, 54, '#ffffff', { weight: 700 }),
|
||||||
|
im(140, 900, 800, 350, '学生伏案复习试卷书本特写,台灯下奋斗场景', { radius: 20 }),
|
||||||
|
sh('rect', 300, 1300, 480, 96, '#ffd60a', { radius: 48 }),
|
||||||
|
tx('金榜题名', 300, 1324, 480, 44, '#b71c1c'),
|
||||||
|
]),
|
||||||
|
mk('dushuyue', '书香校园读书月', 'school', grad(160, '#4e342e', '#8d6e63'), [
|
||||||
|
tx('书香校园', 50, 260, 980, 160, '#ffe0b2', { weight: 900 }),
|
||||||
|
tx('读书月 · 阅读分享活动', 50, 470, 980, 52, '#ffffff', { weight: 700 }),
|
||||||
|
im(130, 620, 820, 480, '图书馆书架与学生阅读,温暖木质色调,书香氛围', { radius: 24 }),
|
||||||
|
sh('rect', 290, 1170, 500, 96, '#ffe0b2', { radius: 48 }),
|
||||||
|
tx('每天阅读30分钟', 290, 1194, 500, 44, '#4e342e'),
|
||||||
|
tx('主办:语文教研组 · 11月', 50, 1330, 980, 40, '#d7ccc8', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
|
||||||
|
// ---------------- 更多促销/节日/活动/美食 ----------------
|
||||||
|
mk('miaosha', '限时秒杀', 'promo', solid('#111111'), [
|
||||||
|
tx('限时秒杀', 50, 260, 980, 170, '#ff1744', { weight: 900 }),
|
||||||
|
tx('前100名 · 1元抢', 50, 480, 980, 72, '#ffffff', { weight: 900 }),
|
||||||
|
im(80, 660, 580, 520, '爆款商品抢购堆头,红黑配色电商海报', { radius: 24 }),
|
||||||
|
sh('ellipse', 700, 660, 320, 320, 'rgba(255,23,68,0.88)'),
|
||||||
|
tx('1元', 700, 755, 320, 120, '#ffffff', { weight: 900, rot: -8 }),
|
||||||
|
tx('每晚8点准时开抢', 50, 1260, 980, 52, '#ff8a80', { weight: 700 }),
|
||||||
|
tx('活动截止:11月30日', 50, 1350, 980, 38, '#9e9e9e', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('shuang12', '双12年终盛典', 'promo', grad(135, '#4a148c', '#e91e63'), [
|
||||||
|
sh('ellipse', 620, 50, 440, 440, 'rgba(255,255,255,0.12)'),
|
||||||
|
tx('双12年终盛典', 40, 340, 1000, 130, '#ffffff', { weight: 900 }),
|
||||||
|
tx('年终好价 · 全场包邮', 50, 530, 980, 58, '#ffd60a', { weight: 900 }),
|
||||||
|
im(140, 670, 800, 470, '双12紫色电商促销礼盒堆头,霓虹光效', { radius: 28 }),
|
||||||
|
sh('rect', 340, 1210, 400, 96, '#ffd60a', { radius: 48 }),
|
||||||
|
tx('立即抢购', 340, 1234, 400, 44, '#4a148c'),
|
||||||
|
tx('12月12日 0点开抢', 50, 1350, 980, 40, '#f3e5f5', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('muri', '母亲节快乐', 'festival', grad(160, '#ec407a', '#f8bbd0'), [
|
||||||
|
tx('母亲节快乐', 50, 280, 980, 160, '#ffffff', { weight: 900, shadow: { color: 'rgba(150,20,60,0.35)', blur: 18, y: 6 } }),
|
||||||
|
tx('时光不老 · 母爱永恒', 50, 490, 980, 54, '#fce4ec', { weight: 700 }),
|
||||||
|
im(170, 640, 740, 540, '粉色康乃馨花束特写,母亲节温馨氛围', { radius: 32 }),
|
||||||
|
sh('ellipse', 380, 1225, 320, 150, '#ad1457'),
|
||||||
|
tx('感恩有你', 380, 1265, 320, 46, '#ffffff', { weight: 900 }),
|
||||||
|
tx('5月第二个星期日', 50, 1395, 980, 36, '#ffffff', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('zhounian', '门店周年庆', 'event', grad(135, '#bf360c', '#ff6d00'), [
|
||||||
|
tx('三周年庆', 50, 290, 980, 175, '#ffd54f', { weight: 900 }),
|
||||||
|
tx('感恩回馈 · 全场5折', 50, 520, 980, 60, '#ffffff', { weight: 900 }),
|
||||||
|
im(130, 670, 820, 460, '店铺周年庆气球拱门与礼盒,喜庆橙红色', { radius: 24 }),
|
||||||
|
sh('rect', 300, 1195, 480, 100, '#ffffff', { radius: 50 }),
|
||||||
|
tx('进店即送礼品', 300, 1222, 480, 44, '#bf360c'),
|
||||||
|
tx('活动3天 · 11月20-22日', 50, 1345, 980, 40, '#ffe0b2', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('waimai', '外卖满减', 'food', solid('#ff6f00'), [
|
||||||
|
tx('外卖满减', 50, 250, 980, 165, '#ffffff', { weight: 900 }),
|
||||||
|
tx('满25减12 · 满40减20', 50, 465, 980, 62, '#ffe0b2', { weight: 900 }),
|
||||||
|
im(140, 630, 800, 470, '外卖餐盒美食打包俯拍,橙色暖调餐饮摄影', { radius: 28 }),
|
||||||
|
sh('ellipse', 700, 1140, 300, 160, '#b71c1c'),
|
||||||
|
tx('立减', 700, 1184, 300, 50, '#ffd54f', { weight: 900 }),
|
||||||
|
tx('扫码下单 · 30分钟送达', 50, 1350, 980, 44, '#ffffff', { weight: 700 }),
|
||||||
|
]),
|
||||||
|
mk('kafei', '咖啡新品', 'food', solid('#3e2723'), [
|
||||||
|
tx('新品拿铁', 50, 250, 980, 160, '#ffab40', { weight: 900 }),
|
||||||
|
tx('第二杯半价', 50, 450, 980, 66, '#ffffff', { weight: 900 }),
|
||||||
|
im(150, 610, 780, 560, '咖啡拉花拿铁特写,木质桌面暖光,咖啡馆氛围', { radius: 32 }),
|
||||||
|
tx('每日现磨 · 门店限量', 50, 1250, 980, 48, '#ffe0b2', { weight: 700 }),
|
||||||
|
tx('活动时间:11:00 - 18:00', 50, 1350, 980, 38, '#bcaaa4', { weight: 400 }),
|
||||||
|
]),
|
||||||
|
mk('meishijie', '美食嘉年华', 'food', grad(135, '#e65100', '#ffb300'), [
|
||||||
|
sh('ellipse', -70, 240, 300, 300, 'rgba(255,255,255,0.14)'),
|
||||||
|
tx('美食嘉年华', 50, 300, 980, 155, '#ffffff', { weight: 900 }),
|
||||||
|
tx('全场5折 · 吃货狂欢', 50, 510, 980, 58, '#fff3e0', { weight: 900 }),
|
||||||
|
im(130, 660, 820, 470, '各类美食拼盘俯拍,烤串甜品饮品,热闹美食节', { radius: 24 }),
|
||||||
|
sh('rect', 340, 1200, 400, 96, '#b71c1c', { radius: 48 }),
|
||||||
|
tx('5折开吃', 340, 1224, 400, 44, '#ffd54f'),
|
||||||
|
tx('本周六日 · 中心广场', 50, 1345, 980, 40, '#ffffff', { weight: 400 }),
|
||||||
|
]),
|
||||||
];
|
];
|
||||||
|
|
||||||
// 背景快捷预设(画布"背景"区一键切换)
|
// 背景快捷预设(画布"背景"区一键切换)
|
||||||
|
|||||||
@@ -1,12 +1,21 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, ref } from 'vue';
|
import { onMounted, ref } from 'vue';
|
||||||
import { useHead } from '@vueuse/head';
|
import { useHead } from '@vueuse/head';
|
||||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
import ImgHist from '@/tools/img-hist/ImgHist.vue';
|
||||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
import { blobToB64, saveImgHist } from '@/tools/img-hist/img-hist';
|
||||||
|
|
||||||
useHead({ title: '文字生成图片 - IT-TOOLS-PRO' });
|
useHead({ title: '文字生成图片 - IT-TOOLS-PRO' });
|
||||||
|
|
||||||
const genHist = useGenHistory('text-to-image');
|
const histRef = ref<InstanceType<typeof ImgHist> | null>(null);
|
||||||
|
|
||||||
|
/** 生成结果保存到服务器历史(失败静默,不影响本地下载) */
|
||||||
|
async function persist(b64: string) {
|
||||||
|
try {
|
||||||
|
const ok = await saveImgHist({ kind: 'text-to-image', tool: 'text-to-image', b64, model: '文字生成图片', prompt: (text.value || '').slice(0, 100) });
|
||||||
|
if (ok) histRef.value?.reload();
|
||||||
|
}
|
||||||
|
catch { /* 静默 */ }
|
||||||
|
}
|
||||||
|
|
||||||
const text = ref('在线免费文字生成图片工具\nIT-TOOLS-PRO 让你更高效地工作\n如果你觉得这个工具好用,可以分享给你的小伙伴们');
|
const text = ref('在线免费文字生成图片工具\nIT-TOOLS-PRO 让你更高效地工作\n如果你觉得这个工具好用,可以分享给你的小伙伴们');
|
||||||
const format = ref<'png' | 'jpg'>('png');
|
const format = ref<'png' | 'jpg'>('png');
|
||||||
@@ -36,7 +45,7 @@ const generated = ref(false);
|
|||||||
const resultUrl = ref('');
|
const resultUrl = ref('');
|
||||||
const resultSize = ref(0);
|
const resultSize = ref(0);
|
||||||
|
|
||||||
function render(toBlob = false) {
|
function render(toBlob = false, save = false) {
|
||||||
const c = canvas.value;
|
const c = canvas.value;
|
||||||
if (!c) {
|
if (!c) {
|
||||||
return;
|
return;
|
||||||
@@ -66,13 +75,15 @@ function render(toBlob = false) {
|
|||||||
}
|
}
|
||||||
resultUrl.value = URL.createObjectURL(blob);
|
resultUrl.value = URL.createObjectURL(blob);
|
||||||
resultSize.value = blob.size;
|
resultSize.value = blob.size;
|
||||||
|
if (save) {
|
||||||
|
blobToB64(blob).then((b64) => { if (b64) persist(b64); });
|
||||||
|
}
|
||||||
}, mime, 0.92);
|
}, mime, 0.92);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function download() {
|
function download() {
|
||||||
render(true);
|
render(true);
|
||||||
genHist.add({ title: `文字生成图片: ${text.value.slice(0, 20)}`, detail: `${width.value}×${height.value} ${format.value.toUpperCase()} · ${fontSize.value}px` });
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = resultUrl.value;
|
a.href = resultUrl.value;
|
||||||
@@ -105,6 +116,7 @@ onMounted(() => {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="ti-root">
|
<div class="ti-root">
|
||||||
|
<div class="ti-main">
|
||||||
<div class="ti-panel">
|
<div class="ti-panel">
|
||||||
<div class="ti-panel-title">📝 文本内容</div>
|
<div class="ti-panel-title">📝 文本内容</div>
|
||||||
<textarea v-model="text" class="ti-textarea" rows="6" placeholder="输入要生成图片的文字,支持多行…" @input="render()" />
|
<textarea v-model="text" class="ti-textarea" rows="6" placeholder="输入要生成图片的文字,支持多行…" @input="render()" />
|
||||||
@@ -175,7 +187,7 @@ onMounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="ti-btns">
|
<div class="ti-btns">
|
||||||
<button class="ti-btn" @click="render(true)">
|
<button class="ti-btn" @click="render(true, true)">
|
||||||
🚀 生成
|
🚀 生成
|
||||||
</button>
|
</button>
|
||||||
<button class="ti-btn ti-btn-ghost" :disabled="!resultUrl" @click="download">
|
<button class="ti-btn ti-btn-ghost" :disabled="!resultUrl" @click="download">
|
||||||
@@ -197,13 +209,25 @@ onMounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<GenHistory tool="text-to-image" label="生成记录" class="mt-10px" />
|
</div>
|
||||||
|
<ImgHist ref="histRef" kind="text-to-image" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style lang="less" scoped>
|
<style lang="less" scoped>
|
||||||
.ti-root {
|
.ti-root {
|
||||||
padding-bottom: 40px;
|
padding-bottom: 40px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
.ti-main {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.ti-root { flex-direction: column; }
|
||||||
}
|
}
|
||||||
|
|
||||||
.ti-panel {
|
.ti-panel {
|
||||||
|
|||||||
@@ -56,6 +56,14 @@ export default defineConfig({
|
|||||||
VitePWA({
|
VitePWA({
|
||||||
registerType: 'autoUpdate',
|
registerType: 'autoUpdate',
|
||||||
strategies: 'generateSW',
|
strategies: 'generateSW',
|
||||||
|
workbox: {
|
||||||
|
// 后端代理路径(图片直链 /relay/ai/img/…、管理台 API /admin/…、
|
||||||
|
// /api/…、MCP)不是 SPA 路由:不加 denylist 时 NavigationRoute 会把
|
||||||
|
// 这些导航一律劫持返回 index.html —— 「新窗口打开」图片变成 404 页、
|
||||||
|
// 下载得到 HTML(2026-11-15 用户报障根因)。/mcp-connect 等 SPA 页
|
||||||
|
// 不匹配 ^/mcp(/|$) 仍走 fallback,离线能力不受影响。
|
||||||
|
navigateFallbackDenylist: [/^\/relay\//, /^\/admin\//, /^\/api\//, /^\/mcp(\/|$)/],
|
||||||
|
},
|
||||||
manifest: {
|
manifest: {
|
||||||
name: 'IT Tools',
|
name: 'IT Tools',
|
||||||
description: 'Aggregated set of useful tools for developers.',
|
description: 'Aggregated set of useful tools for developers.',
|
||||||
|
|||||||
Reference in new issue
Block a user