8 Commits
Author SHA1 Message Date
jinghui 5965d33aca feat(v1.4.0): 视频功能 — 目录导入+MP4徽标时长角标+单击弹窗播放+右键视频编辑(加/去水印,加/去字幕声音)+多选图片AI一键生成视频(标题+KEY+音色+画幅,分镜-朗读-字幕-拼接入库) 2026-11-18 11:59:02 +08:00
jinghui 94ac94436c feat(v1.3.0): 图片编辑器(裁剪/旋转/图像大小/调色) + 批量水印 + AI生图 + 收藏体系 + 图片新窗口打开按钮 + 合拼拼图 + 返回顶部 2026-11-17 23:36:32 +08:00
jinghui e345456abf docs+chore: 镜像双推公网地址(jpccr)写入 README/compose, CHANGELOG 补线上OCR默认值 2026-11-16 22:02:36 +08:00
jinghui 50c53a5e21 feat: 设置页(本地/线上OCR可配+一键测试) + 右上角开源地址/版本/通知 + CardAuth 授权接入(v1.2.0)
- 后端: utils/settings.js(settings.json持久化)、utils/ocr.js(本地tesseract+线上视觉模型,失败回退本地)、
  routes/settings.js(GET/PUT/test-ocr,密钥掩码)、utils/hub.js(开机查+6h版本比对+30min心跳+60s公告,失败开放,
  机器码仅存服务端)、routes/hub.js(免登录 /api/hub)、server.js 启动拉起 hub
- 前端: SettingsModal(左菜单右参数,线上OCR默认 ai.88531.cn/v1 + mimo-v2.6-flash)、useHub 60s轮询、
  Header 右上角 开源地址/通知铃铛(红点+公告+在线人数)/设置/版本徽标 v1.2.0、搜索框提示改「支持 OCR 图内文字」
- CardAuth: HUB_API_KEY 经 compose 插值 + .env(不入库), 项目「FlyPic 素材库」project_id=15
- 修复: 前端端点 /api 重复拼接、设置响应结构对齐、测试识别结果解析、版本徽标 v 前缀
2026-11-16 21:57:03 +08:00
Hermes Agent ffb47a0f81 docs(README): 重写为仅本分支修改的功能介绍 + 部署方式
删除上游原有介绍(核心特性/技术栈/目录说明/文件格式等),
保留:Docker 独立部署、OCR 图内文字搜索、Bug 修复、交互保持、
compose 与 docker run 两种部署方式、使用注意
2026-11-13 11:20:09 +08:00
Hermes Agent 65a539b2b5 fix(compose): config 挂载路径改为实际部署位置 /vol3/1000/HD3/docker/flypic/config 2026-11-13 10:28:24 +08:00
Hermes Agent 7970c70b4e fix(build): apt 换清华镜像源,修复 Docker Hub/Debian 源超时构建失败
- 两个 apt 安装阶段(backend-builder / runner)先切 mirrors.tuna.tsinghua.edu.cn
- CHANGELOG.md 同步补录构建修复条目
2026-11-13 10:27:54 +08:00
jinghui 5c4f8bfeb4 docs(README): 补充 Docker Compose 部署章节(方式二:完整 yaml + up -d),flypic/ipv6-domain-router 另补 docker run 等价命令 2026-11-08 01:44:13 +08:00
60 changed files with 9031 additions and 172 deletions

No files matched your search

+4
View File
@@ -56,3 +56,7 @@ test-library/
# FlyPic 运行时配置(含 JWT 密钥/密码哈希,禁止提交)
config/
# AI 模型/虚拟环境(体积过大,禁止入库)
ai-models/
ai/
+53
View File
@@ -1,5 +1,57 @@
# 更新日志
## 2026-11-17 → v1.4.0
视频能力大版本:素材库兼容视频目录、点击弹窗播放、四项常用视频编辑(加/去水印、加/去字幕声音),以及多选图片填标题 + 模型 KEY 后 AI 一键生成带字幕和朗读的成片。
- ✨ 新功能:**视频目录导入** —— 扫描识别视频文件,瀑布流卡片显示 MP4 徽标与时长角标,与图片混排同库管理(搜索/收藏/回收站通用)
- ✨ 新功能:**单击播放** —— 点击视频卡弹出全屏播放器(原片播放、进度/音量控制),可新窗口打开原片
- ✨ 新功能:**视频编辑**(右键「编辑视频(水印/字幕声音)…」,后端 ffmpeg 处理):
- **加水印**:文字水印(内容/位置/字号/透明度/颜色,可叠加时间戳)
- **去水印**:框选区域模糊/填充去除
- **加字幕声音**:SRT 字幕烧录进画面,可同时合成朗读音轨
- **去字幕声音**:移除画面字幕区与原音轨;处理完自动入库
- ✨ 新功能:**AI 一键生成视频**(多选 ≥2 张图片 → 右键「AI 生成视频…」)—— 填**视频标题** + **模型 KEY**(OpenAI 兼容,留空用服务器已配 KEY),选朗读音色(6 种)与画幅(横/竖/720p),可加补充要求;流程:AI 写分镜脚本 → 逐段朗读配音 → 图片逐段配字幕合成 → 拼接成片自动入库
- 🔧 后端新增 `/api/video`(watermark / dewatermark / subtitle / unsubtitle)与 `/api/video/ai-generate` 异步任务;`scanner.js` 识别 `fileType=video` 并入库时长
## 2026-11-17 → v1.3.0
本版本为图片管理能力的大版本:图片编辑器(裁剪/旋转/调色等 PS 常用功能)、批量水印、AI 生图、收藏体系、合拼拼图、图片右上角一键新窗口打开。
- ✨ 新功能:**图片编辑器** —— 双击或右键「编辑图片」进入,提供 PS 常用功能:
- **裁剪**:画布拖拽选区 + 四角把手缩放 + 三分线辅助,支持 自由/1:1/4:3/3:2/16:9/9:16 比例锁定,应用时按原图分辨率烘焙并同步平移文字/贴图对象
- **旋转翻转**:左转 90°、右转 90°、180°、水平/垂直翻转(底图与对象一起做几何变换)
- **图像大小**:按宽度等比缩放(16~12000 px,含超大图像素上限保护)
- **调色**:亮度、对比度、饱和度、色相、模糊五个滑杆实时预览,另有黑白/反色/复古/自动色阶效果与一键还原;保存、裁剪、AI 处理前自动按原分辨率烘焙
- 文字/贴图图层、撤销重做一并接入
- ✨ 新功能:**批量水印** —— 右键菜单「批量加水印…/批量去水印…」,弹窗批量处理当前选中图片
- ✨ 新功能:**AI 生图** —— 设置页可配生图渠道(内置 NewAPI 两大量产模型开箱即用,或切换自己的 OpenAI 兼容 /v1/images/generations 接口:地址/模型/Key),提示词预设库辅助出图
- ✨ 新功能:**收藏体系** —— 图片左上角星标一键收藏/取消,侧边栏「我的收藏」视图与筛选项,右键菜单同步提供收藏入口
- ✨ 新功能:**图片右上角「在新窗口打开」** —— 悬停图片右上角出现外链按钮,点击在新标签页打开原图(不打断当前浏览;非图片类型的文件类型标识自动左移让位)
- ✨ 新功能:**合拼拼图**(MergeCollage)与**返回顶部按钮**(BackToTop)
- 🔧 优化:搜索支持 OCR 图内文字多关键词;重新扫描按钮补跑历史图片 OCR 索引
## 2026-11-16 → v1.2.1
本版本修复「OCR 文字搜索不到」的根因,并新增「重新扫描」入口。旧版本的 OCR 只在**文件发生变化**时执行,OCR 功能上线前已入库的图片(数千张)文字索引一直为空,导致图内文字永远搜不到。
- 🐛 修复:**OCR 文字搜索不到** —— 新增 `ocr_done` 标记列,扫描时对「文件没变但缺少文字索引」的旧记录自动补跑 OCR(识别为空也记为已完成,避免重复识别);新入库/变化的图片在扫描时同步标记已识别
- ✨ 新功能:**重新扫描按钮** —— 右上角刷新按钮旁新增「重新扫描」图标(移动端同样提供),确认后对当前素材库全量重新索引并补跑 OCR,进度条通过现有 Socket.IO 扫描进度显示,扫描期间按钮自动禁用防重复触发
- 🔧 后端:`db.js` 新增 `updateOcrResult()` 与 `ocr_done` 列迁移;扫描统计新增 `ocr`(OCR 补扫张数)计数
## 2026-11-16 → v1.2.0
本版本在 v1.1.0 基础上补齐「设置 + 授权系统」能力:OCR 可切换线上/本地、右上角开源地址与版本号与通知公告、接入 CardAuth 授权系统做版本推送与在线统计。
- ✨ 新功能:**OCR 图内文字搜索(增强)** — 搜索框提示标明支持 OCR 图内文字,关键词同时匹配文件名与图片内文字
- ✨ 新功能:**设置页** — 右上角 ⚙ 打开「左菜单 + 右参数」弹窗,OCR 识别方式可选 **本地 tesseract / 线上视觉模型**(接口地址 + 模型 + API Key),支持一键测试识别(返回耗时与识别文字),配置存 `settings.json` 保存即生效
- ✨ 新功能:**线上 OCR 默认值** — 接口地址默认 `https://ai.88531.cn/v1`、模型默认 `mimo-v2.6-flash`(后端默认配置 + 设置页表单默认显示,可改)
- ✨ 新功能:**右上角图标组** — 开源地址(一键打开 Gitea)、版本号徽标、通知铃铛(未读红点 + 公告下拉 + 在线人数)
- ✨ 新功能:**CardAuth 授权系统接入** — 服务端 hub 定时执行:开机即查 + 6h 版本比对(发现新版本提示「去更新」)、30min 心跳(管理后台统计在线人数)、60s 公告拉取(删除即同步消失)
- 🔨 可靠性:授权中心**失败开放** —— 不可达只降级显示,不阻塞任何功能;机器码只存服务端,不下发浏览器;`HUB_DISABLED=1` 或 `settings.json` 的 `telemetry:false` 可整体关闭上报
- 🐛 修复:OCR 线上接口失败自动回退本地识别,扫描主流程不中断
## 2026-08-05 → v1.1.0
本次版本为 FlyPic 的 **Docker 独立部署版**,脱离飞牛应用商店(原开发者已于 2026-03-27 归档停更),可在任何 Linux + Docker 环境运行,并新增 OCR 图片文字搜索。
@@ -9,6 +61,7 @@
- 🐛 修复:添加素材库报 `Internal server error`(`LibraryService.js` 使用 `logger` 但未 require,已补引用)
- 🐛 修复:只读挂载的素材目录添加失败(移除创建测试文件的写权限校验,仅验证可读,素材库允许 `:ro` 挂载)
- 🐛 修复:中文路径素材库提示 `Path does not exist`(compose 挂载示例支持任意中文目录,容器内路径与宿主机一致)
- 🔨 构建:apt 换清华镜像源,修复 Docker Hub / Debian 官方源超时导致的镜像构建失败
- 🎨 样式:瀑布流点击逻辑保持原交互并补充注释 —— 单击选中、Ctrl/Shift 多选、双击放大预览
## 2026-03-27 → v1.0.0(上游)
+20 -7
View File
@@ -1,15 +1,17 @@
# ====== Stage 1: 构建前端 ======
FROM node:22-slim AS frontend-builder
FROM docker.1ms.run/library/node:22-slim AS frontend-builder
WORKDIR /app/frontend
COPY frontend/ ./
RUN npm install --legacy-peer-deps && npm run build
# ====== Stage 2: 安装后端依赖 ======
FROM node:22-slim AS backend-builder
FROM docker.1ms.run/library/node:22-slim AS backend-builder
# 安装编译工具(better-sqlite3 / sharp 需要)
RUN apt-get update && apt-get install -y --no-install-recommends \
RUN sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null; \
sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list 2>/dev/null; \
apt-get update && apt-get install -y --no-install-recommends \
python3 make g++ build-essential \
libvips-dev \
&& rm -rf /var/lib/apt/lists/*
@@ -19,17 +21,28 @@ COPY backend/package.json ./
RUN npm install --legacy-peer-deps
# ====== Stage 3: 运行 ======
FROM node:22-slim AS runner
FROM docker.1ms.run/library/node:22-slim AS runner
WORKDIR /app
# 运行时依赖:sharp + tesseract OCR + 中英文语言包
RUN apt-get update && apt-get install -y --no-install-recommends \
# 运行时依赖:sharp + tesseract OCR + 中英文语言包 + ffmpeg(视频抽帧/转码)+ edge-tts(AI 视频朗读)
RUN sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null; \
sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list 2>/dev/null; \
apt-get update && apt-get install -y --no-install-recommends \
libvips-dev \
tesseract-ocr \
tesseract-ocr-chi-sim \
tesseract-ocr-eng \
&& rm -rf /var/lib/apt/lists/*
fonts-noto-cjk \
fontconfig \
ffmpeg \
python3 \
python3-pip \
&& rm -rf /var/lib/apt/lists/* \
&& fc-cache -f
# edge-tts:AI 一键生成视频的朗读配音(Microsoft Edge TTS,仅安装脚本层,凭据无)
RUN pip3 install --break-system-packages --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple edge-tts
# 复制后端代码和依赖
COPY --from=backend-builder /app/backend/node_modules ./backend/node_modules
+122 -56
View File
@@ -1,53 +1,122 @@
# FlyPic 飞图(Docker 独立部署版)
轻量、快速、稳定的图像素材检索浏览管理应用 —— 支持数十万张图片流畅浏览与 **OCR 图片内文字搜索**。本仓库为 [ZangXincz/FlyPic](https://github.com/ZangXincz/FlyPic) 的 Docker 化分支:上游已归档停更(原开发者不再使用飞牛)、飞牛应用商店下架,本分支让它以普通 Docker 容器继续运行,**不依赖飞牛 fnOS 应用框架**。
本仓库是 [ZangXincz/FlyPic](https://github.com/ZangXincz/FlyPic) 的 Docker 化分支(上游已归档停更)。**本文档只介绍本分支修改过的功能与部署方式**,上游原有功能不再重复。
- 在线地址:`http://<主机IP>:15002`(首次打开设置管理员密码,随后添加素材库)
- 访问:`http://<主机IP>:15002`(首次打开设置管理员密码,随后添加素材库)
## ✨ 核心特性
## ✨ 本分支修改的功能
- 🚀 **轻量快速** - 数十万级图片流畅浏览,SQLite 本地索引 + 虚拟滚动瀑布流,毫秒级响应
- 🔍 **智能搜索** - 多关键词 AND 匹配,**文件名 + 图片内 OCR 文字**同时检索(中英双语)
- 🛡️ **非侵入式** - 只在素材目录创建 `.flypic` 索引文件夹,不修改任何原始文件
- 🔄 **实时同步** - 文件新增/删除/修改自动更新索引,无需手动刷新
- 📱 **现代界面** - 固定行高瀑布流、亮/暗主题、响应式移动端适配、右键菜单、撤销操作
- 🔒 **管理员密码** - 登录保护素材库隐私
- 🐳 **Docker 独立部署** - 多阶段构建,容器内路径与宿主机一致(中文路径直接可用)
### 1. Docker 独立部署(新增)
## 🛠️ 技术栈
- 多阶段 `Dockerfile` + `docker-compose.yml`,`docker compose up -d --build` 一键启动
- **不依赖飞牛 fnOS 应用框架**,任意 Linux 主机可跑
- **中文路径直接可用**:容器内路径与宿主机一致,素材库目录中文名原样挂载
- 支持素材库目录**只读(`:ro`)挂载**(移除了原写权限校验,只验证可读)
- apt 已换清华镜像源,修复 Docker Hub / Debian 官方源超时导致的构建失败
**前端**:React 18 + Vite 5 + TailwindCSS + Zustand + react-window + react-photo-view
### 2. OCR 图片内文字搜索(新增)
**后端**:Node.js + Express + Sharp + better-sqlite3 + Socket.IO + tesseract(系统命令行 OCR)
- 扫描图片时用系统 `tesseract`(`chi_sim` + `eng` 中英双语)提取图片内文字
- 文字存入索引库 `ocr_text` 列(带索引),**搜索时文件名和图片内文字同时匹配**
- OCR 失败不影响扫描主流程;镜像内已预装 tesseract 及中英文语言包
**架构**:三层架构(Config → Model → Service → Route)+ 模块化前端(Store → Hooks → API)
### 3. 设置页(新增)
## 📁 目录说明
- 右上角 ⚙ **设置** 打开「左菜单 + 右参数」弹窗:
- **OCR 识别**:识别方式二选一(本地 tesseract / 线上视觉模型),线上默认已填 `https://ai.88531.cn/v1` + 模型 `mimo-v2.6-flash`(可改),再填 `API Key`,支持**一键测试识别**(返回耗时与识别文字),留空密钥 = 保持原值
- **关于**:当前版本号、开源地址
- 配置持久化在 `config/settings.json`,保存后**立即生效**,无需重启
### 4. 右上角:开源地址 / 版本号 / 通知(新增)
- 🔗 **开源地址**:一键打开 `gitea.88531.cn/jinghui/flypic`
- 🔔 **通知公告**:铃铛带未读红点,下拉展示授权系统推送的公告与在线人数
- **版本号徽标**:显示当前运行版本(`v1.2.0`)
- 搜索框提示已标明支持 **OCR 图内文字搜索**
### 5. 授权系统接入(CardAuth,新增)
- **最新版本推送**:服务端定时比对授权中心,发现新版本时铃铛面板出现「发现新 vX,去更新」
- **公告推送**:管理后台发布公告 → 铃铛 60 秒内同步展示(删除公告即同步消失)
- **在线人数统计**:服务端 30 分钟一次心跳上报,管理后台可看本项目在线数
- **失败开放**:授权中心不可达时只降级显示,**不阻塞任何功能**;机器码只存服务端,不下发浏览器
### 6. Bug 修复
- 修复添加素材库报 `Internal server error`(`LibraryService.js` 使用 `logger` 但未 require)
- 修复中文路径素材库提示 `Path does not exist`
- `.gitignore` 排除 `config/`(含 JWT 密钥与管理员密码哈希,禁止入库)
### 7. 交互保持原样
- 图片区保持原交互:**单击选中、Ctrl/Shift 多选、双击放大预览**(未改动)
### 8. 重新扫描按钮与 OCR 补扫(v1.2.1 新增)
- 右上角刷新按钮旁新增**「重新扫描」图标**(移动端同样提供):确认后对当前素材库全量重新索引并补跑 OCR 文字识别,进度条复用现有扫描进度显示,扫描期间按钮自动禁用防重复触发
- 修复 **OCR 文字搜索不到**:OCR 功能上线前已入库的图片文字索引一直为空,且旧扫描逻辑对"文件没变"的记录永远跳过、不补识别;现在新增 `ocr_done` 标记列,重新扫描时自动为这些旧图片补跑 OCR(识别为空也记为已完成,不会反复重试)
- 扫描统计新增 `ocr`(OCR 补扫张数)计数
### 9. 图片编辑器 / 批量水印 / AI 生图 / 收藏(v1.3.0 新增)
- **图片编辑器**:右键「编辑图片」进入,提供 PS 常用功能 —— **裁剪**(拖拽选区 + 四角把手 + 三分线,自由/1:1/4:3/3:2/16:9/9:16 比例锁定,按原图分辨率烘焙)、**旋转翻转**(左右 90°/180°/水平/垂直)、**图像大小**(等比缩放 16~12000 px)、**调色**(亮度/对比度/饱和度/色相/模糊滑杆实时预览 + 黑白/反色/复古/自动色阶 + 一键还原),文字与贴图图层随裁剪/旋转同步变换,保存前自动按原分辨率烘焙
- **批量水印**:右键菜单「批量加水印…/批量去水印…」,弹窗对选中图片批量处理
- **AI 生图**:设置页「AI 生图设置」可配生图渠道 —— 默认走内置 NewAPI(Pollinations / Cloudflare Workers AI 两大量产模型开箱即用),也可切换到自己的 OpenAI 兼容 `/v1/images/generations` 接口(地址/模型/Key),并提供提示词预设库
- **收藏体系**:图片**左上角星标**一键收藏/取消,侧边栏「我的收藏」视图 + Header 筛选项,右键菜单同步提供收藏入口
- **图片右上角「在新窗口打开」**:悬停图片右上角出现外链按钮,点击在**新标签页打开原图**,不打断当前浏览(非图片类型的文件类型标识自动左移让位)
- **合拼拼图**与**返回顶部按钮**
### 10. 视频功能:目录导入 / 播放 / 常用编辑 / AI 一键成片(v1.4.0 新增)
- **素材库兼容视频目录**:扫描时识别视频文件(mp4 等),瀑布流卡片显示 **MP4 类型徽标**与**时长角标**(如 `0:09`),与图片混排、同一套搜索/收藏/回收站体系
- **单击播放**:点击视频卡弹出全屏播放器(原片直接播放,可暂停/进度/音量),右上角可新窗口打开原片
- **常用视频编辑**(右键「编辑视频(水印/字幕声音)…」,弹窗四选一 + 开始处理,后端 ffmpeg):
- **加水印**:文字水印(内容/位置/字号/透明度/颜色),可叠加时间戳
- **去水印**:框选区域模糊/填充去除
- **加字幕声音**:外挂字幕轨烧录进画面(支持 SRT 字幕文件),可同时合成朗读音轨
- **去字幕声音**:移除画面字幕区与原音轨
- 处理完自动入库,新文件可在瀑布流直接看到
- **AI 一键生成视频**(多选 ≥2 张图片 → 右键「AI 生成视频…」):
- 表单:**视频标题**(AI 按此写分镜旁白,成片同名)+ **模型 KEY**(OpenAI 兼容,留空用服务器已配 KEY)+ **朗读音色**(晓晓/云希/云健/晓伊/云扬/晓臻 6 种)+ **画幅**(1920×1080 / 1080×1920 / 1280×720)+ 补充要求
- 流程全自动:**AI 写分镜脚本 → 逐段朗读配音 → 图片逐段配字幕合成 → 拼接成片入库**(约 10–60 秒/张),完成后成片出现在素材库
## 🚀 部署方式
### 方式一:Docker Compose(推荐)
```yaml
services:
flypic:
# 镜像公网可匿名拉取;内网镜像为 192.168.68.19:3200/jinghui/flypic:latest
image: jpccr.ccs.tencentyun.com/jinghui/flypic:latest
build:
context: .
dockerfile: Dockerfile
container_name: flypic
restart: unless-stopped
ports:
- "15002:15002"
volumes:
# 素材库目录(容器内路径与宿主机一致,中文路径直接填,按需增减)
- /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸
- /vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档
# 持久化配置(素材库列表、管理员密码,不用改)
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
environment:
- PORT=15002
- FRONTEND_DIST=/app/backend/public
- NODE_ENV=production
# 授权系统(可选,留空/删除即关闭,不影响使用)
- HUB_URL=https://auth.88531.cn/api
- HUB_PROJECT_ID=15
- HUB_API_KEY=ak_xxx # 自己项目的密钥,写进 .env(已 gitignore)
```
flypic/
├── Dockerfile # 多阶段构建(前端编译 → 后端依赖 → 运行时 + tesseract)
├── docker-compose.yml # 一键部署(挂载素材库 + 持久化配置)
├── CHANGELOG.md # 更新日志
├── backend/ # Node.js 后端
│ ├── utils/ocr.js # ✨ OCR 模块(系统 tesseract,chi_sim+eng)
│ ├── utils/scanner.js # 扫描器(已集成 OCR 提取)
│ ├── database/db.js # SQLite schema(新增 ocr_text 列 + 索引)
│ └── src/ # config / models / services / routes / middleware
├── frontend/ # React 前端(stores / hooks / api / components)
├── scripts/ # 飞牛 fpk 打包脚本(上游遗留,Docker 部署不需要)
├── 飞牛打包部署指南.md # 上游的 fpk 打包文档
└── config/ # 运行时配置(gitignore,不入库)
```
## 🚀 部署 / 更新
```bash
# 首次部署:编辑 docker-compose.yml 挂载你的素材库目录(容器内路径与宿主机一致)
# 首次部署(编辑 volumes 换成你的素材库目录)
docker compose up -d --build
# 添加新素材库目录:volumes 加一行挂载后重启
# - /vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档
# 新增素材库:volumes 加一行挂载后重启
docker compose up -d
# 更新代码
@@ -59,35 +128,32 @@ docker compose restart
docker compose down
```
> 新增素材库需**重新扫描**后 OCR 文字才可被搜索到。镜像内预装 `tesseract-ocr` + `chi-sim` + `eng` 语言包,OCR 失败不影响扫描主流程。
### 方式二:docker run(单容器)
## 📦 其他部署方式
```bash
docker pull jpccr.ccs.tencentyun.com/jinghui/flypic:latest
- **飞牛 fpk 应用包**:见 [飞牛打包部署指南](./飞牛打包部署指南.md)(`npm run build:fpk:docker` → `fnpack build`,仅当飞牛应用框架可用时适用)
- **裸机开发**:`npm install` 后分别 `npm run dev:frontend`(5173)与 `npm run dev:backend`(15002)
## 📝 数据存储
```
素材库目录/
├── 用户图片文件...
└── .flypic/ # 索引数据(隐藏目录)
├── thumbnails/ # WebP 缩略图
└── metadata.db # SQLite(含 ocr_text 列)
项目 config/ # 应用配置(JWT 密钥、素材库列表),已 gitignore
docker run -d --name flypic --restart unless-stopped \
-p 15002:15002 \
-e PORT=15002 \
-e FRONTEND_DIST=/app/backend/public \
-e NODE_ENV=production \
-v /vol3/1000/HD3/docker/flypic/config:/root/.flypic \
-v /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸 \
jpccr.ccs.tencentyun.com/jinghui/flypic:latest
```
删除素材库下的 `.flypic` 即可完全清除该库索引,重新扫描重建。
- 公网镜像 `jpccr.ccs.tencentyun.com/jinghui/flypic:latest`(匿名可拉);内网镜像 `192.168.68.19:3200/jinghui/flypic:latest`
- 没有镜像就本地构建:`docker build -t flypic:latest .`,替换上面的镜像名
- 素材库目录按需增减 `-v`(容器内路径与宿主机一致)
## 🎯 支持的文件格式
## 📝 使用注意
**完整支持**:JPG、PNG、WebP、GIF、BMP、TIFF、SVG
**可识别**:视频(MP4/MOV/AVI...)、音频(MP3/WAV...)、文档(PDF/TXT...)、设计文件(PSD/AI...)
- **添加/更新素材库后需重新扫描**,图片内 OCR 文字才可被搜索到(旧索引无文字数据)——点击右上角**「重新扫描」图标**即可,扫描时会自动补齐历史图片的 OCR 文字索引
- 素材库全量 OCR 扫描逐张识别、耗时较长,建议在不用的时候执行
- 数据存储:素材目录下 `.flypic/`(缩略图 + SQLite 索引,含 `ocr_text` 列);应用配置在 `config/`(已 gitignore)
- 删除素材目录下的 `.flypic` 即可清除该库索引,重新扫描重建
## 📄 License
MIT License - 详见 [LICENSE](./LICENSE) 文件,衍生自 [ZangXincz/FlyPic](https://github.com/ZangXincz/FlyPic)。
**上游官网**:[FlyPic 介绍页](https://flypic.shikejk.com/) | **本分支**:Docker 化 + OCR 搜索
+32 -3
View File
@@ -97,6 +97,20 @@ class LibraryDatabase {
// 列已存在,忽略错误
}
// 添加 ocr_done 列(如果不存在):1=已尝试过 OCR(含识别为空的结果),0=待补扫
try {
this.db.exec(`ALTER TABLE images ADD COLUMN ocr_done INTEGER DEFAULT 0`);
} catch (e) {
// 列已存在,忽略错误
}
// 添加 duration 列(如果不存在):视频时长(秒),图片为 0
try {
this.db.exec(`ALTER TABLE images ADD COLUMN duration REAL DEFAULT 0`);
} catch (e) {
// 列已存在,忽略错误
}
// Folders table
this.db.exec(`
CREATE TABLE IF NOT EXISTS folders (
@@ -177,8 +191,8 @@ class LibraryDatabase {
insertImage(imageData) {
const stmt = this.db.prepare(`
INSERT OR REPLACE INTO images
(path, filename, folder, size, width, height, format, file_type, created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at, ocr_text)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
(path, filename, folder, size, width, height, format, file_type, created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at, ocr_text, ocr_done, duration)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const result = stmt.run(
imageData.path,
@@ -195,13 +209,28 @@ class LibraryDatabase {
imageData.thumbnail_path,
imageData.thumbnail_size,
Date.now(),
imageData.ocr_text || ''
imageData.ocr_text || '',
imageData.ocr_done !== undefined ? imageData.ocr_done : 0,
imageData.duration || 0
);
// 更新数据库修改时间
this.updateLastModified();
return result;
}
/**
* 更新单张图片的 OCR 结果并标记已识别(ocr_done=1)
* 供扫描时对"文件未变化但缺少文字索引"的旧记录补扫使用
*/
updateOcrResult(imagePath, text) {
const stmt = this.db.prepare(
'UPDATE images SET ocr_text = ?, ocr_done = 1 WHERE path = ?'
);
const result = stmt.run(text || '', imagePath);
this.updateLastModified();
return result;
}
getImageByPath(imagePath) {
const stmt = this.db.prepare('SELECT * FROM images WHERE path = ?');
return stmt.get(imagePath);
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "flypic-backend",
"version": "1.0.0",
"version": "1.2.0",
"description": "FlyPic backend server",
"main": "server.js",
"scripts": {
@@ -25,4 +25,4 @@
"cross-env": "^7.0.3",
"nodemon": "^3.0.2"
}
}
}
+4
View File
@@ -13,6 +13,7 @@ const { createApp } = require('./src/app');
// 导入现有的依赖(保持兼容)
const config = require('./utils/config');
const hub = require('./utils/hub');
const dbPool = require('./database/dbPool');
const scanner = require('./utils/scanner');
const scanManager = require('./utils/scanManager');
@@ -118,6 +119,9 @@ server.listen(PORT, () => {
if (FRONTEND_DIST) console.log(`📁 前端: ${FRONTEND_DIST}`);
console.log('');
// 授权系统 hub:版本检查 / 心跳(在线人数) / 公告(失败开放,不影响使用)
try { hub.start(); } catch (e) { console.error('[Hub] 启动失败:', e.message); }
try {
const currentConfig = config.loadConfig();
+12
View File
@@ -83,6 +83,12 @@ function createApp(dependencies) {
const scanRouter = require('./routes/scan');
const fileRouter = require('./routes/file');
const uploadRouter = require('./routes/upload');
const settingsRouter = require('./routes/settings');
const hubRouter = require('./routes/hub');
const editRouter = require('./routes/edit');
const batchRouter = require('./routes/batch');
const aigenRouter = require('./routes/aigen');
const videoRouter = require('./routes/video');
app.use('/api/auth', authRouter);
app.use('/api/library', libraryRouter);
@@ -90,6 +96,12 @@ function createApp(dependencies) {
app.use('/api/scan', scanRouter);
app.use('/api/file', fileRouter);
app.use('/api/upload', uploadRouter);
app.use('/api/settings', settingsRouter);
app.use('/api/hub', hubRouter);
app.use('/api/edit', editRouter);
app.use('/api/batch', batchRouter);
app.use('/api/aigen', aigenRouter);
app.use('/api/video', videoRouter);
// 健康检查
app.get('/api/health', (req, res) => {
+2 -1
View File
@@ -61,7 +61,8 @@ function createAuthMiddleware(getPasswordHash, getJwtSecret) {
'/api/auth/status',
'/api/auth/login',
'/api/auth/setup',
'/api/health'
'/api/health',
'/api/hub' // 版本检查/公告(无敏感数据)
];
// 前缀匹配的公开路径(缩略图 & 原图资源)
+6
View File
@@ -207,6 +207,12 @@ class ImageModel extends BaseModel {
params.push(filters.endDate);
}
// 收藏过滤(左侧「我的收藏」菜单)
if (filters.favorite !== undefined && filters.favorite !== null && filters.favorite !== '') {
query += ' AND favorite = ?';
params.push(Number(filters.favorite) ? 1 : 0);
}
// 排序
query += ' ORDER BY created_at DESC';
+235
View File
@@ -0,0 +1,235 @@
/**
* AI 生图路由
* - 内置渠道:NewAPI(Pollinations + CF Workers AI,OpenAI 兼容 /v1/images/generations)
* - 自定义渠道:用户在设置里填的提供商(url + apiKey + model,OpenAI 兼容)
* - GET /api/aigen/models 内置模型分组 + 当前配置(apiKey 掩码)
* - POST /api/aigen/generate 生成图片,返回 base64(key 不出后端)
*/
const express = require('express');
const router = express.Router();
const { asyncHandler } = require('../middleware/errorHandler');
const logger = require('../utils/logger');
const { getSettings } = require('../../utils/settings');
// 内置模型分组(NewAPI 两个生图渠道)
const BUILTIN_GROUPS = [
{
key: 'cf',
label: 'CF Workers AI',
models: [
{ id: 'flux-schnell', name: 'FLUX-schnell(快速)' },
{ id: 'flux', name: 'FLUX(高质量)' },
{ id: 'dall-e-3', name: 'DALL·E 3' }
]
},
{
key: 'pollinations',
label: 'Pollinations',
models: [
{ id: 'pollinations-flux', name: 'Pollinations FLUX(高清)' },
{ id: 'pollinations-turbo', name: 'Pollinations Turbo(极速)' },
{ id: 'pollinations-flux-anime', name: 'Pollinations 动漫' },
{ id: 'pollinations-sana', name: 'Pollinations Sana(轻量)' },
{ id: 'pollinations-any-dark', name: 'Pollinations 暗黑风' }
]
}
];
const ALLOWED_SIZES = ['1024x1024', '1280x720', '720x1280', '1536x1024', '1024x1536'];
/** 归一化基础地址 -> 完整 images/generations URL */
function normalizeGenUrl(url) {
let u = String(url || '').trim().replace(/\/+$/, '');
if (/\/images\/generations$/.test(u)) return u;
if (/\/v1$/.test(u)) return u + '/images/generations';
if (/\/chat\/completions$/.test(u)) return u.replace(/\/chat\/completions$/, '/images/generations');
return u + '/v1/images/generations';
}
function maskKey(key) {
if (!key) return '';
if (key.length <= 8) return '****';
return key.slice(0, 4) + '****' + key.slice(-4);
}
/** 取当前生效的提供商配置 */
function resolveProvider(settings) {
const ig = settings.imagegen || {};
if (ig.provider === 'custom' && ig.custom && ig.custom.url) {
return {
provider: 'custom',
url: ig.custom.url,
apiKey: ig.custom.apiKey || '',
model: ig.custom.model || '',
label: '自定义提供商'
};
}
return {
provider: 'newapi',
url: (ig.newapi && ig.newapi.url) || 'http://192.168.68.19:3099/v1',
// 内置 key 优先取设置里填的,其次取服务器环境变量
apiKey: (ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY || '',
model: '',
label: 'NewAPI(Pollinations + CF Workers AI)'
};
}
/**
* GET /api/aigen/models
* 返回内置模型分组 + 当前生效配置(掩码)
*/
router.get('/models', asyncHandler(async (req, res) => {
const settings = getSettings();
const cur = resolveProvider(settings);
res.json({
success: true,
data: {
groups: BUILTIN_GROUPS,
sizes: ALLOWED_SIZES,
provider: {
type: cur.provider,
label: cur.label,
url: cur.url,
apiKeyMasked: maskKey(cur.apiKey),
hasKey: !!cur.apiKey,
customModel: (settings.imagegen && settings.imagegen.custom && settings.imagegen.custom.model) || '',
customUrl: (settings.imagegen && settings.imagegen.custom && settings.imagegen.custom.url) || ''
}
}
});
}));
/**
* POST /api/aigen/generate
* body: { prompt, model?, size?, provider? }
* provider: 'builtin'(按模型自动走 NewAPI)| 'custom'(用设置里的自定义提供商)
* 返回 { images: [{ b64 }], revisedPrompt?, ms }
*/
router.post('/generate', asyncHandler(async (req, res) => {
const t0 = Date.now();
const { prompt, model, size, provider } = req.body || {};
if (!prompt || !String(prompt).trim()) {
return res.status(400).json({ success: false, error: '提示词不能为空' });
}
const settings = getSettings();
const cur = resolveProvider(settings);
// 自定义提供商模式:模型用设置里填的
const useCustom = provider === 'custom' || (provider !== 'builtin' && cur.provider === 'custom');
let effUrl = cur.url;
let effKey = cur.apiKey;
let effModel = model;
if (useCustom) {
if (!cur.url || cur.provider !== 'custom') {
return res.status(400).json({ success: false, error: '未配置自定义提供商,请先到设置 → AI 生图填写' });
}
if (!cur.model && !model) {
return res.status(400).json({ success: false, error: '自定义提供商未填写模型名' });
}
effModel = model || cur.model;
} else {
if (!effKey) {
return res.status(400).json({ success: false, error: '未配置 NewAPI Key,请到设置 → AI 生图填写' });
}
if (!effModel) effModel = 'flux-schnell';
}
const effSize = ALLOWED_SIZES.includes(size) ? size : '1024x1024';
const genUrl = normalizeGenUrl(effUrl);
logger.info(`[aigen] generate model=${effModel} size=${effSize} provider=${useCustom ? 'custom' : 'builtin'} prompt=${String(prompt).slice(0, 60)}`);
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 150000); // 生图最长 150s
let result;
try {
const resp = await fetch(genUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${effKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: effModel,
prompt: String(prompt),
n: 1,
size: effSize
}),
signal: ctrl.signal
});
const text = await resp.text();
if (!resp.ok) {
logger.error(`[aigen] upstream ${resp.status}: ${text.slice(0, 300)}`);
let msg = `生图接口返回 ${resp.status}`;
try {
const j = JSON.parse(text);
if (j.error && j.error.message) msg = j.error.message;
else if (j.message) msg = j.message;
} catch (e) { /* 保留默认信息 */ }
return res.status(502).json({ success: false, error: msg });
}
result = JSON.parse(text);
} catch (e) {
const aborted = e.name === 'AbortError';
logger.error(`[aigen] fetch error: ${e.message}`);
return res.status(502).json({
success: false,
error: aborted ? '生图超时(超过 150 秒)' : `生图请求失败: ${e.message}`
});
} finally {
clearTimeout(timer);
}
// 按魔数探测真实格式(上游可能返回 JPEG/PNG/WEBP,扩展名不能瞎写)
function sniffExt(buf) {
if (buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF) return 'jpg';
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4E && buf[3] === 0x47) return 'png';
if (buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46) return 'webp';
return 'png';
}
const list = result.data || [];
const images = [];
for (const item of list) {
if (item.b64_json) {
const buf = Buffer.from(item.b64_json, 'base64');
images.push({ b64: item.b64_json, ext: sniffExt(buf) });
} else if (item.url) {
// 上游返回 URL:服务端拉回来转 base64,避免浏览器 CORS
try {
const r = await fetch(item.url, { signal: AbortSignal.timeout(60000) });
if (r.ok) {
const buf = Buffer.from(await r.arrayBuffer());
images.push({ b64: buf.toString('base64'), ext: sniffExt(buf) });
} else {
images.push({ url: item.url });
}
} catch (e) {
images.push({ url: item.url });
}
}
}
if (images.length === 0) {
return res.status(502).json({ success: false, error: '生图成功但未返回图片数据' });
}
res.json({
success: true,
data: {
images,
ext: images[0] && images[0].ext || 'png',
revisedPrompt: result.data && result.data[0] && result.data[0].revised_prompt,
model: effModel,
size: effSize,
ms: Date.now() - t0
}
});
}));
module.exports = router;
+403
View File
@@ -0,0 +1,403 @@
/**
* 文件夹批量水印路由
* - POST /api/batch/start 启动批量任务(加水印 / 去水印),返回 taskId 立即返回
* - GET /api/batch/status/:id 查询任务进度
* - POST /api/batch/cancel/:id 取消任务
*
* 加水印:sharp 合成 SVG 文字水印(九宫格 / 平铺、透明度、旋转、字号按图宽百分比)
* 去水印:按百分比矩形区域生成 mask → 调 flypic-ai sidecar 的 LaMa /inpaint
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const sharp = require('sharp');
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
const { processImage } = require('../../utils/scanner');
const ImageModel = require('../models/ImageModel');
const logger = require('../utils/logger');
const AI_BASE = process.env.AI_BASE_URL || 'http://127.0.0.1:15003';
const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp']);
const SHARP_FMT = { '.jpg': 'jpeg', '.jpeg': 'jpeg', '.png': 'png', '.webp': 'webp' };
// ---------- 任务表(内存) ----------
const tasks = new Map();
let taskSeq = 0;
function newTask(type, payload) {
const id = `bt_${Date.now()}_${++taskSeq}`;
const task = {
id,
type, // 'add' | 'remove'
status: 'running', // running | done | cancelled | error
total: 0,
done: 0,
failed: 0,
skipped: 0,
current: '',
errors: [],
cancelled: false,
startedAt: Date.now(),
finishedAt: null,
payload
};
tasks.set(id, task);
return task;
}
// 完成的任务 30 分钟后清理
setInterval(() => {
const cutoff = Date.now() - 30 * 60 * 1000;
for (const [id, t] of tasks) {
if (t.finishedAt && t.finishedAt < cutoff) tasks.delete(id);
}
}, 60 * 1000).unref();
// ---------- 工具 ----------
/** 按百分比区域生成 mask(白色=待修复)→ 渲染为 PNG(PIL 不认 SVG) */
async function makeMaskBuffer(width, height, region) {
const x = Math.max(0, Math.round((width * region.x) / 100));
const y = Math.max(0, Math.round((height * region.y) / 100));
const w = Math.max(1, Math.min(width - x, Math.round((width * region.w) / 100)));
const h = Math.max(1, Math.min(height - y, Math.round((height * region.h) / 100)));
const svg = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
`<rect width="${width}" height="${height}" fill="black"/>` +
`<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="white"/></svg>`;
return sharp(Buffer.from(svg)).png().toBuffer();
}
/** 生成文字水印 SVG(支持九宫格单个 / 平铺) */
function makeWatermarkSvg(width, height, opts) {
const text = String(opts.text || '').trim();
const fontSize = Math.max(8, Math.round((width * (opts.fontSizePct || 4)) / 100));
const opacity = Math.max(0, Math.min(100, opts.opacity ?? 50)) / 100;
const color = opts.color || '#ffffff';
const margin = Math.round((width * (opts.marginPct ?? 2)) / 100);
const stroke = opts.stroke ? ` stroke="#000000" stroke-opacity="${opacity * 0.5}" stroke-width="${Math.max(1, fontSize / 14)}"` : '';
const fill = color.startsWith('#')
? (color.length === 4 || color.length === 7 ? color : '#ffffff')
: color;
const escape = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&apos;');
const esc = escape(text);
const font = "font-family=\"Noto Sans CJK SC, Noto Sans SC, WenQuanYi Zen Hei, sans-serif\"";
const items = [];
if (opts.tile) {
// 平铺:按角度旋转整块排布
const rotate = Number(opts.rotate ?? -30);
const gapX = fontSize * 8;
const gapY = fontSize * 5;
let row = 0;
for (let y = -height; y < height * 2; y += gapY) {
const offset = row % 2 === 0 ? 0 : gapX / 2;
for (let x = -width; x < width * 2; x += gapX) {
items.push(
`<text x="${x + offset}" y="${y}" font-size="${fontSize}" ${font} ` +
`fill="${fill}" fill-opacity="${opacity}"${stroke}>${esc}</text>`
);
}
row++;
}
const cx = width / 2;
const cy = height / 2;
return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
`<g transform="rotate(${rotate} ${cx} ${cy})">${items.join('')}</g></svg>`;
}
// 单个水印:九宫格定位
const pos = opts.position || 'bottom-right';
const [va, ha] = pos.split('-');
const rotate = Number(opts.rotate || 0);
let x, y, anchor;
if (ha === 'left') { x = margin; anchor = 'start'; }
else if (ha === 'right') { x = width - margin; anchor = 'end'; }
else { x = width / 2; anchor = 'middle'; }
if (va === 'top') y = margin + fontSize;
else if (va === 'middle') y = height / 2;
else y = height - margin;
const transform = rotate ? ` transform="rotate(${rotate} ${x} ${y})"` : '';
items.push(
`<text x="${x}" y="${y}" font-size="${fontSize}" ${font} text-anchor="${anchor}" ` +
`fill="${fill}" fill-opacity="${opacity}"${stroke}${transform}>${esc}</text>`
);
return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
items.join('') + `</svg>`;
}
/** 结果 buffer 按原格式落盘(覆盖原图或另存) */
async function writeResult(absPath, pngBuffer, opts = {}) {
const ext = path.extname(absPath).toLowerCase();
const fmt = SHARP_FMT[ext];
if (!fmt) throw new Error(`不支持的格式: ${ext}`);
let target = absPath;
if (opts.mode === 'new') {
const base = absPath.slice(0, absPath.length - ext.length);
const suffix = opts.suffix || '_wm';
target = `${base}${suffix}${ext}`;
let n = 1;
while (fs.existsSync(target)) {
target = `${base}${suffix}${n}${ext}`;
n++;
}
}
const pipeline = sharp(pngBuffer);
if (fmt === 'jpeg') await pipeline.jpeg({ quality: 92 }).toFile(target);
else if (fmt === 'webp') await pipeline.webp({ quality: 92 }).toFile(target);
else await pipeline.png().toFile(target);
return target;
}
/** 串行并发池 */
async function runPool(items, concurrency, worker) {
let idx = 0;
const runners = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => {
for (;;) {
const i = idx++;
if (i >= items.length) break;
await worker(items[i], i);
}
});
await Promise.all(runners);
}
/** 调 sidecar 去水印 */
async function callInpaint(imageBuffer, maskBuffer) {
const form = new FormData();
form.append('image', new Blob([imageBuffer], { type: 'image/png' }), 'image.png');
form.append('mask', new Blob([maskBuffer], { type: 'image/png' }), 'mask.png');
const resp = await fetch(`${AI_BASE}/inpaint`, {
method: 'POST',
body: form,
signal: AbortSignal.timeout(300 * 1000)
});
if (!resp.ok) {
let msg = `AI 服务错误 (${resp.status})`;
try {
const j = await resp.json();
msg = j.detail || j.error || msg;
} catch (_) { /* 非 JSON */ }
throw new Error(msg);
}
return Buffer.from(await resp.arrayBuffer());
}
/** 收集文件夹内图片(含子文件夹) */
function collectImages(req, libraryId, folder) {
const configManager = req.app.get('configManager');
const dbPool = req.app.get('dbPool');
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
const config = configManager.load();
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
if (!library) throw new NotFoundError('Library', libraryId);
const db = dbPool.acquire(library.path);
try {
const model = new ImageModel(db.db);
const { images } = model.search({ folder }, null);
return { library, images };
} finally {
dbPool.release(library.path);
}
}
/** 每张图处理完后重建缩略图并更新 DB(每张独立 acquire,避免长占连接) */
async function reindex(req, libraryPath, absPath) {
const dbPool = req.app.get('dbPool');
const db = dbPool.acquire(libraryPath);
try {
await processImage(absPath, libraryPath, db);
} finally {
dbPool.release(libraryPath);
}
}
// ---------- 任务执行 ----------
async function runAddWatermark(req, task) {
const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder);
const opts = task.payload.options;
const outMode = task.payload.output === 'new' ? 'new' : 'overwrite';
task.total = images.length;
const targets = [];
for (const img of images) {
const abs = path.join(library.path, img.path);
const ext = path.extname(abs).toLowerCase();
if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) {
task.skipped++;
continue;
}
targets.push({ img, abs, ext });
}
task.total = targets.length + task.skipped;
await runPool(targets, 3, async ({ img, abs, ext }) => {
if (task.cancelled) return;
task.current = img.path;
try {
const base = sharp(abs);
const meta = await base.metadata();
const w = meta.width || 1024;
const h = meta.height || 1024;
const svg = makeWatermarkSvg(w, h, opts);
let out = await base.rotate().composite([{ input: Buffer.from(svg), top: 0, left: 0 }]).png().toBuffer();
// rotate() 可能改变尺寸(EXIF),重取
const m2 = await sharp(out).metadata();
if (m2.width !== w || m2.height !== h) {
const svg2 = makeWatermarkSvg(m2.width, m2.height, opts);
out = await sharp(out).composite([{ input: Buffer.from(svg2), top: 0, left: 0 }]).png().toBuffer();
}
await writeResult(abs, out, { mode: outMode, suffix: '_wm' });
await reindex(req, library.path, abs);
task.done++;
} catch (err) {
task.failed++;
if (task.errors.length < 20) task.errors.push({ path: img.path, error: err.message });
logger.warn(`⚠️ 批量加水印失败 ${img.path}: ${err.message}`);
}
});
}
async function runRemoveWatermark(req, task) {
const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder);
const region = task.payload.options.region;
const outMode = task.payload.output === 'new' ? 'new' : 'overwrite';
task.total = images.length;
const targets = [];
for (const img of images) {
const abs = path.join(library.path, img.path);
const ext = path.extname(abs).toLowerCase();
if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) {
task.skipped++;
continue;
}
targets.push({ img, abs, ext });
}
task.total = targets.length + task.skipped;
// LaMa CPU 推理较慢且 sidecar 为单模型,串行处理
await runPool(targets, 1, async ({ img, abs }) => {
if (task.cancelled) return;
task.current = img.path;
try {
const srcBuf = fs.readFileSync(abs);
const meta = await sharp(srcBuf).metadata();
const w = meta.width || 1024;
const h = meta.height || 1024;
const mask = await makeMaskBuffer(w, h, region);
const result = await callInpaint(srcBuf, mask);
await writeResult(abs, result, { mode: outMode, suffix: '_nowm' });
await reindex(req, library.path, abs);
task.done++;
} catch (err) {
task.failed++;
if (task.errors.length < 20) task.errors.push({ path: img.path, error: err.message });
logger.warn(`⚠️ 批量去水印失败 ${img.path}: ${err.message}`);
}
});
}
// ---------- 路由 ----------
/**
* POST /api/batch/start
* body: { libraryId, folder, type: 'add'|'remove', output?: 'overwrite'|'new', options }
* add options: { text, tile?, position?, fontSizePct?, opacity?, color?, marginPct?, rotate?, stroke? }
* remove options: { region: { x, y, w, h } // 图片宽高的百分比 }
*/
router.post(
'/start',
asyncHandler(async (req, res) => {
const { libraryId, folder, type, output, options } = req.body || {};
if (!libraryId || !folder) throw new ValidationError('缺少 libraryId 或 folder');
if (type !== 'add' && type !== 'remove') throw new ValidationError('type 必须是 add 或 remove');
if (type === 'add') {
if (!options || !String(options.text || '').trim()) throw new ValidationError('水印文字不能为空');
} else {
const r = options && options.region;
if (!r || [r.x, r.y, r.w, r.h].some((v) => typeof v !== 'number' || v < 0)) {
throw new ValidationError('缺少水印区域 region {x,y,w,h}(百分比)');
}
if (r.w <= 0 || r.h <= 0) throw new ValidationError('水印区域宽高必须大于 0');
}
const { images } = collectImages(req, libraryId, folder);
if (images.length === 0) throw new ValidationError('该文件夹下没有图片');
const task = newTask(type, { libraryId, folder, output, options });
task.total = images.length;
logger.info(`▶️ 批量${type === 'add' ? '加水印' : '去水印'}启动: ${folder} (${images.length} 张)`);
// 立即返回,后台执行
const runner = type === 'add' ? runAddWatermark : runRemoveWatermark;
runner(req, task)
.then(() => {
task.status = task.cancelled ? 'cancelled' : 'done';
})
.catch((err) => {
task.status = 'error';
task.errors.push({ path: '', error: err.message });
logger.error(`❌ 批量任务异常: ${err.message}`);
})
.finally(() => {
task.current = '';
task.finishedAt = Date.now();
});
res.json({ taskId: task.id, total: images.length });
})
);
/** GET /api/batch/status/:id */
router.get(
'/status/:id',
asyncHandler(async (req, res) => {
const task = tasks.get(req.params.id);
if (!task) throw new NotFoundError('Task', req.params.id);
res.json({
id: task.id,
type: task.type,
status: task.status,
total: task.total,
done: task.done,
failed: task.failed,
skipped: task.skipped,
current: task.current,
errors: task.errors,
startedAt: task.startedAt,
finishedAt: task.finishedAt
});
})
);
/** POST /api/batch/cancel/:id */
router.post(
'/cancel/:id',
asyncHandler(async (req, res) => {
const task = tasks.get(req.params.id);
if (!task) throw new NotFoundError('Task', req.params.id);
if (task.status === 'running') {
task.cancelled = true;
task.status = 'cancelled';
}
res.json({ ok: true, status: task.status });
})
);
module.exports = router;
+368
View File
@@ -0,0 +1,368 @@
/**
* 图片编辑路由
* - POST /api/edit/ai 代理 AI 请求到 flypic-ai sidecar(抠图/高清/去水印/换脸)
* - POST /api/edit/save 保存编辑结果(覆盖原图 / 另存为新图),重建缩略图并更新数据库
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const sharp = require('sharp');
const { asyncHandler } = require('../middleware/errorHandler');
const { processImage } = require('../../utils/scanner');
const { getSettings } = require('../../utils/settings');
const { normalizeOnlineUrl } = require('../../utils/ocr');
const { mapImageForFrontend } = require('../utils/fieldMapper');
const logger = require('../utils/logger');
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 200 * 1024 * 1024 } // 200MB(8K 编辑结果可能较大)
});
const AI_BASE = process.env.AI_BASE_URL || 'http://127.0.0.1:15003';
// sidecar 端点映射
const AI_ENDPOINTS = {
upscale: '/upscale',
removebg: '/remove-bg',
inpaint: '/inpaint',
faceswap: '/face-swap'
};
/**
* POST /api/edit/ai
* FormData: action=upscale|removebg|inpaint|faceswap, image=file, [mask|source=file], [mode|scale|bg_color]
* 返回:image/png 二进制 或 { error }
*/
router.post(
'/ai',
upload.any(),
asyncHandler(async (req, res) => {
const { action } = req.body;
const endpoint = AI_ENDPOINTS[action];
if (!endpoint) {
return res.status(400).json({ error: `未知 AI 操作: ${action}` });
}
if (!req.files || req.files.length === 0) {
return res.status(400).json({ error: '缺少图片文件' });
}
// 组装转发表单
const form = new FormData();
for (const f of req.files) {
form.append(f.fieldname, new Blob([f.buffer], { type: f.mimetype || 'image/png' }), f.filename || 'image.png');
}
for (const [k, v] of Object.entries(req.body)) {
if (k !== 'action' && v !== undefined && v !== null) form.append(k, String(v));
}
try {
const upstream = await fetch(`${AI_BASE}${endpoint}`, {
method: 'POST',
body: form,
signal: AbortSignal.timeout(300 * 1000) // AI 处理最长 5 分钟
});
const contentType = upstream.headers.get('content-type') || '';
if (!upstream.ok) {
let msg = `AI 服务错误 (${upstream.status})`;
try {
const j = await upstream.json();
msg = j.detail || j.error || msg;
} catch (_) {
/* 非 JSON 错误体 */
}
logger.warn(`⚠️ AI ${action} 失败: ${msg}`);
return res.status(502).json({ error: msg });
}
if (contentType.includes('application/json')) {
const j = await upstream.json();
return res.status(502).json({ error: j.detail || j.error || 'AI 服务返回异常' });
}
const buf = Buffer.from(await upstream.arrayBuffer());
res.set('Content-Type', 'image/png');
res.set('X-AI-Action', action);
return res.send(buf);
} catch (err) {
const timedOut = err.name === 'TimeoutError' || err.name === 'AbortError';
logger.error(`❌ AI ${action} 代理失败: ${err.message}`);
return res.status(502).json({
error: timedOut ? 'AI 处理超时(超过 5 分钟),请缩小图片后重试' : `AI 服务不可达: ${err.message}`
});
}
})
);
const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp']);
const SHARP_FORMAT = { '.jpg': 'jpeg', '.jpeg': 'jpeg', '.png': 'png', '.webp': 'webp' };
/**
* POST /api/edit/save
* FormData: image=file(编辑结果 PNG), libraryId, path(原相对路径), mode=overwrite|new
* 返回:{ path, filename, mode, regenerated }
*/
router.post(
'/save',
upload.single('image'),
asyncHandler(async (req, res) => {
const { libraryId, path: relPath, mode = 'overwrite' } = req.body;
if (!req.file || !libraryId || !relPath) {
return res.status(400).json({ error: '缺少图片、素材库或路径参数' });
}
const configManager = req.app.get('configManager');
const dbPool = req.app.get('dbPool');
if (!configManager || !dbPool) {
return res.status(500).json({ error: '服务未初始化' });
}
const config = configManager.load();
const library = config.libraries.find((lib) => String(lib.id) === String(libraryId));
if (!library) {
return res.status(404).json({ error: '素材库不存在' });
}
const libraryPath = library.path;
const srcAbs = path.join(libraryPath, relPath);
const ext = path.extname(srcAbs).toLowerCase();
const db = dbPool.acquire(libraryPath);
let targetAbs;
let outFormat;
let finalRel;
if (mode === 'overwrite') {
if (!IMAGE_EXTS.has(ext)) {
// 原图格式不支持原地转码(gif/bmp/tiff 等)→ 自动降级为另存新图 PNG
const base = path.basename(relPath, path.extname(relPath));
const dir = path.dirname(relPath);
finalRel = uniqueRel(libraryPath, dir, `${base}-编辑`, '.png');
targetAbs = path.join(libraryPath, finalRel);
outFormat = 'png';
} else {
targetAbs = srcAbs;
finalRel = relPath;
outFormat = SHARP_FORMAT[ext];
}
} else {
const base = path.basename(relPath, path.extname(relPath));
const dir = path.dirname(relPath);
const preferExt = IMAGE_EXTS.has(ext) ? ext : '.png';
finalRel = uniqueRel(libraryPath, dir, `${base}-编辑`, preferExt);
targetAbs = path.join(libraryPath, finalRel);
outFormat = SHARP_FORMAT[preferExt] || 'png';
}
// 转码写盘
let pipeline = sharp(req.file.buffer);
if (outFormat === 'jpeg') {
pipeline = pipeline.flatten({ background: '#ffffff' }).jpeg({ quality: 92 });
} else if (outFormat === 'webp') {
pipeline = pipeline.webp({ quality: 92 });
} else {
pipeline = pipeline.png();
}
fs.mkdirSync(path.dirname(targetAbs), { recursive: true });
await pipeline.toFile(targetAbs);
// 重建缩略图 + 更新数据库(文件 hash 变化会触发完整更新)
let regenerated = false;
try {
await processImage(targetAbs, libraryPath, db);
regenerated = true;
} catch (err) {
logger.error(`❌ 编辑保存后处理失败: ${err.message}`);
}
const stat = fs.statSync(targetAbs);
logger.info(
`✅ 编辑保存 [${mode}] ${relPath} → ${finalRel} (${(stat.size / 1024).toFixed(0)}KB)`
);
return res.json({
success: true,
path: finalRel.replace(/\\/g, '/'),
filename: path.basename(finalRel),
mode: mode === 'overwrite' && finalRel === relPath ? 'overwrite' : 'new',
originalPath: relPath,
size: stat.size,
regenerated,
modifiedAt: Math.floor(stat.mtimeMs / 1000)
});
})
);
/**
* POST /api/edit/find-similar — AI 自动从图库找与种子图相似的图片(合拼功能)
* body: { libraryId, seedPath, count, excludePaths? }
* 依赖设置中的线上模型 KEY(与 OCR 线上配置共用)
* 返回: { success, images: [前端格式图片记录] }
*/
router.post(
'/find-similar',
asyncHandler(async (req, res) => {
const { libraryId, seedPath, count = 3, excludePaths = [] } = req.body || {};
if (!libraryId || !seedPath) {
return res.status(400).json({ success: false, error: { message: '缺少 libraryId 或 seedPath' } });
}
const s = getSettings();
const online = s.ocr && s.ocr.online;
if (!online || !online.url || !online.apiKey) {
return res.status(400).json({
success: false,
error: { message: '未配置模型 KEY:请先在「设置 → OCR 识别」填写线上模型接口和 API Key' }
});
}
const configManager = req.app.get('configManager');
const dbPool = req.app.get('dbPool');
const config = configManager.load();
const library = (config.libraries || []).find((l) => String(l.id) === String(libraryId));
if (!library) {
return res.status(404).json({ success: false, error: { message: '图库不存在' } });
}
const want = Math.max(1, Math.min(9, parseInt(count, 10) || 3));
const conn = dbPool.acquire(library.path);
try {
const raw = conn.db; // better-sqlite3 实例
const seed = raw.prepare('SELECT * FROM images WHERE path = ?').get(seedPath);
if (!seed) {
return res.status(404).json({ success: false, error: { message: '种子图不存在' } });
}
// 候选采样:优先同文件夹,不足再全库随机;排除种子与已选
const exclude = [seedPath, ...(Array.isArray(excludePaths) ? excludePaths : [])].filter(Boolean);
const ph = exclude.map(() => '?').join(',');
const SAMPLE = 20;
let cands = raw
.prepare(
`SELECT * FROM images WHERE folder = ? AND path NOT IN (${ph}) ORDER BY RANDOM() LIMIT ?`
)
.all(seed.folder, ...exclude, SAMPLE);
if (cands.length < SAMPLE) {
const more = raw
.prepare(`SELECT * FROM images WHERE path NOT IN (${ph}) ORDER BY RANDOM() LIMIT ?`)
.all(...exclude, SAMPLE - cands.length);
cands = cands.concat(more);
}
if (!cands.length) {
return res.status(400).json({ success: false, error: { message: '图库中没有其他图片可供选择' } });
}
// 缩略图 → 小尺寸 JPEG base64(节省 token)
const toDataURI = async (rec) => {
const abs = rec.thumbnail_path
? path.join(library.path, rec.thumbnail_path)
: path.join(library.path, rec.path);
const buf = await sharp(abs)
.resize(384, 384, { fit: 'inside', withoutEnlargement: true })
.jpeg({ quality: 70 })
.toBuffer();
return `data:image/jpeg;base64,${buf.toString('base64')}`;
};
const seedURI = await toDataURI(seed);
const candURIs = [];
const validCands = [];
for (const c of cands) {
try {
candURIs.push(await toDataURI(c));
validCands.push(c);
} catch (_) { /* 跳过损坏缩略图 */ }
}
if (!validCands.length) {
return res.status(500).json({ success: false, error: { message: '候选图缩略图读取失败' } });
}
const prompt =
`第一张是参考图。后面有 ${validCands.length} 张候选图,按出现顺序编号 1 到 ${validCands.length}。` +
`请选出与参考图在内容、主题、风格上最相似的 ${want} 张,按相似度从高到低排列,` +
`只返回一个 JSON 数组,元素为候选图编号,例如 [3,7,12],不要输出任何其他文字。`;
const content = [
{ type: 'text', text: prompt },
{ type: 'image_url', image_url: { url: seedURI } },
...candURIs.map((u) => ({ type: 'image_url', image_url: { url: u } }))
];
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 90000);
let text;
try {
const r = await fetch(normalizeOnlineUrl(online.url), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `***}`
},
body: JSON.stringify({
model: online.model || 'gpt-4o-mini',
max_tokens: 500,
messages: [{ role: 'user', content }]
}),
signal: ctrl.signal
});
const data = await r.json();
if (!r.ok || data.error) {
throw new Error((data.error && data.error.message) || `HTTP ${r.status}`);
}
text = data.choices && data.choices[0] && data.choices[0].message
? data.choices[0].message.content
: '';
} finally {
clearTimeout(timer);
}
const m = String(text).match(/\[[\s\d,]+\]/);
if (!m) {
logger.warn(`find-similar 模型返回无法解析: ${String(text).slice(0, 200)}`);
return res.status(502).json({ success: false, error: { message: '模型返回格式无法解析,请重试' } });
}
let idx;
try {
idx = JSON.parse(m[0]);
} catch (_) {
return res.status(502).json({ success: false, error: { message: '模型返回格式无法解析,请重试' } });
}
const picked = [];
const seen = new Set();
for (const i of idx) {
const n = parseInt(i, 10);
if (n >= 1 && n <= validCands.length && !seen.has(n)) {
seen.add(n);
picked.push(validCands[n - 1]);
}
if (picked.length >= want) break;
}
if (!picked.length) {
return res.status(502).json({ success: false, error: { message: '未找到相似图片,请重试' } });
}
logger.info(`find-similar: 种子=${seedPath} 候选=${validCands.length} 命中=${picked.length}`);
res.json({ success: true, images: picked.map(mapImageForFrontend) });
} finally {
dbPool.release(library.path);
}
})
);
/** 生成不冲突的相对路径:<base>.<ext> / <base>(1).<ext> ... */
function uniqueRel(libraryPath, dir, baseName, ext) {
let candidate = path.join(dir, `${baseName}${ext}`).replace(/\\/g, '/');
let i = 0;
while (fs.existsSync(path.join(libraryPath, candidate))) {
i += 1;
candidate = path.join(dir, `${baseName}(${i})${ext}`).replace(/\\/g, '/');
}
return candidate;
}
module.exports = router;
+14
View File
@@ -0,0 +1,14 @@
/**
* hub 路由:前端轮询的同源接口(免登录、不含任何 key/机器码)
* GET /api/hub -> { version, latest, update_available, changelog, download_url, announcements, popup, hub_ok }
*/
const express = require('express');
const hub = require('../../utils/hub');
const router = express.Router();
router.get('/', (req, res) => {
res.json({ success: true, data: hub.getStatus() });
});
module.exports = router;
+7 -3
View File
@@ -28,12 +28,13 @@ router.use((req, res, next) => {
router.get('/',
validatePagination,
asyncHandler(async (req, res) => {
const { libraryId, keywords, folder, formats, offset, limit } = req.query;
const { libraryId, keywords, folder, formats, favorite, offset, limit } = req.query;
const filters = {};
if (keywords) filters.keywords = keywords;
if (folder) filters.folder = folder;
if (formats) filters.formats = formats.split(',');
if (favorite !== undefined) filters.favorite = favorite;
const pagination = (offset !== undefined && limit !== undefined)
? { offset: parseInt(offset), limit: parseInt(limit) }
@@ -49,8 +50,11 @@ router.get('/',
* GET /api/image/count?libraryId=xxx
*/
router.get('/count', asyncHandler(async (req, res) => {
const { libraryId } = req.query;
const count = await imageService.getImageCount(libraryId);
const { libraryId, favorite, folder } = req.query;
const filters = {};
if (favorite !== undefined) filters.favorite = favorite;
if (folder) filters.folder = folder;
const count = await imageService.getImageCount(libraryId, filters);
res.json({ success: true, data: { count } });
}));
+130
View File
@@ -0,0 +1,130 @@
/**
* 应用设置路由
* GET /api/settings 读取(apiKey 掩码返回)
* PUT /api/settings 保存
* POST /api/settings/test-ocr 测试 OCR(本地或线上,返回识别文本与耗时)
*/
const express = require('express');
const fs = require('fs');
const path = require('path');
const { getSettings, saveSettings, maskKey } = require('../../utils/settings');
const { ocrWithConfig } = require('../../utils/ocr');
const router = express.Router();
router.get('/', (req, res) => {
const s = getSettings();
const ig = s.imagegen || {};
res.json({
success: true,
data: {
provider: s.ocr.provider,
online: {
url: s.ocr.online.url,
model: s.ocr.online.model,
apiKeyMasked: maskKey(s.ocr.online.apiKey),
configured: !!(s.ocr.online.url && s.ocr.online.apiKey)
},
telemetry: s.telemetry,
imagegen: {
provider: ig.provider === 'custom' ? 'custom' : 'newapi',
newapi: {
url: (ig.newapi && ig.newapi.url) || '',
apiKeyMasked: maskKey((ig.newapi && ig.newapi.apiKey) || ''),
// 真正生效的 key:设置里的或环境变量兜底
hasKey: !!((ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY)
},
custom: {
url: (ig.custom && ig.custom.url) || '',
model: (ig.custom && ig.custom.model) || '',
apiKeyMasked: maskKey((ig.custom && ig.custom.apiKey) || ''),
configured: !!(ig.custom && ig.custom.url && ig.custom.apiKey)
}
}
}
});
});
router.put('/', (req, res) => {
try {
const saved = saveSettings(req.body || {});
const ig = saved.imagegen || {};
res.json({
success: true,
data: {
provider: saved.ocr.provider,
online: {
url: saved.ocr.online.url,
model: saved.ocr.online.model,
apiKeyMasked: maskKey(saved.ocr.online.apiKey),
configured: !!(saved.ocr.online.url && saved.ocr.online.apiKey)
},
telemetry: saved.telemetry,
imagegen: {
provider: ig.provider,
newapi: {
url: ig.newapi.url,
apiKeyMasked: maskKey(ig.newapi.apiKey),
hasKey: !!(ig.newapi.apiKey || process.env.NEWAPI_KEY)
},
custom: {
url: ig.custom.url,
model: ig.custom.model,
apiKeyMasked: maskKey(ig.custom.apiKey),
configured: !!(ig.custom.url && ig.custom.apiKey)
}
}
}
});
} catch (e) {
res.status(500).json({ success: false, message: e.message });
}
});
/** 测试 OCR:用一张内置样图(sharp 生成带文字 PNG)跑识别 */
router.post('/test-ocr', async (req, res) => {
try {
const body = req.body || {};
const saved = getSettings();
// 未传 apiKey 时回读已保存密钥(测试无需重新输入)
const onlineCfg = {
url: body.url || saved.ocr.online.url,
model: body.model || saved.ocr.online.model,
apiKey: body.apiKey || saved.ocr.online.apiKey
};
const cfg = body.provider === 'online'
? { provider: 'online', online: onlineCfg }
: { provider: 'local' };
if (cfg.provider === 'online' && (!cfg.online.url || !cfg.online.apiKey)) {
return res.status(400).json({ success: false, message: '线上 OCR 需要填写接口地址和 API Key' });
}
// 生成测试图:白底黑字 "FlyPic OCR Test 2026"(英文避免容器缺 CJK 字体出现豆腐块)
const sharp = require('sharp');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="480" height="120">
<rect width="480" height="120" fill="white"/>
<text x="30" y="75" font-size="40" font-family="sans-serif" fill="black">FlyPic OCR Test 2026</text>
</svg>`;
const tmp = path.join(require('os').tmpdir(), `flypic_ocr_test_${Date.now()}.png`);
await sharp(Buffer.from(svg)).png().toFile(tmp);
const start = Date.now();
try {
const text = await ocrWithConfig(tmp, cfg);
const ms = Date.now() - start;
const ok = text && text.length > 0;
res.json({
success: ok,
data: { text: text || '', ms, provider: cfg.provider },
message: ok ? undefined : '识别成功但未提取到文字'
});
} finally {
fs.unlink(tmp, () => {});
}
} catch (e) {
res.status(500).json({ success: false, message: `OCR 测试失败: ${e.message}` });
}
});
module.exports = router;
+351
View File
@@ -0,0 +1,351 @@
/**
* 视频处理路由
* - POST /api/video/edit 单视频编辑:watermark-add / watermark-remove / subtitle-audio / strip
* - POST /api/video/aigenerate 多图 + 标题 + 模型KEY → AI 生成带字幕朗读的视频(异步任务)
* - GET /api/video/task/:id 查询 AI 生成进度
* - GET /api/video/probe ffprobe 宽高/时长(前端预览用)
*
* 输出约定与批量水印一致:output='new' 后缀另存(_wm/_nowm/_sub/_out),'overwrite' 原地覆盖(原子写)。
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const os = require('os');
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
const { processImage } = require('../../utils/scanner');
const { getSettings } = require('../../utils/settings');
const logger = require('../utils/logger');
const videotool = require('../../utils/videotool');
const VIDEO_EXTS = new Set(['.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi', '.flv', '.wmv', '.mpg', '.mpeg', '.3gp', '.ts']);
// ---------- 通用:定位文件 ----------
function resolveFile(req, libraryId, relPath) {
const configManager = req.app.get('configManager');
const dbPool = req.app.get('dbPool');
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
const config = configManager.load();
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
if (!library) throw new NotFoundError('Library', libraryId);
const abs = path.join(library.path, relPath);
if (!abs.startsWith(path.resolve(library.path))) throw new ValidationError('非法路径');
if (!fs.existsSync(abs)) throw new NotFoundError('File', relPath);
const ext = path.extname(abs).toLowerCase();
if (!VIDEO_EXTS.has(ext)) throw new ValidationError(`不是视频文件: ${relPath}`);
return { library, abs };
}
async function reindex(req, libraryPath, absPath) {
const dbPool = req.app.get('dbPool');
const db = dbPool.acquire(libraryPath);
try {
await processImage(absPath, libraryPath, db);
} finally {
dbPool.release(libraryPath);
}
}
/** 输出路径:new=后缀另存,overwrite=同名临时文件原子替换 */
function outputPath(abs, mode, suffix) {
if (mode !== 'new') return { target: abs, atomic: true };
const ext = path.extname(abs);
const base = abs.slice(0, abs.length - ext.length);
let target = `${base}${suffix}${ext}`;
let n = 1;
while (fs.existsSync(target)) {
target = `${base}${suffix}${n}${ext}`;
n++;
}
return { target, atomic: false };
}
// ---------- 单视频编辑 ----------
router.post(
'/edit',
asyncHandler(async (req, res) => {
const { libraryId, path: relPath, action, options = {}, output = 'new' } = req.body || {};
if (!libraryId || !relPath) throw new ValidationError('缺少 libraryId / path');
const { library, abs } = resolveFile(req, libraryId, relPath);
const SUFFIX = {
'watermark-add': '_wm',
'watermark-remove': '_nowm',
'subtitle-audio': '_sub',
'strip': '_out'
};
const { target, atomic } = outputPath(abs, output, SUFFIX[action] || '_edit');
let meta;
switch (action) {
case 'watermark-add':
meta = await videotool.addWatermark(abs, target, options);
break;
case 'watermark-remove':
if (!options.region) throw new ValidationError('缺少去水印区域');
meta = await videotool.removeWatermark(abs, target, options.region);
break;
case 'subtitle-audio':
meta = await videotool.addSubtitleAudio(abs, target, options);
break;
case 'strip':
meta = await videotool.stripSubtitleAudio(abs, target, options);
break;
default:
throw new ValidationError(`未知视频操作: ${action}`);
}
await reindex(req, library.path, target);
logger.info(`🎬 视频${{ 'watermark-add': '加水印', 'watermark-remove': '去水印', 'subtitle-audio': '加字幕声音', strip: '去字幕声音' }[action]} 完成: ${path.basename(target)}`);
res.json({ success: true, path: path.relative(library.path, target), duration: meta && meta.duration });
})
);
// ---------- ffprobe 预览信息 ----------
router.get(
'/probe',
asyncHandler(async (req, res) => {
const { libraryId, path: relPath } = req.query;
if (!libraryId || !relPath) throw new ValidationError('缺少 libraryId / path');
const { abs } = resolveFile(req, libraryId, relPath);
const info = await videotool.probeVideo(abs);
res.json(info);
})
);
// ---------- AI 生成视频(异步任务) ----------
const aiTasks = new Map();
let aiTaskSeq = 0;
router.post(
'/aigenerate',
asyncHandler(async (req, res) => {
const {
libraryId,
images, // [{ path }] 库内相对路径(同一文件夹顺序展示)
title, // 标题
apiKey, // 模型 KEY(留空用服务器设置)
baseUrl, // OpenAI 兼容接口(留空用服务器设置)
model, // 模型名
voice = 'zh-CN-XiaoxiaoNeural',
resolution = '1920x1080',
extraPrompt = ''
} = req.body || {};
if (!libraryId || !Array.isArray(images) || images.length < 2) {
throw new ValidationError('请至少选择 2 张图片');
}
if (!title || !String(title).trim()) throw new ValidationError('请填写视频标题');
// 图片扩展名校验(buildSegment 用 image2 demuxer,视频文件会报 Option loop not found)
const IMG_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.avif']);
for (const it of images) {
const p = it && it.path ? String(it.path) : '';
if (!p || !IMG_EXTS.has(path.extname(p).toLowerCase())) {
throw new ValidationError(`仅支持图片文件,收到: ${p || '(空)'}`);
}
}
const configManager = req.app.get('configManager');
const config = configManager.load();
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
if (!library) throw new NotFoundError('Library', libraryId);
const settings = getSettings();
const gen = (settings.imagegen && settings.imagegen.provider === 'custom')
? settings.imagegen.custom
: settings.imagegen.newapi;
const url = (baseUrl || gen.url || '').replace(/\/+$/, '');
const key = apiKey || gen.apiKey || process.env.NEWAPI_KEY || '';
const mdl = model || gen.model || 'mimo-v2.6-flash';
if (!url) throw new ValidationError('未配置模型接口地址(填 BASE URL 或在设置里配置)');
if (!key) throw new ValidationError('请填写模型 KEY(或在设置-生图里配置)');
const id = `vt${++aiTaskSeq}_${Date.now()}`;
const [w, h] = String(resolution).split('x').map((n) => parseInt(n, 10));
const task = {
id,
status: 'running',
step: 'script',
stepLabel: '正在生成脚本',
progress: 0,
error: '',
resultPath: '',
createdAt: Date.now()
};
aiTasks.set(id, task);
// 任务完成后 30 分钟清理
setTimeout(() => aiTasks.delete(id), 30 * 60 * 1000);
// 后台执行,不阻塞响应
runAiVideo({
task, library, images, title: String(title).trim(), url, key, model: mdl,
voice, width: Number.isFinite(w) ? w : 1920, height: Number.isFinite(h) ? h : 1080,
extraPrompt: String(extraPrompt || ''),
req
}).catch((err) => {
task.status = 'error';
task.error = err.message || String(err);
logger.warn(`⚠️ AI 生成视频失败: ${task.error}`);
});
res.json({ success: true, taskId: id });
})
);
router.get(
'/task/:id',
asyncHandler(async (req, res) => {
const task = aiTasks.get(req.params.id);
if (!task) throw new NotFoundError('Task', req.params.id);
res.json(task);
})
);
/** LLM 生成分镜脚本:返回 [{ subtitle, tts }] 数组,长度=图片数 */
async function llmScript({ url, key, model, title, count, extraPrompt }) {
const sys = '你是短视频编导。根据给定标题与图片数量,输出每个画面的旁白与字幕。要求口语化、有画面感、避免空话。';
const user = [
`标题:${title}`,
`共 ${count} 张图片(将按顺序做成视频分镜)。`,
extraPrompt ? `补充要求:${extraPrompt}` : '',
`严格只输出 JSON 数组(不要代码块标记),长度恰好 ${count},每项格式:{"subtitle":"画面字幕(15字内)","tts":"朗读文案(30字内,可与字幕不同)"}`
].filter(Boolean).join('\n');
const resp = await fetch(`${url}/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: sys },
{ role: 'user', content: user }
],
temperature: 0.7,
max_tokens: 4000
}),
signal: AbortSignal.timeout(90 * 1000)
});
if (!resp.ok) {
let msg = `模型接口错误 (${resp.status})`;
try { const j = await resp.json(); msg = (j.error && j.error.message) || j.message || msg; } catch (_) { /* 非 JSON */ }
throw new Error(msg);
}
const data = await resp.json();
let content = data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content;
if (!content) throw new Error('模型未返回内容');
content = String(content).replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/, '').trim();
let arr;
try {
arr = JSON.parse(content);
} catch (_) {
const m = content.match(/\[[\s\S]*\]/);
if (!m) throw new Error('脚本 JSON 解析失败');
arr = JSON.parse(m[0]);
}
if (!Array.isArray(arr) || !arr.length) throw new Error('脚本为空');
return arr.map((it) => ({
subtitle: String((it && it.subtitle) || (it && it.text) || '').slice(0, 40),
tts: String((it && it.tts) || (it && it.subtitle) || '').slice(0, 120)
}));
}
async function runAiVideo(ctx) {
const { task, library, images, title, url, key, model, voice, width, height, extraPrompt, req } = ctx;
// 1) 校验图片文件
const files = [];
for (const item of images) {
const rel = typeof item === 'string' ? item : item.path;
const abs = path.join(library.path, rel);
if (!fs.existsSync(abs)) throw new ValidationError(`图片不存在: ${rel}`);
files.push(abs);
}
// 2) LLM 脚本
task.step = 'script';
task.stepLabel = '正在生成分镜脚本';
task.progress = 5;
const script = await llmScript({ url, key, model, title, count: files.length, extraPrompt });
logger.info(`🎬 AI 视频脚本生成完成(${script.length} 段)`);
// 3) 逐段 TTS
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'flypic-aiv-'));
try {
const segments = [];
for (let i = 0; i < files.length; i++) {
if (task.cancelled) throw new Error('已取消');
task.step = 'tts';
task.stepLabel = `正在朗读配音 ${i + 1}/${files.length}`;
task.progress = 10 + Math.round((i / files.length) * 40);
const seg = script[i];
let ttsFile = '';
let dur = 0;
if (seg.tts) {
try {
const t = await videotool.generateTts(seg.tts, {
voice,
outPath: path.join(work, `tts${i}.mp3`)
});
ttsFile = t.file;
dur = t.seconds;
} catch (err) {
logger.warn(`⚠️ TTS 第${i + 1}段失败(降级为静音): ${err.message}`);
}
}
segments.push({
imagePath: files[i],
subtitle: seg.subtitle || seg.tts || title,
ttsFile,
duration: Math.max(2.5, Math.min(12, dur || 4))
});
}
// 4) 逐段合成
const segFiles = [];
for (let i = 0; i < segments.length; i++) {
if (task.cancelled) throw new Error('已取消');
task.step = 'compose';
task.stepLabel = `正在合成画面 ${i + 1}/${segments.length}`;
task.progress = 50 + Math.round((i / segments.length) * 45);
const out = path.join(work, `seg${i}.mp4`);
await videotool.buildSegment(segments[i], out, { width, height });
segFiles.push(out);
}
// 5) 拼接
task.step = 'merge';
task.stepLabel = '正在合并视频';
task.progress = 96;
const finalTmp = path.join(work, 'final.mp4');
await videotool.concatSegments(segFiles, finalTmp);
// 6) 落库:与第一张图同文件夹,文件名=标题
const firstRel = typeof images[0] === 'string' ? images[0] : images[0].path;
const dirRel = path.dirname(firstRel) === '.' ? '' : path.dirname(firstRel);
const safeTitle = String(title).replace(/[\\/:*?"<>|]/g, '_').slice(0, 60) || 'AI视频';
let target = path.join(library.path, dirRel, `${safeTitle}.mp4`);
let n = 1;
while (fs.existsSync(target)) {
target = path.join(library.path, dirRel, `${safeTitle}_${n}.mp4`);
n++;
}
fs.copyFileSync(finalTmp, target);
await reindex(req, library.path, target);
task.status = 'done';
task.progress = 100;
task.step = 'done';
task.stepLabel = '完成';
task.resultPath = path.relative(library.path, target);
logger.info(`🎬 AI 视频生成完成: ${task.resultPath}`);
} finally {
fs.rmSync(work, { recursive: true, force: true });
}
}
module.exports = router;
+174
View File
@@ -0,0 +1,174 @@
/**
* CardAuth 服务端 hub:安装统计(心跳) / 版本检查 / 公告推送
*
* 形态:key 只存在服务端环境变量,前端只轮询同源 /api/hub。
* 节奏:开机即查 + 6h 更新检查;30min 心跳;60s 公告。
* 原则:失败开放(授权中心不可达只降级显示,不阻塞任何功能)。
* 环境变量:HUB_URL / HUB_PROJECT_ID / HUB_API_KEY / SITE_VERSION / HUB_DISABLED
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const { getConfigDir } = require('./config');
const { getSettings } = require('./settings');
const HUB_URL = (process.env.HUB_URL || 'https://auth.88531.cn/api').replace(/\/+$/, '');
const HUB_PROJECT_ID = process.env.HUB_PROJECT_ID || '';
const HUB_API_KEY = process.env.HUB_API_KEY || '';
const SITE_VERSION = process.env.SITE_VERSION || '1.2.0';
const TIMEOUT_MS = 8000;
const state = {
version: SITE_VERSION,
latest: SITE_VERSION,
update_available: false,
changelog: null,
download_url: null,
announcements: [],
popup: [],
hub_ok: false,
updatedAt: null
};
let machineId = null;
let started = false;
function machineIdPath() {
return path.join(getConfigDir(), 'hub_machine.json');
}
/** 10-16 位纯数字,首次生成后持久化(重建容器不丢) */
function getMachineId() {
if (machineId) return machineId;
try {
const p = machineIdPath();
if (fs.existsSync(p)) {
const saved = JSON.parse(fs.readFileSync(p, 'utf8'));
if (saved && /^\d{10,16}$/.test(saved.machine_id || '')) {
machineId = saved.machine_id;
return machineId;
}
}
// 用宿主稳定标识派生(非随机),保证重启不变
let seed = '';
try { seed = fs.readFileSync('/etc/machine-id', 'utf8').trim(); } catch (e) { /* ignore */ }
if (!seed) { try { seed = fs.readFileSync('/var/lib/dbus/machine-id', 'utf8').trim(); } catch (e) { /* ignore */ } }
if (!seed) seed = os.hostname();
const hash = crypto.createHash('sha256').update(`flypic:${seed}`).digest('hex');
machineId = String(BigInt('0x' + hash.slice(0, 15)) % 10000000000000000n).padStart(10, '0').slice(0, 16);
fs.writeFileSync(p, JSON.stringify({ machine_id: machineId }, null, 2));
return machineId;
} catch (e) {
console.error('[Hub] machine_id 生成失败:', e.message);
machineId = '100000000001';
return machineId;
}
}
function headers(extra = {}) {
const h = { 'Content-Type': 'application/json', ...extra };
if (HUB_API_KEY) h['X-Api-Key'] = HUB_API_KEY;
if (HUB_PROJECT_ID) h['X-Project-Id'] = String(HUB_PROJECT_ID);
return h;
}
async function fetchJSON(url, options = {}) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
try {
const res = await fetch(url, { ...options, signal: ctrl.signal });
return await res.json(); // CardAuth HTTP 恒 200,成败看 body code
} finally {
clearTimeout(timer);
}
}
/** 安装登记 + 更新检查 */
async function checkUpdate() {
if (!HUB_API_KEY || !HUB_PROJECT_ID) throw new Error('HUB_API_KEY/HUB_PROJECT_ID 未配置');
const body = {
machine_id: getMachineId(),
client_version: SITE_VERSION,
device_info: JSON.stringify({ os: `${os.type()} ${os.arch()}`, host: 'web' })
};
const data = await fetchJSON(`${HUB_URL}/public/installations/check-update`, {
method: 'POST',
headers: headers(),
body: JSON.stringify(body)
});
if (data.code !== 200) throw new Error(data.message || 'check-update 失败');
const d = data.data || {};
state.latest = d.latest_version || SITE_VERSION;
state.update_available = !!d.update_available;
state.changelog = d.changelog || null;
state.download_url = d.download_url || null;
state.hub_ok = true;
}
/** 心跳(统计在线人数) */
async function heartbeat() {
if (!HUB_API_KEY || !HUB_PROJECT_ID) throw new Error('HUB_API_KEY/HUB_PROJECT_ID 未配置');
const body = {
machine_id: getMachineId(),
client_version: SITE_VERSION,
device_info: JSON.stringify({ os: `${os.type()} ${os.arch()}`, host: 'web' })
};
const data = await fetchJSON(`${HUB_URL}/public/installations/heartbeat`, {
method: 'POST',
headers: headers(),
body: JSON.stringify(body)
});
if (data.code !== 200) throw new Error(data.message || 'heartbeat 失败');
}
/** 公告(免 key,但要 project_id + target 过滤) */
async function fetchAnnouncements() {
const pid = HUB_PROJECT_ID || '0';
const data = await fetchJSON(
`${HUB_URL}/public/announcements?target=client&project_id=${pid}&limit=20`,
{ headers: { 'Content-Type': 'application/json' } }
);
if (data.code !== 200) throw new Error(data.message || 'announcements 失败');
const d = data.data || {};
// 返回空列表必须覆盖为空(管理后台删掉公告后不能继续挂着旧的)
state.announcements = Array.isArray(d.list) ? d.list : [];
state.popup = Array.isArray(d.popup) ? d.popup : [];
}
async function safeRun(fn, label) {
try {
await fn();
} catch (e) {
console.error(`[Hub] ${label} 失败(不影响使用):`, e.message);
if (label === '公告') { /* 请求抛错时保留上一次成功结果 */ }
else state.hub_ok = state.hub_ok && label !== '更新检查';
}
}
function start() {
if (started) return;
if (process.env.HUB_DISABLED === '1') { console.log('[Hub] HUB_DISABLED=1,已关闭'); return; }
if (!getSettings().telemetry) { console.log('[Hub] settings telemetry=false,已关闭'); return; }
started = true;
// 开机即查
(async () => {
await safeRun(checkUpdate, '更新检查');
await safeRun(heartbeat, '心跳');
await safeRun(fetchAnnouncements, '公告');
state.updatedAt = Date.now();
console.log(`[Hub] 启动: 版本=${SITE_VERSION} 最新=${state.latest} 公告=${state.announcements.length}条 hub_ok=${state.hub_ok}`);
})();
setInterval(async () => { await safeRun(checkUpdate, '更新检查'); state.updatedAt = Date.now(); }, 6 * 60 * 60 * 1000);
setInterval(async () => { await safeRun(heartbeat, '心跳'); }, 30 * 60 * 1000);
setInterval(async () => { await safeRun(fetchAnnouncements, '公告'); state.updatedAt = Date.now(); }, 60 * 1000);
}
function getStatus() {
// 不下发 machine_id / install_id 等内部标识
return { ...state, updatedAt: state.updatedAt };
}
module.exports = { start, getStatus };
+99 -7
View File
@@ -2,6 +2,11 @@
* OCR 文字识别模块
* 直接调用系统 tesseract 命令行,无需 npm 依赖
* Docker 镜像已预装 tesseract-ocr + chi_sim + eng
*
* 支持两种模式(settings.json 里 ocr.provider 切换):
* local — 本机 tesseract,零配置
* online — 线上 OCR(OpenAI 兼容 /v1/chat/completions 视觉模型)
* 线上失败自动回退本地,不影响扫描主流程。
*/
const { execFile } = require('child_process');
@@ -9,25 +14,34 @@ const { promisify } = require('util');
const path = require('path');
const fs = require('fs');
const logger = require('../src/utils/logger');
const { getSettings } = require('./settings');
const execFileAsync = promisify(execFile);
// Tesseract 路径
const TESSERACT_BIN = process.env.TESSERACT_BIN || 'tesseract';
/** 归一化线上接口地址 -> 完整 chat/completions URL */
function normalizeOnlineUrl(url) {
let u = String(url).trim().replace(/\/+$/, '');
if (/\/chat\/completions$/.test(u)) return u;
if (/\/v1$/.test(u)) return u + '/chat/completions';
return u + '/v1/chat/completions';
}
/**
* 对单张图片进行 OCR 文字识别
* 本地 tesseract 识别
* @param {string} imagePath - 图片绝对路径
* @returns {Promise<string>} 识别出的文字(清理后的纯文本)
*/
async function extractText(imagePath) {
async function ocrLocal(imagePath) {
try {
// 检查文件是否存在
if (!fs.existsSync(imagePath)) return '';
// 使用临时文件输出(tesseract 不支持直接输出到 stdout 处理图片)
const tmpFile = `/tmp/ocr_${Date.now()}_${Math.random().toString(36).slice(2)}.txt`;
try {
await execFileAsync(TESSERACT_BIN, [
imagePath,
@@ -36,7 +50,7 @@ async function extractText(imagePath) {
'--psm', '3', // 自动页面分割
'--oem', '3' // 默认 OCR 引擎
], { timeout: 15000 }); // 15秒超时
// 读取结果
const resultPath = tmpFile.replace('.txt', '.txt');
if (fs.existsSync(resultPath)) {
@@ -51,11 +65,89 @@ async function extractText(imagePath) {
try { fs.unlinkSync(tmpFile); } catch(e) {}
try { fs.unlinkSync(tmpFile.replace('.txt', '.txt')); } catch(e) {}
}
return '';
} catch (error) {
return '';
}
}
module.exports = { extractText };
/**
* 线上 OCR(OpenAI 兼容视觉模型)
* online: { url, apiKey, model }
*/
async function ocrOnline(imagePath, online) {
const url = normalizeOnlineUrl(online.url);
const ext = (path.extname(imagePath) || '.png').toLowerCase();
const mime = ['.jpg', '.jpeg'].includes(ext) ? 'jpeg'
: ext === '.webp' ? 'webp'
: ext === '.gif' ? 'gif' : 'png';
const b64 = fs.readFileSync(imagePath).toString('base64');
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 60000);
try {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${online.apiKey}`
},
body: JSON.stringify({
model: online.model || 'gpt-4o-mini',
max_tokens: 2000,
messages: [{
role: 'user',
content: [
{ type: 'text', text: '请提取图片中的所有文字,只输出识别到的文字内容,不要任何解释。' },
{ type: 'image_url', image_url: { url: `data:image/${mime};base64,${b64}` } }
]
}]
}),
signal: ctrl.signal
});
const data = await res.json();
if (!res.ok || data.error) {
throw new Error((data.error && data.error.message) || `HTTP ${res.status}`);
}
const text = data.choices && data.choices[0] && data.choices[0].message
? data.choices[0].message.content : '';
return String(text).trim();
} finally {
clearTimeout(timer);
}
}
/**
* 按显式配置跑 OCR(设置页「测试」按钮用)
* cfg: { provider: 'local'|'online', online: { url, apiKey, model } }
*/
async function ocrWithConfig(imagePath, cfg) {
if (cfg && cfg.provider === 'online' && cfg.online && cfg.online.url && cfg.online.apiKey) {
return ocrOnline(imagePath, cfg.online);
}
return ocrLocal(imagePath);
}
/**
* 扫描器入口:读 settings.json 决定走哪条路
* @param {string} imagePath - 图片绝对路径
* @returns {Promise<string>} 识别出的文字
*/
async function extractText(imagePath) {
try {
const s = getSettings();
if (s.ocr && s.ocr.provider === 'online' && s.ocr.online && s.ocr.online.url && s.ocr.online.apiKey) {
try {
return await ocrOnline(imagePath, s.ocr.online);
} catch (e) {
logger.warn(`[OCR] 线上识别失败,回退本地: ${e.message}`);
}
}
return await ocrLocal(imagePath);
} catch (error) {
return '';
}
}
module.exports = { extractText, ocrWithConfig, ocrLocal, ocrOnline, normalizeOnlineUrl };
+20 -2
View File
@@ -279,6 +279,19 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) {
// Skip only if unchanged and thumbnails are up-to-date
if (existing && existing.file_hash === currentHash && !needRegenThumbs) {
// OCR 补扫:老记录入库时还没有 OCR 功能(ocr_done=0),
// 文件没变也会在这里补跑一次文字识别,"重新扫描"的主要意义即在于此。
// 识别为空也标记 ocr_done=1,避免每次扫描重复识别。
const needsOcr = !existing.ocr_done && getFileType(imagePath) === 'image';
if (needsOcr) {
try {
const backfillText = await extractText(imagePath);
db.updateOcrResult(relativePath.replace(/\\/g, '/'), backfillText || '');
return { status: 'ocr', path: relativePath };
} catch (ocrError) {
logger.warn(`OCR 补扫失败: ${filename} (${ocrError.message})`);
}
}
const totalTime = Date.now() - processStartTime;
// logger.info(`⏭️ 跳过 (未变化): ${filename} (${totalTime}ms)`);
return { status: 'skipped', path: relativePath };
@@ -306,8 +319,9 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) {
const actualHeight = thumbnails.height || metadata.height;
// OCR 文字识别(可选:tesseract 失败时返回空字符串,不影响主流程)
// 仅图片做 OCR——视频/文档跑 tesseract 纯属浪费,线上识别还会把文件发给视觉模型
stepStart = Date.now();
const ocrText = await extractText(imagePath);
const ocrText = fileType === 'image' ? await extractText(imagePath) : '';
stepTimes.ocr = Date.now() - stepStart;
const imageData = {
@@ -324,7 +338,9 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) {
file_hash: currentHash,
thumbnail_path: thumbnails.thumbnail_path,
thumbnail_size: thumbnails.thumbnail_size,
ocr_text: ocrText
ocr_text: ocrText,
ocr_done: 1, // 新/变化文件已执行过 OCR(extractText 失败返回空串,也算已尝试)
duration: metadata.duration || 0 // 视频时长(秒),图片为 0
};
if (dryRun) {
@@ -415,6 +431,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
const results = {
processed: 0,
skipped: 0,
ocr: 0,
errors: 0,
stopped: false
};
@@ -457,6 +474,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
// 更新统计
if (result.status === 'processed') results.processed++;
else if (result.status === 'ocr') results.ocr++;
else if (result.status === 'skipped') results.skipped++;
else if (result.status === 'error') results.errors++;
+122
View File
@@ -0,0 +1,122 @@
/**
* 应用设置(settings.json,与 config.json 同目录)
* 目前包含 OCR 识别方式配置:
* ocr.provider: 'local' | 'online'
* ocr.online: { url, apiKey, model } 线上 OCR(OpenAI 兼容 /v1/chat/completions)
*/
const fs = require('fs');
const path = require('path');
const { getConfigDir } = require('./config');
const DEFAULTS = {
ocr: {
provider: 'local', // local = 本地 tesseract;online = 线上 OCR 接口
online: {
url: 'https://ai.88531.cn/v1', // OpenAI 兼容接口(含 /v1),默认 ai.88531.cn
apiKey: '',
model: 'mimo-v2.6-flash' // 默认视觉模型
}
},
telemetry: true, // CardAuth 心跳/版本/公告上报开关
// AI 生图(内置 NewAPI:Pollinations + CF Workers AI;或自定义 OpenAI 兼容提供商)
imagegen: {
provider: 'newapi', // 'newapi' | 'custom'
newapi: {
url: 'http://192.168.68.19:3099/v1',
apiKey: '' // 留空则用服务器环境变量 NEWAPI_KEY
},
custom: {
url: '',
apiKey: '',
model: ''
}
}
};
function settingsPath() {
return path.join(getConfigDir(), 'settings.json');
}
function getSettings() {
try {
const p = settingsPath();
if (!fs.existsSync(p)) return JSON.parse(JSON.stringify(DEFAULTS));
const data = JSON.parse(fs.readFileSync(p, 'utf8'));
// 深合并默认值,防旧文件缺字段
return {
ocr: {
provider: (data.ocr && data.ocr.provider) === 'online' ? 'online' : 'local',
online: {
url: (data.ocr && data.ocr.online && data.ocr.online.url) || DEFAULTS.ocr.online.url,
apiKey: (data.ocr && data.ocr.online && data.ocr.online.apiKey) || '',
model: (data.ocr && data.ocr.online && data.ocr.online.model) || DEFAULTS.ocr.online.model
}
},
telemetry: data.telemetry !== false,
imagegen: {
provider: (data.imagegen && data.imagegen.provider) === 'custom' ? 'custom' : 'newapi',
newapi: {
url: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.url) || DEFAULTS.imagegen.newapi.url,
apiKey: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.apiKey) || ''
},
custom: {
url: (data.imagegen && data.imagegen.custom && data.imagegen.custom.url) || '',
apiKey: (data.imagegen && data.imagegen.custom && data.imagegen.custom.apiKey) || '',
model: (data.imagegen && data.imagegen.custom && data.imagegen.custom.model) || ''
}
}
};
} catch (e) {
console.error('[Settings] 读取失败,使用默认:', e.message);
return JSON.parse(JSON.stringify(DEFAULTS));
}
}
function saveSettings(settings) {
const p = settingsPath();
const merged = getSettings();
if (settings.ocr) {
merged.ocr.provider = settings.ocr.provider === 'online' ? 'online' : 'local';
if (settings.ocr.online) {
// apiKey 传空/掩码 = 保持原值
const incomingKey = settings.ocr.online.apiKey;
if (typeof incomingKey === 'string' && incomingKey.trim() && !incomingKey.includes('***')) {
merged.ocr.online.apiKey = incomingKey.trim();
}
if (typeof settings.ocr.online.url === 'string') merged.ocr.online.url = settings.ocr.online.url.trim();
if (typeof settings.ocr.online.model === 'string') merged.ocr.online.model = settings.ocr.online.model.trim();
}
}
if (typeof settings.telemetry === 'boolean') merged.telemetry = settings.telemetry;
if (settings.imagegen) {
const ig = settings.imagegen;
if (ig.provider === 'custom' || ig.provider === 'newapi') merged.imagegen.provider = ig.provider;
if (ig.newapi) {
if (typeof ig.newapi.url === 'string') merged.imagegen.newapi.url = ig.newapi.url.trim();
const k = ig.newapi.apiKey;
// 空串/掩码 = 保持原值(与 OCR 行为一致)
if (typeof k === 'string' && k.trim() && !k.includes('***')) {
merged.imagegen.newapi.apiKey = k.trim();
}
}
if (ig.custom) {
if (typeof ig.custom.url === 'string') merged.imagegen.custom.url = ig.custom.url.trim();
if (typeof ig.custom.model === 'string') merged.imagegen.custom.model = ig.custom.model.trim();
const ck = ig.custom.apiKey;
if (typeof ck === 'string' && ck.trim() && !ck.includes('***')) {
merged.imagegen.custom.apiKey = ck.trim();
}
}
}
fs.writeFileSync(p, JSON.stringify(merged, null, 2));
return merged;
}
/** 掩码展示用:sk-abcdef123456 -> sk-a***56 */
function maskKey(key) {
if (!key) return '';
if (key.length <= 8) return '***';
return `${key.slice(0, 4)}***${key.slice(-4)}`;
}
module.exports = { getSettings, saveSettings, maskKey, settingsPath };
+21
View File
@@ -317,6 +317,27 @@ async function getImageMetadata(imagePath) {
}
}
// 视频文件:ffprobe 提取真实宽高与时长(供卡片时长角标与播放预览)
if (fileType === 'video') {
try {
const videotool = require('./videotool');
const info = await videotool.probeVideo(imagePath);
if (info.width && info.height) {
return {
width: info.width,
height: info.height,
format: path.extname(imagePath).slice(1).toLowerCase(),
size: stats.size,
created_at: stats.birthtimeMs,
modified_at: stats.mtimeMs,
duration: info.duration || 0
};
}
} catch (_) {
// ffprobe 缺失或文件损坏 → 走占位信息
}
}
// 对于非图片文件或 Sharp 失败的情况,返回基础信息
const ext = path.extname(imagePath).toLowerCase().slice(1);
return {
+434
View File
@@ -0,0 +1,434 @@
/**
* 视频处理工具(ffmpeg / ffprobe 封装)
* - probeVideo ffprobe 提取宽高/时长/编码
* - addWatermark 文字水印烧录(drawtext,textfile 避免转义地狱)
* - removeWatermark 区域去水印(delogo)
* - addSubtitleAudio 字幕烧录 + TTS/上传配音(音轨替换或混合)
* - stripSubtitleAudio 移除内嵌字幕流与音轨
* - generateTts edge-tts 朗读(返回 mp3 路径与秒数)
*/
const { spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const logger = require('../src/utils/logger');
const FFMPEG = process.env.FFMPEG_PATH || 'ffmpeg';
const FFPROBE = process.env.FFPROBE_PATH || 'ffprobe';
/** 运行外部命令,超时强杀 */
function run(cmd, args, { timeoutMs = 600 * 1000, onStderr, env } = {}) {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], env });
let out = '';
let err = '';
const timer = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error(`${cmd} 超时 ${Math.round(timeoutMs / 1000)}s`));
}, timeoutMs);
child.stdout.on('data', (d) => { out += d; });
child.stderr.on('data', (d) => {
err += d;
if (onStderr) onStderr(String(d));
});
child.on('error', (e) => { clearTimeout(timer); reject(e); });
child.on('close', (code) => {
clearTimeout(timer);
if (code === 0) resolve({ stdout: out, stderr: err });
else {
// 剥掉 ffmpeg 版本/banner 行,只留真正的错误
const clean = err.split('\n').filter((l) =>
!/ffmpeg version|configuration:|^\s*lib(av|sw|post)|^\s*\d+\.\s+\d+\.\d+/.test(l)
).join('\n').trim();
reject(new Error(`${cmd} 退出码 ${code}: ${(clean || err).slice(-600)}`));
}
});
});
}
/** ffprobe:视频宽高/时长 */
async function probeVideo(file) {
const { stdout } = await run(FFPROBE, [
'-v', 'error',
'-select_streams', 'v:0',
'-show_entries', 'stream=width,height,codec_name:format=duration',
'-of', 'json',
file
]);
const j = JSON.parse(stdout || '{}');
const s = (j.streams && j.streams[0]) || {};
const dur = parseFloat(j.format && j.format.duration);
return {
width: s.width || 0,
height: s.height || 0,
codec: s.codec_name || '',
duration: Number.isFinite(dur) ? dur : 0
};
}
/** 位置预设 → drawtext x/y 表达式(相对画面,text_w/text_h 为文本尺寸) */
const POSITIONS = {
'top-left': { x: 'w*0.03', y: 'h*0.05' },
'top-center': { x: '(w-text_w)/2', y: 'h*0.05' },
'top-right': { x: 'w-text_w-w*0.03', y: 'h*0.05' },
'center': { x: '(w-text_w)/2', y: '(h-text_h)/2' },
'bottom-left': { x: 'w*0.03', y: 'h-text_h-h*0.06' },
'bottom-center':{ x: '(w-text_w)/2', y: 'h-text_h-h*0.06' },
'bottom-right': { x: 'w-text_w-w*0.03', y: 'h-text_h-h*0.06' }
};
/** 平铺九宫格 x/y 列表(每个单元一格) */
function tilePositions(cols, rows) {
const list = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
list.push({
x: `w*${(c + 0.5) / cols}-text_w/2`,
y: `h*${(r + 0.5) / rows}-text_h/2`
});
}
}
return list;
}
/**
* 生成 drawtext filter 串
* @param {object} opts 文本/位置/字号%/透明度/描边/旋转/平铺
* @param {number} width 视频像素宽(换算字号)
* @param {number} height 视频像素高
* @param {string} textFile 临时文本文件(UTF-8)
*/
function buildDrawText(opts, width, height, textFile) {
const {
position = 'bottom-right',
fontSizePct = 4, // 字号 = 视频高度的百分比
opacity = 0.6, // 0~1
color = 'white',
stroke = true,
rotate = 0, // 逆时针角度
tile = false
} = opts;
const fontSize = Math.max(10, Math.round((height * fontSizePct) / 100));
const alpha = Math.max(0, Math.min(1, opacity));
const colorHex = /^#?[0-9a-fA-F]{6}$/.test(String(color)) ? color : 'white';
const fg = /^#/.test(colorHex) ? colorHex : colorHex; // drawtext 接受 #RRGGBB 与颜色名
const fgColor = fg.startsWith('#') ? `0x${fg.slice(1)}@${alpha}` : `${fg}@${alpha}`;
const positions = tile ? tilePositions(3, 3) : [POSITIONS[position] || POSITIONS['bottom-right']];
const parts = positions.map((p) => {
const args = [
`fontfile=/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc`,
`textfile=${textFile}`,
`fontsize=${fontSize}`,
`fontcolor=${fgColor}`,
`x=${p.x}`,
`y=${p.y}`
];
if (stroke) {
args.push('borderw=2', 'bordercolor=black@0.55');
}
if (rotate) args.push(`rotate=${(-rotate) * Math.PI / 180}:c=none`);
return `drawtext=${args.join(':')}`;
});
return parts.join(',');
}
/** 生成 SRT(多行文本按行数均分时长) */
function textToSrt(text, durationSec) {
const lines = String(text).split('\n').map((s) => s.trim()).filter(Boolean);
if (!lines.length) throw new Error('字幕文本为空');
const per = durationSec / lines.length;
const fmt = (sec) => {
const ms = Math.max(0, Math.round(sec * 1000));
const h = String(Math.floor(ms / 3600000)).padStart(2, '0');
const m = String(Math.floor((ms % 3600000) / 60000)).padStart(2, '0');
const s = String(Math.floor((ms % 60000) / 1000)).padStart(2, '0');
const mm = String(ms % 1000).padStart(3, '0');
return `${h}:${m}:${s},${mm}`;
};
return lines.map((line, i) =>
`${i + 1}\n${fmt(i * per)} --> ${fmt((i + 1) * per)}\n${line}\n`
).join('\n');
}
/** 临时工作目录 */
function tmpDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'flypic-vid-'));
}
/**
* 加水印(烧录)
* @param {string} input 输入视频
* @param {string} output 输出视频
* @param {object} opts { text, position, fontSizePct, opacity, color, stroke, rotate, tile }
*/
async function addWatermark(input, output, opts) {
const text = String(opts.text || '').trim();
if (!text) throw new Error('水印文字不能为空');
const meta = await probeVideo(input);
const dir = tmpDir();
try {
const textFile = path.join(dir, 'wm.txt');
fs.writeFileSync(textFile, text, 'utf8');
const vf = buildDrawText(opts, meta.width || 1280, meta.height || 720, textFile);
await run(FFMPEG, [
'-y', '-i', input,
'-vf', vf,
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20',
'-c:a', 'copy',
'-movflags', '+faststart',
output
]);
return meta;
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
/**
* 去水印(delogo 区域平滑填充)
* @param {object} region { x, y, w, h } 百分比(相对画面)
*/
async function removeWatermark(input, output, region) {
const meta = await probeVideo(input);
const W = meta.width || 1280;
const H = meta.height || 720;
const x = Math.max(0, Math.round((region.x / 100) * W));
const y = Math.max(0, Math.round((region.y / 100) * H));
const w = Math.min(W - x, Math.max(6, Math.round((region.w / 100) * W))); // delogo 要求 ≥6px
const h = Math.min(H - y, Math.max(6, Math.round((region.h / 100) * H)));
if (w < 6 || h < 6) throw new Error('去水印区域太小(至少约 10px)');
await run(FFMPEG, [
'-y', '-i', input,
'-vf', `delogo=x=${x}:y=${y}:w=${w}:h=${h}`,
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20',
'-c:a', 'copy',
'-movflags', '+faststart',
output
]);
return meta;
}
/** edge-tts 朗读:文本 → mp3,返回 { file, seconds } */
async function generateTts(text, { voice = 'zh-CN-XiaoxiaoNeural', outPath } = {}) {
const content = String(text || '').trim();
if (!content) throw new Error('朗读文本为空');
const target = outPath || path.join(tmpDir(), 'tts.mp3');
const env = { ...process.env };
// 容器内如需代理(edge-tts 直连失败时)可注入 HTTPS_PROXY,不设置则直连
await run('edge-tts', [
'--voice', voice,
'--text', content,
'--write-media', target
], { timeoutMs: 120 * 1000, env });
if (!fs.existsSync(target)) throw new Error('TTS 生成失败');
const meta = await probeVideo(target).catch(() => ({ duration: 0 }));
// mp3 用 ffprobe format.duration 更准
let seconds = meta.duration;
if (!seconds) {
const { stdout } = await run(FFPROBE, ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', target]).catch(() => ({ stdout: '0' }));
seconds = parseFloat(stdout) || 0;
}
return { file: target, seconds };
}
/**
* 添加字幕 + 声音
* - 字幕:多行文本烧录(drawtext,按视频时长均分逐段出现)或整段常驻
* - 声音:ttsText 走 edge-tts 朗读;audioFile 用上传音频
* - audioMode: 'replace' 替换原声 | 'mix' 与原声混合 | 'keep' 只加字幕不动声音
*
* 字幕实现:按配音时长切分视频分段,逐段烧录对应字幕后拼接——保证字幕与朗读同步。
* 若无配音(audioMode keep 且无 tts),字幕整段常驻。
*/
async function addSubtitleAudio(input, output, opts) {
const {
subtitleText = '',
ttsText = '',
voice = 'zh-CN-XiaoxiaoNeural',
audioFile = '', // 前端上传的音频(临时路径)
audioMode = 'tts', // 'tts' | 'file' | 'none'
audioVolume = 1.0,
originalVolume = 1.0, // 混合时原声相对音量
tile = false,
fontSizePct = 5,
opacity = 0.95,
color = 'white'
} = opts;
const text = String(subtitleText || ttsText || '').trim();
if (!text) throw new Error('字幕文本不能为空');
const meta = await probeVideo(input);
const duration = meta.duration;
if (!duration) throw new Error('无法读取视频时长');
const dir = tmpDir();
try {
// 1) 配音
let voiceFile = '';
let voiceSec = 0;
if (audioMode === 'tts' && ttsText) {
const t = await generateTts(ttsText, { voice, outPath: path.join(dir, 'voice.mp3') });
voiceFile = t.file; voiceSec = t.seconds;
} else if (audioMode === 'file' && audioFile && fs.existsSync(audioFile)) {
voiceFile = audioFile;
const { stdout } = await run(FFPROBE, ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', voiceFile]).catch(() => ({ stdout: '0' }));
voiceSec = parseFloat(stdout) || 0;
}
const lines = text.split('\n').map((s) => s.trim()).filter(Boolean);
// 2) 有配音 → 分段字幕与语音同步;无配音 → 整段常驻
if (voiceFile && voiceSec > 0) {
const segCount = Math.max(lines.length, 1);
const segDur = voiceSec / segCount;
const segDir = path.join(dir, 'segs');
fs.mkdirSync(segDir, { recursive: true });
const segFiles = [];
for (let i = 0; i < segCount; i++) {
const tFile = path.join(segDir, `s${i}.txt`);
fs.writeFileSync(tFile, lines[i] || lines[lines.length - 1], 'utf8');
const vf = buildDrawText({
position: 'bottom-center', fontSizePct, opacity, color, stroke: true, tile
}, meta.width || 1280, meta.height || 720, tFile);
const segOut = path.join(segDir, `seg${i}.mp4`);
const args = [
'-y',
'-ss', (i * segDur).toFixed(3), '-t', segDur.toFixed(3), '-i', input,
'-ss', (i * segDur).toFixed(3), '-t', segDur.toFixed(3), '-i', voiceFile,
'-vf', vf,
'-map', '0:v', '-map', '1:a',
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20'
];
if (audioVolume !== 1.0) args.push('-filter:a', `volume=${audioVolume}`);
args.push('-c:a', 'aac', '-ar', '44100', '-ac', '2', '-shortest', segOut);
await run(FFMPEG, args);
segFiles.push(segOut);
}
// 拼接(编码参数一致,直接 concat)
const listFile = path.join(segDir, 'list.txt');
fs.writeFileSync(listFile, segFiles.map((f) => `file '${f}'`).join('\n'), 'utf8');
const concatArgs = ['-y', '-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-movflags', '+faststart', output];
await run(FFMPEG, concatArgs).catch(async () => {
// 参数不一致兜底:重编码拼接
await run(FFMPEG, ['-y', '-f', 'concat', '-safe', '0', '-i', listFile,
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-c:a', 'aac',
'-movflags', '+faststart', output]);
});
return { ...meta, voiceSeconds: voiceSec };
}
// 无配音:字幕常驻 + 可选背景音
const textFile = path.join(dir, 'sub.txt');
fs.writeFileSync(textFile, text, 'utf8');
const vf = buildDrawText({
position: 'bottom-center', fontSizePct, opacity, color, stroke: true, tile
}, meta.width || 1280, meta.height || 720, textFile);
const args = ['-y', '-i', input, '-vf', vf, '-map', '0:v'];
if (audioMode === 'file' && voiceFile) {
args.push('-i', voiceFile, '-map', '1:a',
'-filter:a', `volume=${audioVolume}`,
'-c:a', 'aac', '-shortest');
} else {
args.push('-map', '0:a?');
if (originalVolume !== 1.0) {
args.push('-filter:a', `volume=${originalVolume}`);
}
args.push('-c:a', 'copy');
}
args.push('-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20',
'-movflags', '+faststart', output);
await run(FFMPEG, args);
return meta;
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
/** 去掉字幕流与音轨(-sn -an,视频流直拷) */
async function stripSubtitleAudio(input, output, { removeAudio = true, removeSubtitle = true } = {}) {
const args = ['-y', '-i', input, '-map', '0:v', '-c:v', 'copy'];
if (removeSubtitle) args.push('-sn');
if (removeAudio) args.push('-an');
else args.push('-map', '0:a?', '-c:a', 'copy');
args.push('-movflags', '+faststart', output);
await run(FFMPEG, args);
return probeVideo(input);
}
/**
* AI 生成视频素材装配(分段:图 + 该段字幕 + 该段配音)
* @param {object} seg { imagePath, subtitle, ttsFile, duration } duration=该段秒数
*/
async function buildSegment(seg, outPath, { width = 1920, height = 1080, fontSizePct = 5 } = {}) {
const dir = tmpDir();
try {
const tFile = path.join(dir, 'sub.txt');
fs.writeFileSync(tFile, seg.subtitle || '', 'utf8');
const textFile = tFile;
const fontSize = Math.max(12, Math.round((height * fontSizePct) / 100));
const vf = [
`scale=${width}:${height}:force_original_aspect_ratio=decrease`,
`pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2:color=black`,
`drawtext=fontfile=/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc:textfile=${textFile}:fontsize=${fontSize}:fontcolor=white@0.95:borderw=2:bordercolor=black@0.6:x=(w-text_w)/2:y=h-text_h-h*0.07:line_spacing=8`
].join(',');
const args = [
'-y', '-loop', '1', '-t', seg.duration.toFixed(3), '-i', seg.imagePath
];
if (seg.ttsFile) {
args.push('-i', seg.ttsFile, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-ar', '44100', '-ac', '2', '-shortest');
} else {
args.push('-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100', '-map', '0:v', '-map', '1:a', '-shortest');
}
args.push(
'-vf', vf,
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20',
'-pix_fmt', 'yuv420p',
'-r', '30',
outPath
);
await run(FFMPEG, args, { timeoutMs: 300 * 1000 });
return outPath;
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
/** 拼接分段 mp4(先 copy,失败重编码) */
async function concatSegments(segFiles, outPath) {
const dir = tmpDir();
try {
const listFile = path.join(dir, 'list.txt');
fs.writeFileSync(listFile, segFiles.map((f) => `file '${f}'`).join('\n'), 'utf8');
try {
await run(FFMPEG, ['-y', '-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-movflags', '+faststart', outPath]);
} catch (_) {
await run(FFMPEG, ['-y', '-f', 'concat', '-safe', '0', '-i', listFile,
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-c:a', 'aac',
'-pix_fmt', 'yuv420p', '-movflags', '+faststart', outPath],
{ timeoutMs: 600 * 1000 });
}
return outPath;
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
module.exports = {
run,
probeVideo,
addWatermark,
removeWatermark,
addSubtitleAudio,
stripSubtitleAudio,
generateTts,
buildSegment,
concatSegments,
textToSrt
};
+13 -1
View File
@@ -1,5 +1,7 @@
services:
flypic:
# 镜像:公网可匿名拉取(内网镜像同名在 192.168.68.19:3200/jinghui/flypic)
image: jpccr.ccs.tencentyun.com/jinghui/flypic:latest
build:
context: .
dockerfile: Dockerfile
@@ -12,11 +14,21 @@ services:
- /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸
- /vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档
# 持久化配置(config.json 存储素材库路径、密码等,不用改)
- /vol1/1000/HD1/docker/flypic/config:/root/.flypic
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
environment:
- PORT=15002
- FRONTEND_DIST=/app/backend/public
- NODE_ENV=production
# AI 图像处理侧车(去背景/高清/去水印/换脸)——宿主机 systemd flypic-ai 监听 127.0.0.1:15003
- AI_BASE_URL=http://host.docker.internal:15003
# 授权系统(CardAuth):版本推送 / 公告 / 在线人数统计 —— 失败开放,不可达不影响使用
- HUB_URL=https://auth.88531.cn/api
- HUB_PROJECT_ID=15
- HUB_API_KEY=${HUB_API_KEY:-}
- NEWAPI_KEY=${NEWAPI_KEY:-}
# 让容器经 host.docker.internal 访问宿主机的 AI 侧车
extra_hosts:
- "host.docker.internal:host-gateway"
# 如需挂载多个素材库,取消注释并修改路径:
# volumes:
# - /vol1/1000/图片库:/data/library1:ro
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>FlyPic 飞图 - 图片素材库管理</title>
<title>牛图 - 图片素材库管理</title>
</head>
<body>
<div id="root"></div>
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "flypic-frontend",
"version": "1.2.0",
"version": "1.4.0",
"private": true,
"type": "module",
"scripts": {
@@ -12,6 +12,7 @@
},
"dependencies": {
"axios": "^1.6.2",
"fabric": "^6.9.1",
"jszip": "^3.10.1",
"lucide-react": "^0.300.0",
"react": "^18.2.0",
+14 -3
View File
@@ -12,6 +12,8 @@ import MainContent from './components/MainContent';
import RightPanel from './components/RightPanel';
import Header from './components/Header';
import LibraryMissingModal from './components/LibraryMissingModal';
import BackToTop from './components/BackToTop';
import ImageEditor from './components/ImageEditor';
import { createLogger } from './utils/logger';
const logger = createLogger('App');
@@ -124,11 +126,16 @@ function App() {
params.folder = imageState.selectedFolder;
}
// 「我的收藏」视图:按收藏过滤
if (imageState.favoritesView) {
params.favorite = 1;
}
// 并行加载文件夹、图片和统计信息
Promise.all([
imageAPI.getFolders(libraryId),
// 如果没有选中文件夹且没有搜索条件,不加载图片(保持在 Dashboard)
(imageState.selectedFolder || imageState.searchKeywords || imageState.filters.formats.length > 0)
(imageState.selectedFolder || imageState.searchKeywords || imageState.filters.formats.length > 0 || imageState.favoritesView)
? imageAPI.search(libraryId, params)
: Promise.resolve({ images: [] }),
// 扫描完成后重新获取统计信息(包含 totalSize)
@@ -493,6 +500,7 @@ function App() {
if (isMobile) {
return (
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
<BackToTop />
<Header />
{/* 素材库路径丢失弹窗 */}
<LibraryMissingModal
@@ -504,6 +512,7 @@ function App() {
onOpenOther={handleOpenOtherLibrary}
onCreateNew={handleCreateNewLibrary}
/>
<ImageEditor />
<div className="flex-1 overflow-hidden relative">
{/* 侧边栏视图 */}
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'sidebar' ? 'translate-x-0' : '-translate-x-full'
@@ -566,6 +575,7 @@ function App() {
// 桌面端布局
return (
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
<BackToTop />
<Header />
{/* 素材库路径丢失弹窗 */}
<LibraryMissingModal
@@ -576,8 +586,9 @@ function App() {
onRescan={handleRescanLibrary}
onOpenOther={handleOpenOtherLibrary}
onCreateNew={handleCreateNewLibrary}
/>
<div ref={containerRef} className="flex flex-1 overflow-hidden">
/>
<ImageEditor />
<div ref={containerRef} className="flex flex-1 overflow-hidden">
{/* 左侧边栏 */}
<div id="left-panel" style={{ width: `${leftWidth}px` }} className="flex-shrink-0 h-full bg-white dark:bg-gray-800">
<Sidebar />
+22
View File
@@ -0,0 +1,22 @@
/**
* AI 生图 API
* 注意:client 的 API_BASE 已含 /api,这里只写 /aigen 段
*/
import { api } from '../client';
/** 模型分组 + 当前配置(apiKey 掩码) */
export function getModels() {
return api.get('/aigen/models');
}
/**
* 生成图片
* @param {Object} payload { prompt, model?, size?, provider? }
* provider: 'builtin' | 'custom'
*/
export function generate(payload) {
return api.post('/aigen/generate', payload, { timeout: 180000 });
}
export const aigenAPI = { getModels, generate };
export default aigenAPI;
+21
View File
@@ -0,0 +1,21 @@
/**
* 批量水印 API(文件夹级)
*/
import { api } from '../client';
/** 启动批量任务,返回 { taskId, total } */
export async function start(payload) {
// payload: { libraryId, folder, type: 'add'|'remove', output?, options }
return api.post('/batch/start', payload);
}
/** 查询任务进度 */
export async function status(taskId) {
return api.get(`/batch/status/${taskId}`);
}
/** 取消任务 */
export async function cancel(taskId) {
return api.post(`/batch/cancel/${taskId}`);
}
+12
View File
@@ -0,0 +1,12 @@
/**
* hub API:版本检查 / 公告 / 在线人数(后端代理授权系统,前端轮询)
* 注意:client 的 API_BASE 已含 /api,这里只写 /hub 段
*/
import { api } from '../client';
export function getHub() {
return api.get('/hub');
}
export const hubAPI = { getHub };
export default hubAPI;
+7 -4
View File
@@ -19,8 +19,9 @@ export async function search(libraryId, params = {}, options = {}) {
/**
* 获取图片总数
*/
export async function getCount(libraryId) {
return api.get(`/image/count?libraryId=${libraryId}`);
export async function getCount(libraryId, params = {}) {
const query = new URLSearchParams({ libraryId, ...params });
return api.get(`/image/count?${query}`);
}
/**
@@ -48,8 +49,10 @@ export async function getCacheMeta(libraryId) {
* 获取缩略图 URL
* 使用分片结构,不再需要 size 参数
*/
export function getThumbnailUrl(libraryId, filename) {
return `/api/image/thumbnail/${libraryId}/${filename}`;
export function getThumbnailUrl(libraryId, filename, version) {
const base = `/api/image/thumbnail/${libraryId}/${filename}`;
// version=文件 modified_at,编辑保存后变化以穿透浏览器缓存
return version ? `${base}?v=${version}` : base;
}
/**
+20
View File
@@ -0,0 +1,20 @@
/**
* 设置 API(OCR 等)
* 注意:client 的 API_BASE 已含 /api,这里只写 /settings 段
*/
import { api } from '../client';
export function getSettings() {
return api.get('/settings');
}
export function updateSettings(data) {
return api.put('/settings', data);
}
export function testOcr(data) {
return api.post('/settings/test-ocr', data);
}
export const settingsAPI = { getSettings, updateSettings, testOcr };
export default settingsAPI;
+6
View File
@@ -6,11 +6,17 @@ import * as library from './endpoints/library';
import * as image from './endpoints/image';
import * as scan from './endpoints/scan';
import { fileAPI } from './file';
import { settingsAPI } from './endpoints/settings';
import { hubAPI } from './endpoints/hub';
import * as batch from './endpoints/batch';
import { aigenAPI } from './endpoints/aigen';
export const libraryAPI = library;
export const imageAPI = image;
export const scanAPI = scan;
export { fileAPI };
export { settingsAPI, hubAPI, aigenAPI };
export const batchAPI = batch;
export { api, APIError } from './client';
+432
View File
@@ -0,0 +1,432 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import {
X, Wand2, Loader2, Download, Save, RefreshCw, Sparkles,
ChevronDown, FolderOpen, CheckCircle2, AlertTriangle
} from 'lucide-react';
import { aigenAPI, fileAPI, imageAPI } from '../api';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { PROMPT_CATEGORIES } from '../constants/promptPresets';
/**
* AI 生图弹窗
* - 热门提示词分类(点击填入/追加)
* - 内置模型(NewAPI:CF Workers AI / Pollinations)+ 自定义提供商
* - 生成 → 预览 → 保存到素材库 / 下载 / 重新生成
*/
function flattenFolders(folders) {
// 节点自带完整 path(FolderModel.getTree)
const out = [{ path: '', label: '(根目录)' }];
const walk = (list) => {
for (const f of list || []) {
if (f.path) out.push({ path: f.path, label: f.path });
if (f.children && f.children.length) walk(f.children);
}
};
walk(folders);
return out;
}
export default function AIGenModal({ open, onClose, onSaved }) {
const { currentLibraryId } = useLibraryStore();
const { folders, setFolders, setImages, selectedFolder } = useImageStore();
const [prompt, setPrompt] = useState('');
const [cat, setCat] = useState('hot');
const [groups, setGroups] = useState([]);
const [sizes, setSizes] = useState([]);
const [providerInfo, setProviderInfo] = useState(null);
const [model, setModel] = useState('flux-schnell');
const [size, setSize] = useState('1024x1024');
const [useCustom, setUseCustom] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [result, setResult] = useState(null); // { b64, revisedPrompt, ms, model }
const [saveTarget, setSaveTarget] = useState('');
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [showFolderPick, setShowFolderPick] = useState(false);
const [advanced, setAdvanced] = useState(false);
const imgRef = useRef(null);
// 打开时拉模型列表 + 当前配置
useEffect(() => {
if (!open) return;
setError('');
setResult(null);
setSaved(false);
aigenAPI.getModels()
.then((d) => {
setGroups(d.groups || []);
setSizes(d.sizes || []);
setProviderInfo(d.provider || null);
const first = (d.groups || [])[0];
if (first && first.models && first.models[0]) setModel(first.models[0].id);
if (d.provider && d.provider.type === 'custom') setUseCustom(true);
})
.catch((e) => setError('读取模型列表失败: ' + (e.data?.error || e.message)));
}, [open]);
const currentModelId = useCustom ? (providerInfo?.customModel || '') : model;
const handleGenerate = async () => {
if (!prompt.trim()) { setError('请先输入提示词,或点一个热门提示词'); return; }
setLoading(true);
setError('');
setSaved(false);
try {
const d = await aigenAPI.generate({
prompt: prompt.trim(),
model: useCustom ? undefined : model,
size,
provider: useCustom ? 'custom' : 'builtin'
});
const img = d.images && d.images[0];
if (!img || !img.b64) throw new Error('未返回图片数据');
const ext = d.ext || img.ext || 'png';
setResult({ b64: img.b64, ext, mime: ext === 'jpg' ? 'jpeg' : ext, revisedPrompt: d.revisedPrompt, ms: d.ms, model: d.model });
// 生成成功后刷新一次文件夹(可能有别处新入库)
if (currentLibraryId) {
imageAPI.getFolders(currentLibraryId).then((r) => setFolders(r.folders)).catch(() => {});
}
} catch (e) {
setError(e.data?.error || e.message || '生成失败');
} finally {
setLoading(false);
}
};
const b64ToFile = () => {
const bin = atob(result.b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
const ts = new Date();
const pad = (n) => String(n).padStart(2, '0');
const ext = result.ext || 'png';
const name = `AI_${ts.getFullYear()}${pad(ts.getMonth() + 1)}${pad(ts.getDate())}_${pad(ts.getHours())}${pad(ts.getMinutes())}${pad(ts.getSeconds())}.${ext}`;
return new File([arr], name, { type: `image/${result.mime || ext}` });
};
const handleSave = async () => {
if (!currentLibraryId) { setError('请先选择素材库'); return; }
setSaving(true);
setError('');
try {
const file = b64ToFile();
await fileAPI.upload(currentLibraryId, saveTarget, [file], undefined, 'rename');
setSaved(true);
// 刷新文件夹与当前视图
const r = await imageAPI.getFolders(currentLibraryId);
setFolders(r.folders);
const params = { folder: selectedFolder || '' };
const resp = await imageAPI.search(currentLibraryId, params);
setImages(resp.images);
onSaved && onSaved();
} catch (e) {
setError('保存失败: ' + (e.data?.error || e.message));
} finally {
setSaving(false);
}
};
const handleDownload = () => {
const a = document.createElement('a');
a.href = `data:image/${result.mime || 'png'};base64,${result.b64}`;
a.download = b64ToFile().name;
a.click();
};
const appendPrompt = (p) => {
setPrompt((prev) => (prev.trim() ? prev.replace(/[,,、\s]+$/, '') + ',' + p : p));
setError('');
};
if (!open) return null;
const activeCat = PROMPT_CATEGORIES.find((c) => c.key === cat) || PROMPT_CATEGORIES[0];
const noKey = providerInfo && !providerInfo.hasKey && !useCustom;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-5xl max-h-[90vh] overflow-hidden flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* 头部 */}
<div className="flex items-center justify-between px-5 py-3.5 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<div className="p-1.5 rounded-lg bg-gradient-to-br from-purple-500 to-pink-500">
<Wand2 className="w-4 h-4 text-white" />
</div>
<h2 className="text-base font-semibold text-gray-900 dark:text-white">AI 生图</h2>
<span className="text-xs text-gray-400 dark:text-gray-500">热门提示词 · 一键生成 · 入库</span>
</div>
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-5">
<div className="grid grid-cols-1 lg:grid-cols-5 gap-5">
{/* 左:提示词 + 热门词库 */}
<div className="lg:col-span-3 space-y-4">
<div>
<div className="flex items-center justify-between mb-1.5">
<label className="text-xs font-medium text-gray-500 dark:text-gray-400">提示词</label>
<span className="text-[11px] text-gray-400">{prompt.length} 字</span>
</div>
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
placeholder="描述你想要的画面,例如:一只戴墨镜的柴犬在海边冲浪,卡通风格"
className="w-full px-3 py-2.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 resize-none focus:ring-2 focus:ring-purple-400 focus:border-transparent"
/>
</div>
{/* 热门提示词 */}
<div>
<div className="flex items-center gap-1.5 mb-2">
<Sparkles className="w-3.5 h-3.5 text-amber-500" />
<span className="text-xs font-medium text-gray-500 dark:text-gray-400">常用热门提示词</span>
</div>
<div className="flex flex-wrap gap-1.5 mb-2.5">
{PROMPT_CATEGORIES.map((c) => (
<button
key={c.key}
onClick={() => setCat(c.key)}
className={`px-2.5 py-1 rounded-full text-xs transition-colors ${
cat === c.key
? 'bg-purple-600 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
}`}
>
{c.label}
</button>
))}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5 max-h-56 overflow-y-auto pr-1">
{activeCat.prompts.map((p) => (
<button
key={p.name}
onClick={() => appendPrompt(p.prompt)}
title={p.prompt}
className="text-left px-2.5 py-2 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-purple-400 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-500/10 transition-colors group"
>
<div className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate group-hover:text-purple-700 dark:group-hover:text-purple-300">
{p.name}
</div>
<div className="text-[10px] text-gray-400 dark:text-gray-500 truncate">{p.prompt}</div>
</button>
))}
</div>
</div>
</div>
{/* 右:参数 + 生成 */}
<div className="lg:col-span-2 space-y-3.5">
{/* 提供商 */}
<div>
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">模型提供商</label>
<select
value={useCustom ? 'custom' : 'builtin'}
onChange={(e) => setUseCustom(e.target.value === 'custom')}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
>
<option value="builtin">内置 NewAPI(Pollinations + CF Workers AI)</option>
<option value="custom" disabled={!providerInfo?.customModel && !providerInfo?.customUrl}>
自定义提供商{providerInfo?.customModel ? `(${providerInfo.customModel})` : '(未配置)'}
</option>
</select>
{providerInfo && !providerInfo.hasKey && !useCustom && (
<div className="mt-1.5 flex items-start gap-1.5 text-[11px] text-amber-600 dark:text-amber-400">
<AlertTriangle className="w-3.5 h-3.5 flex-shrink-0 mt-px" />
<span>
未配置 API Key。到「设置 → AI 生图」填写,或由服务器环境变量注入。
</span>
</div>
)}
</div>
{/* 模型 */}
{!useCustom && (
<div>
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">模型</label>
<select
value={model}
onChange={(e) => setModel(e.target.value)}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
>
{groups.map((g) => (
<optgroup key={g.key} label={g.label}>
{g.models.map((m) => (
<option key={m.id} value={m.id}>{m.name}</option>
))}
</optgroup>
))}
</select>
</div>
)}
{useCustom && (
<div className="p-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/30 rounded-lg text-xs text-amber-700 dark:text-amber-300">
使用设置中配置的自定义提供商({providerInfo?.customUrl || '未配置地址'})。
模型:{providerInfo?.customModel || '(未配置)'}
<button
onClick={() => window.dispatchEvent(new CustomEvent('open:settings', { detail: { tab: 'aigen' } }))}
className="ml-1 underline hover:text-amber-900 dark:hover:text-amber-100"
>
去配置
</button>
</div>
)}
{/* 尺寸 */}
<div>
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">尺寸</label>
<div className="grid grid-cols-3 gap-1.5">
{sizes.map((s) => (
<button
key={s}
onClick={() => setSize(s)}
className={`px-2 py-1.5 rounded-lg text-xs transition-colors ${
size === s
? 'bg-purple-600 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
}`}
>
{s.replace('x', '×')}
</button>
))}
</div>
</div>
{/* 生成按钮 */}
<button
onClick={handleGenerate}
disabled={loading || !prompt.trim()}
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
{loading ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
生成中…(约 10-30 秒)
</>
) : (
<>
<Wand2 className="w-4 h-4" />
生成图片
</>
)}
</button>
{loading && (
<div className="text-[11px] text-gray-400 dark:text-gray-500 text-center">
正在调用 {useCustom ? '自定义提供商' : (model || '')},超时上限 150 秒
</div>
)}
</div>
</div>
{/* 错误 */}
{error && (
<div className="mt-4 flex items-start gap-2 px-3 py-2.5 rounded-lg bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/30 text-sm text-red-700 dark:text-red-300">
<AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
<span className="whitespace-pre-wrap">{error}</span>
</div>
)}
{/* 结果预览 */}
{result && (
<div className="mt-5 border border-gray-200 dark:border-gray-700 rounded-xl overflow-hidden">
<div className="flex items-center justify-between px-4 py-2 bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
<span>模型 {result.model}</span>
<span>耗时 {(result.ms / 1000).toFixed(1)}s</span>
</div>
<div className="flex items-center gap-1.5">
<button
onClick={handleGenerate}
disabled={loading}
className="flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
>
<RefreshCw className="w-3.5 h-3.5" /> 重新生成
</button>
<button
onClick={handleDownload}
className="flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
>
<Download className="w-3.5 h-3.5" /> 下载
</button>
</div>
</div>
<div className="p-4 bg-gray-100 dark:bg-gray-900 flex justify-center">
<img
ref={imgRef}
src={`data:image/${result.mime || 'png'};base64,${result.b64}`}
alt="AI 生成结果"
className="max-h-[46vh] max-w-full object-contain rounded-lg shadow"
/>
</div>
{result.revisedPrompt && (
<div className="px-4 py-2 text-[11px] text-gray-400 dark:text-gray-500 border-t border-gray-200 dark:border-gray-700 truncate" title={result.revisedPrompt}>
改写提示词:{result.revisedPrompt}
</div>
)}
{/* 入库区 */}
<div className="flex flex-wrap items-center gap-2 px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
<div className="relative">
<button
onClick={() => setShowFolderPick((v) => !v)}
className="flex items-center gap-1.5 px-3 py-2 text-xs rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
>
<FolderOpen className="w-3.5 h-3.5" />
{saveTarget || '根目录'}
<ChevronDown className="w-3.5 h-3.5" />
</button>
{showFolderPick && (
<>
<div className="fixed inset-0 z-10" onClick={() => setShowFolderPick(false)}></div>
<div className="absolute left-0 bottom-full mb-1 z-20 w-64 max-h-64 overflow-y-auto bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl p-1">
{flattenFolders(folders).map((f) => (
<button
key={f.path}
onClick={() => { setSaveTarget(f.path); setShowFolderPick(false); }}
className={`w-full text-left px-2.5 py-1.5 rounded text-xs truncate ${
saveTarget === f.path
? 'bg-purple-50 dark:bg-purple-500/20 text-purple-700 dark:text-purple-300'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
{f.path || '(根目录)'}
</button>
))}
</div>
</>
)}
</div>
<button
onClick={handleSave}
disabled={saving || saved}
className="flex items-center gap-1.5 px-4 py-2 text-xs font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
>
{saving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : saved ? <CheckCircle2 className="w-3.5 h-3.5" /> : <Save className="w-3.5 h-3.5" />}
{saved ? '已入库' : saving ? '入库中…' : '保存到素材库'}
</button>
<span className="text-[11px] text-gray-400 dark:text-gray-500">
{currentLibraryId ? 'PNG 格式,入库后自动建索引与缩略图' : '未选择素材库'}
</span>
</div>
</div>
)}
</div>
</div>
</div>
);
}
+225
View File
@@ -0,0 +1,225 @@
/**
* AI 生成视频弹窗
* 多选图片 + 标题 + 模型 KEY → 一键生成带字幕和朗读的视频
* 后端:POST /api/video/aigenerate(异步任务)+ GET /api/video/task/:id 轮询
*/
import { useEffect, useRef, useState } from 'react';
import { X, Loader2, Film, CheckCircle2, AlertCircle, KeyRound } from 'lucide-react';
import { imageAPI } from '../api';
const VOICES = [
{ key: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声·自然)' },
{ key: 'zh-CN-YunxiNeural', label: '云希(男声·温暖)' },
{ key: 'zh-CN-YunjianNeural', label: '云健(男声·浑厚)' },
{ key: 'zh-CN-XiaoyiNeural', label: '晓伊(女声·活泼)' },
{ key: 'zh-CN-YunyangNeural', label: '云扬(男声·播音)' },
{ key: 'zh-TW-HsiaoChenNeural', label: '晓臻(台湾腔)' }
];
const RESOLUTIONS = [
{ key: '1920x1080', label: '横屏 1920×1080' },
{ key: '1080x1920', label: '竖屏 1080×1920' },
{ key: '1280x720', label: '横屏 1280×720' }
];
const STEPS = {
script: '正在生成分镜脚本',
tts: '正在朗读配音',
compose: '正在合成画面',
merge: '正在合并视频',
done: '完成'
};
function AIVideoModal({ libraryId, images, onClose, onDone }) {
const [title, setTitle] = useState('');
const [apiKey, setApiKey] = useState('');
const [showKey, setShowKey] = useState(false);
const [voice, setVoice] = useState(VOICES[0].key);
const [resolution, setResolution] = useState('1920x1080');
const [extraPrompt, setExtraPrompt] = useState('');
const [taskId, setTaskId] = useState('');
const [task, setTask] = useState(null);
const [error, setError] = useState('');
const [starting, setStarting] = useState(false);
const timerRef = useRef(null);
const list = Array.isArray(images) ? images : [];
// 轮询任务进度
useEffect(() => {
if (!taskId) return;
timerRef.current = setInterval(async () => {
try {
const res = await fetch(`/api/video/task/${taskId}`);
if (!res.ok) return;
const data = await res.json();
setTask(data);
if (data.status === 'done' || data.status === 'error') {
clearInterval(timerRef.current);
if (data.status === 'done') {
setTimeout(() => { onDone && onDone(data.resultPath); onClose(); }, 1200);
}
}
} catch (_) { /* 网络抖动继续轮询 */ }
}, 1500);
return () => timerRef.current && clearInterval(timerRef.current);
}, [taskId, onDone, onClose]);
const handleStart = async () => {
setError('');
if (!title.trim()) { setError('请填写视频标题'); return; }
if (list.length < 2) { setError('请至少选择 2 张图片'); return; }
setStarting(true);
try {
const res = await fetch('/api/video/aigenerate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
libraryId,
images: list.map((img) => ({ path: img.path })),
title: title.trim(),
apiKey: apiKey.trim(),
voice,
resolution,
extraPrompt: extraPrompt.trim()
})
});
const data = await res.json().catch(() => ({}));
if (!res.ok || data.error) throw new Error(data.error || `启动失败 (${res.status})`);
setTaskId(data.taskId);
} catch (e) {
setError(e.message || '启动失败');
} finally {
setStarting(false);
}
};
const running = !!taskId && task && task.status === 'running';
const failed = task && task.status === 'error';
const done = task && task.status === 'done';
const label = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1';
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
return (
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4" onClick={(running || starting) ? undefined : onClose}>
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg max-h-[92vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<Film className="w-5 h-5 text-purple-500" />
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">AI 生成视频</h2>
<span className="text-xs px-2 py-0.5 rounded-full bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300">{list.length} 张图片</span>
</div>
<button onClick={onClose} disabled={running || starting} className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="p-5 space-y-4">
{/* 图片缩略条 */}
<div className="flex gap-2 overflow-x-auto pb-1">
{list.map((img, i) => (
<div key={img.id || i} className="flex-shrink-0 w-20 h-14 rounded bg-gray-100 dark:bg-gray-700 overflow-hidden relative">
<img
src={img.thumbnailPath ? imageAPI.getThumbnailUrl(libraryId, img.thumbnailPath.replace(/\\/g, '/').split('/').pop(), img.modifiedAt) : ''}
alt={img.filename || ''}
className="w-full h-full object-cover"
onError={(e) => { e.target.style.display = 'none'; }}
/>
<span className="absolute top-0.5 left-0.5 text-[10px] bg-black bg-opacity-55 text-white px-1 rounded z-10">{i + 1}</span>
</div>
))}
</div>
<div>
<label className={label}>视频标题</label>
<input className={input} value={title} onChange={(e) => setTitle(e.target.value)} placeholder="例如:周末探店 vlog / 产品功能速览" maxLength={60} disabled={running || done} />
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">AI 将按此标题撰写分镜旁白,成片文件名也用它。</p>
</div>
<div>
<label className={`${label} flex items-center gap-1`}><KeyRound className="w-3.5 h-3.5" /> 模型 KEY(OpenAI 兼容)</label>
<div className="relative">
<input
type={showKey ? 'text' : 'password'}
className={`${input} pr-16`}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="留空则使用服务器已配置的 KEY"
disabled={running || done}
/>
<button type="button" onClick={() => setShowKey(!showKey)} className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-1">
{showKey ? '隐藏' : '显示'}
</button>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className={label}>朗读音色</label>
<select className={input} value={voice} onChange={(e) => setVoice(e.target.value)} disabled={running || done}>
{VOICES.map((v) => <option key={v.key} value={v.key}>{v.label}</option>)}
</select>
</div>
<div>
<label className={label}>画幅</label>
<select className={input} value={resolution} onChange={(e) => setResolution(e.target.value)} disabled={running || done}>
{RESOLUTIONS.map((r) => <option key={r.key} value={r.key}>{r.label}</option>)}
</select>
</div>
</div>
<div>
<label className={label}>补充要求(可选)</label>
<input className={input} value={extraPrompt} onChange={(e) => setExtraPrompt(e.target.value)} placeholder="例如:语气轻松活泼 / 强调性价比 / 结尾加行动号召" maxLength={100} disabled={running || done} />
</div>
{/* 进度 */}
{(running || done || failed) && (
<div className={`rounded-lg border px-4 py-3 ${failed ? 'border-red-200 bg-red-50 dark:bg-red-900/20' : done ? 'border-green-200 bg-green-50 dark:bg-green-900/20' : 'border-blue-200 bg-blue-50 dark:bg-blue-900/20'}`}>
<div className="flex items-center gap-2 text-sm">
{failed ? <AlertCircle className="w-4 h-4 text-red-500" /> : done ? <CheckCircle2 className="w-4 h-4 text-green-500" /> : <Loader2 className="w-4 h-4 animate-spin text-blue-500" />}
<span className={`font-medium ${failed ? 'text-red-700 dark:text-red-300' : done ? 'text-green-700 dark:text-green-300' : 'text-blue-700 dark:text-blue-300'}`}>
{failed ? '生成失败' : done ? '生成完成,正在打开…' : (task.stepLabel || STEPS[task.step] || '处理中')}
</span>
{running && <span className="ml-auto text-xs text-blue-600 dark:text-blue-300">{task.progress || 0}%</span>}
</div>
{running && (
<div className="mt-2 h-1.5 bg-blue-100 dark:bg-blue-900/50 rounded-full overflow-hidden">
<div className="h-full bg-blue-500 rounded-full transition-all" style={{ width: `${task.progress || 0}%` }} />
</div>
)}
{failed && <p className="mt-1 text-xs text-red-600 dark:text-red-400">{task.error}</p>}
{done && task.resultPath && <p className="mt-1 text-xs text-green-600 dark:text-green-400">已保存:{task.resultPath}</p>}
</div>
)}
{error && <div className="text-sm text-red-600 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg px-3 py-2">{error}</div>}
<p className="text-xs text-gray-500 dark:text-gray-400">
流程:AI 写分镜脚本 → 逐段朗读配音 → 图片逐段配字幕合成 → 拼接成片入库。图片越多耗时越长(约 10–60 秒/张)。
</p>
<div className="flex justify-end gap-3 pt-1">
<button onClick={onClose} disabled={running || starting} className="px-4 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50">
{done ? '关闭' : '取消'}
</button>
{!running && !done && (
<button
onClick={handleStart}
disabled={starting}
className="px-5 py-2 text-sm rounded-lg bg-purple-600 hover:bg-purple-700 text-white font-medium disabled:opacity-50 flex items-center gap-2"
>
{starting && <Loader2 className="w-4 h-4 animate-spin" />}
{starting ? '启动中…' : '一键生成'}
</button>
)}
</div>
</div>
</div>
</div>
);
}
export default AIVideoModal;
+64
View File
@@ -0,0 +1,64 @@
import { useEffect, useState, useCallback } from 'react';
import { Rocket } from 'lucide-react';
/**
* 返回顶部小火箭(右下角)
* 兼容两种滚动容器:react-window 虚拟列表(内部滚动)和普通 overflow-y-auto 容器。
*/
function findScrolledElement() {
const all = document.querySelectorAll('*');
let best = null;
let bestTop = 0;
for (const el of all) {
const style = window.getComputedStyle(el);
const scrollable = (style.overflowY === 'auto' || style.overflowY === 'scroll') && el.scrollHeight > el.clientHeight + 4;
if (scrollable && el.scrollTop > bestTop) {
bestTop = el.scrollTop;
best = el;
}
}
return bestTop > 0 ? best : null;
}
function BackToTop() {
const [visible, setVisible] = useState(false);
useEffect(() => {
const onScroll = () => {
const el = findScrolledElement();
const top = el ? el.scrollTop : (window.scrollY || document.documentElement.scrollTop || 0);
setVisible(top > 300);
};
onScroll();
window.addEventListener('scroll', onScroll, true);
window.addEventListener('resize', onScroll);
const timer = setInterval(onScroll, 1500);
return () => {
window.removeEventListener('scroll', onScroll, true);
window.removeEventListener('resize', onScroll);
clearInterval(timer);
};
}, []);
const scrollToTop = useCallback(() => {
const el = findScrolledElement();
if (el) el.scrollTo({ top: 0, behavior: 'smooth' });
window.scrollTo({ top: 0, behavior: 'smooth' });
document.documentElement.scrollTo({ top: 0, behavior: 'smooth' });
}, []);
if (!visible) return null;
return (
<button
onClick={scrollToTop}
title="返回顶部"
aria-label="返回顶部"
className="fixed bottom-20 md:bottom-6 right-4 md:right-6 z-40 w-12 h-12 rounded-full bg-blue-600 hover:bg-blue-700 text-white shadow-lg shadow-blue-600/40 hover:shadow-blue-600/60 flex items-center justify-center transition-all hover:-translate-y-0.5 active:translate-y-0"
>
<Rocket size={22} className="-rotate-45" />
</button>
);
}
export default BackToTop;
@@ -0,0 +1,556 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import {
Droplets, Eraser, Loader2, X, Play, Square, CheckCircle2,
AlertTriangle, Save, FileEdit, Eye
} from 'lucide-react';
import { batchAPI, imageAPI } from '../api';
/**
* 批量水印弹窗(文件夹级)
* mode='add' 批量加水印:文字水印(九宫格单个 / 平铺)
* mode='remove' 批量去水印:按百分比区域生成 mask → 后端 LaMa inpaint
*
* 流程:配置 → 启动任务(立即返回 taskId)→ 1s 轮询进度 → 完成/取消
*/
// 九宫格位置(与后端 makeWatermarkSvg 的 pos 规则一致)
const POSITIONS = [
['top-left', 'top-center', 'top-right'],
['middle-left', 'middle-center', 'middle-right'],
['bottom-left', 'bottom-center', 'bottom-right']
];
const POSITION_LABEL = {
'top-left': '左上', 'top-center': '顶部', 'top-right': '右上',
'middle-left': '左侧', 'middle-center': '居中', 'middle-right': '右侧',
'bottom-left': '左下', 'bottom-center': '底部', 'bottom-right': '右下'
};
// 去水印预设区域(百分比)
const REGION_PRESETS = [
{ key: 'bottom-right', label: '右下角', region: { x: 68, y: 86, w: 30, h: 11 } },
{ key: 'bottom-left', label: '左下角', region: { x: 2, y: 86, w: 30, h: 11 } },
{ key: 'top-right', label: '右上角', region: { x: 68, y: 3, w: 30, h: 11 } },
{ key: 'top-left', label: '左上角', region: { x: 2, y: 3, w: 30, h: 11 } },
{ key: 'center', label: '画面居中', region: { x: 35, y: 42, w: 30, h: 16 } },
{ key: 'bottom-bar', label: '底部横条', region: { x: 0, y: 88, w: 100, h: 11 } },
{ key: 'right-bar', label: '右侧竖条', region: { x: 85, y: 0, w: 15, h: 100 } },
{ key: 'custom', label: '自定义', region: null }
];
const clampPct = (v) => Math.max(0, Math.min(100, Number(v) || 0));
function Field({ label, children, hint }) {
return (
<div className="mb-4">
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">{label}</div>
{children}
{hint && <div className="text-[11px] text-gray-400 dark:text-gray-500 mt-1">{hint}</div>}
</div>
);
}
function Slider({ value, onChange, min, max, step = 1, suffix = '' }) {
return (
<div className="flex items-center gap-3">
<input
type="range"
className="flex-1 accent-blue-500"
value={value}
min={min}
max={max}
step={step}
onChange={(e) => onChange(Number(e.target.value))}
/>
<span className="text-xs text-gray-600 dark:text-gray-300 w-12 text-right tabular-nums">
{value}{suffix}
</span>
</div>
);
}
function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinished }) {
const [phase, setPhase] = useState('config'); // config | running | done
const [imageCount, setImageCount] = useState(0);
const [starting, setStarting] = useState(false);
const [error, setError] = useState('');
// 加水印配置
const [text, setText] = useState('');
const [tile, setTile] = useState(false);
const [position, setPosition] = useState('bottom-right');
const [fontSizePct, setFontSizePct] = useState(4);
const [opacity, setOpacity] = useState(50);
const [color, setColor] = useState('#ffffff');
const [marginPct, setMarginPct] = useState(2);
const [rotate, setRotate] = useState(-30);
const [stroke, setStroke] = useState(true);
// 去水印配置
const [presetKey, setPresetKey] = useState('bottom-right');
const [region, setRegion] = useState({ x: 68, y: 86, w: 30, h: 11 });
// 输出方式
const [output, setOutput] = useState('overwrite');
// 任务进度
const [taskId, setTaskId] = useState(null);
const [progress, setProgress] = useState(null);
const pollRef = useRef(null);
// 打开时重置 + 取图片数
useEffect(() => {
if (!isOpen) return;
setPhase('config');
setError('');
setTaskId(null);
setProgress(null);
setStarting(false);
setOutput('overwrite');
if (mode === 'remove') {
setPresetKey('bottom-right');
setRegion({ x: 68, y: 86, w: 30, h: 11 });
}
let cancelled = false;
(async () => {
try {
const resp = await imageAPI.getCount(libraryId, { folder });
if (!cancelled) setImageCount(resp.count ?? 0);
} catch (_) {
if (!cancelled) setImageCount(0);
}
})();
return () => { cancelled = true; };
}, [isOpen, mode, folder, libraryId]);
// 停止轮询
const stopPolling = useCallback(() => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
}, []);
useEffect(() => stopPolling, [stopPolling]);
const startPolling = useCallback((id) => {
stopPolling();
pollRef.current = setInterval(async () => {
try {
const s = await batchAPI.status(id);
setProgress(s);
if (s.status !== 'running') {
stopPolling();
setPhase('done');
onFinished?.(s);
}
} catch (_) {
/* 网络抖动,继续轮询 */
}
}, 1000);
}, [stopPolling, onFinished]);
const handleStart = async () => {
setError('');
if (mode === 'add' && !text.trim()) {
setError('请输入水印文字');
return;
}
setStarting(true);
try {
const payload = { libraryId, folder, type: mode, output };
payload.options = mode === 'add'
? { text: text.trim(), tile, position, fontSizePct, opacity, color, marginPct, rotate, stroke }
: { region };
const resp = await batchAPI.start(payload);
setTaskId(resp.taskId);
setPhase('running');
setProgress({
status: 'running', total: resp.total, done: 0, failed: 0,
skipped: 0, current: '', errors: []
});
startPolling(resp.taskId);
} catch (err) {
setError(err?.message || '启动失败');
} finally {
setStarting(false);
}
};
const handleCancel = async () => {
if (!taskId) return;
try {
await batchAPI.cancel(taskId);
} catch (_) { /* 任务可能已结束 */ }
stopPolling();
setPhase('done');
};
const handleClose = () => {
stopPolling();
onClose();
};
if (!isOpen) return null;
const isAdd = mode === 'add';
const title = isAdd ? '批量加水印' : '批量去水印';
const Icon = isAdd ? Droplets : Eraser;
const accent = isAdd ? 'text-blue-500' : 'text-emerald-500';
const accentBtn = isAdd ? 'bg-blue-500 hover:bg-blue-600' : 'bg-emerald-500 hover:bg-emerald-600';
const pct = progress && progress.total > 0
? Math.round(((progress.done + progress.failed + progress.skipped) / progress.total) * 100)
: 0;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={handleClose}>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* 头部 */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2.5">
<Icon className={`w-5 h-5 ${accent}`} />
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">{title}</h2>
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 truncate max-w-[240px]">
{folder}
</span>
<span className="text-xs text-gray-400">{imageCount} 张图片</span>
</div>
<button onClick={handleClose} className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
{/* 内容 */}
<div className="flex-1 overflow-y-auto p-5">
{phase === 'config' && (
<>
{isAdd ? (
<>
<Field label="水印文字">
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="例如:素材室出品"
maxLength={50}
className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</Field>
<Field label="水印形式">
<div className="flex gap-2">
<button
onClick={() => setTile(false)}
className={`flex-1 px-3 py-2 rounded-lg text-sm border transition-colors ${!tile
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
单个水印
</button>
<button
onClick={() => setTile(true)}
className={`flex-1 px-3 py-2 rounded-lg text-sm border transition-colors ${tile
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
全屏平铺
</button>
</div>
</Field>
{!tile && (
<Field label="位置">
<div className="grid grid-cols-3 gap-1.5 w-44">
{POSITIONS.flat().map((pos) => (
<button
key={pos}
onClick={() => setPosition(pos)}
title={POSITION_LABEL[pos]}
className={`px-1 py-1.5 rounded text-xs border transition-colors ${position === pos
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 font-medium'
: 'border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-400'}`}
>
{POSITION_LABEL[pos]}
</button>
))}
</div>
</Field>
)}
<div className="grid grid-cols-2 gap-x-5">
<Field label="字号(占图宽比例)">
<Slider value={fontSizePct} onChange={setFontSizePct} min={1} max={15} suffix="%" />
</Field>
<Field label="透明度">
<Slider value={opacity} onChange={setOpacity} min={5} max={100} suffix="%" />
</Field>
<Field label={tile ? '倾斜角度' : '旋转角度'}>
<Slider value={rotate} onChange={setRotate} min={-90} max={90} suffix="°" />
</Field>
<Field label="边距(占图宽比例)">
<Slider value={marginPct} onChange={setMarginPct} min={0} max={10} suffix="%" />
</Field>
</div>
<div className="grid grid-cols-2 gap-x-5">
<Field label="颜色">
<div className="flex items-center gap-2">
<input
type="color"
value={color}
onChange={(e) => setColor(e.target.value)}
className="w-9 h-9 rounded cursor-pointer border border-gray-300 dark:border-gray-600 bg-transparent"
/>
{['#ffffff', '#000000', '#ff3b30', '#ffd60a'].map((c) => (
<button
key={c}
onClick={() => setColor(c)}
title={c}
className={`w-6 h-6 rounded-full border-2 ${color === c ? 'border-blue-500' : 'border-gray-300 dark:border-gray-600'}`}
style={{ backgroundColor: c }}
/>
))}
<span className="text-xs text-gray-500 tabular-nums">{color}</span>
</div>
</Field>
<Field label="描边(浅色背景更清晰)">
<label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
<input
type="checkbox"
checked={stroke}
onChange={(e) => setStroke(e.target.checked)}
className="accent-blue-500 w-4 h-4"
/>
启用黑色描边
</label>
</Field>
</div>
</>
) : (
<>
<Field label="水印区域(占图片宽高的百分比)" hint="批量去水印按统一区域处理,请选择水印所在的固定位置">
<div className="flex flex-wrap gap-2 mb-3">
{REGION_PRESETS.map((p) => (
<button
key={p.key}
onClick={() => {
setPresetKey(p.key);
if (p.region) setRegion(p.region);
}}
className={`px-3 py-1.5 rounded-lg text-xs border transition-colors ${presetKey === p.key
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-300 font-medium'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:border-gray-400'}`}
>
{p.label}
</button>
))}
</div>
<div className="flex items-center gap-4">
{/* 区域示意 */}
<div className="relative w-32 h-20 rounded border border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-900 shrink-0 overflow-hidden">
<div
className="absolute bg-emerald-400/50 border border-emerald-500"
style={{
left: `${clampPct(region.x)}%`,
top: `${clampPct(region.y)}%`,
width: `${Math.max(1, Math.min(100 - clampPct(region.x), region.w))}%`,
height: `${Math.max(1, Math.min(100 - clampPct(region.y), region.h))}%`
}}
/>
</div>
<div className="grid grid-cols-2 gap-x-4 gap-y-2 text-xs">
{[['x', '左边距'], ['y', '上边距'], ['w', '宽度'], ['h', '高度']].map(([k, lb]) => (
<label key={k} className="flex items-center gap-2">
<span className="text-gray-500 dark:text-gray-400 w-10">{lb}</span>
<input
type="number"
min={0}
max={100}
value={region[k]}
onChange={(e) => {
setPresetKey('custom');
setRegion((r) => ({ ...r, [k]: clampPct(e.target.value) }));
}}
className="w-16 px-2 py-1 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white tabular-nums focus:outline-none focus:ring-2 focus:ring-emerald-500"
/>
<span className="text-gray-400">%</span>
</label>
))}
</div>
</div>
</Field>
<div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 px-3 py-2.5 text-xs text-amber-700 dark:text-amber-300 flex gap-2">
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
<span>
修复区域内的所有内容都会被抹除重建(包括文字、logo、图案)。水印位置在整批图片中不一致时请分批处理,或用编辑器单张涂抹。
</span>
</div>
</>
)}
{/* 输出方式 */}
<Field label="处理后">
<div className="flex gap-2">
<button
onClick={() => setOutput('overwrite')}
className={`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg text-sm border transition-colors ${output === 'overwrite'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
<FileEdit className="w-4 h-4" /> 覆盖原图
</button>
<button
onClick={() => setOutput('new')}
className={`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg text-sm border transition-colors ${output === 'new'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
<Save className="w-4 h-4" /> 另存为新图
</button>
</div>
<div className="text-[11px] text-gray-400 dark:text-gray-500 mt-1.5">
{output === 'overwrite'
? '原图将被替换(缩略图与索引同步更新)'
: isAdd ? '生成 新图名_wm.jpg 保留原图' : '生成 新图名_nowm.jpg 保留原图'}
</div>
</Field>
{error && (
<div className="rounded-lg bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 px-3 py-2 text-xs text-red-600 dark:text-red-300">
{error}
</div>
)}
</>
)}
{(phase === 'running' || phase === 'done') && progress && (
<div className="py-2">
{/* 状态 */}
<div className="flex items-center gap-3 mb-4">
{phase === 'running' ? (
<Loader2 className="w-6 h-6 text-blue-500 animate-spin shrink-0" />
) : progress.failed > 0 ? (
<AlertTriangle className="w-6 h-6 text-amber-500 shrink-0" />
) : (
<CheckCircle2 className="w-6 h-6 text-emerald-500 shrink-0" />
)}
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-white">
{phase === 'running'
? (isAdd ? '正在加水印…' : '正在去水印…(AI 修复较慢,请耐心等待)')
: progress.status === 'cancelled'
? '已取消'
: progress.status === 'error'
? '任务异常终止'
: '处理完成'}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">
{phase === 'running' && progress.current
? progress.current
: `成功 ${progress.done} · 失败 ${progress.failed}${progress.skipped ? ` · 跳过 ${progress.skipped}` : ''} / 共 ${progress.total}`}
</div>
</div>
<div className="text-sm tabular-nums text-gray-600 dark:text-gray-300 shrink-0">
{progress.done + progress.failed + progress.skipped}/{progress.total}
</div>
</div>
{/* 进度条 */}
<div className="h-2.5 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden mb-4">
<div
className={`h-full transition-all duration-300 ${progress.failed > 0 && phase === 'done' ? 'bg-amber-500' : isAdd ? 'bg-blue-500' : 'bg-emerald-500'}`}
style={{ width: `${pct}%` }}
/>
</div>
{/* 统计 */}
<div className="grid grid-cols-3 gap-2 mb-4">
{[
['成功', progress.done, 'text-emerald-600 dark:text-emerald-400'],
['失败', progress.failed, progress.failed ? 'text-red-500' : 'text-gray-500'],
['跳过', progress.skipped, 'text-gray-500']
].map(([lb, v, cls]) => (
<div key={lb} className="rounded-lg bg-gray-50 dark:bg-gray-900 px-3 py-2 text-center">
<div className={`text-lg font-semibold tabular-nums ${cls}`}>{v}</div>
<div className="text-[11px] text-gray-400">{lb}</div>
</div>
))}
</div>
{/* 错误明细 */}
{progress.errors && progress.errors.length > 0 && (
<div className="rounded-lg border border-red-200 dark:border-red-800 bg-red-50/50 dark:bg-red-900/20 p-3 mb-2">
<div className="text-xs font-medium text-red-600 dark:text-red-300 mb-1.5">
失败明细(最多记录 20 条)
</div>
<div className="space-y-1 max-h-40 overflow-y-auto">
{progress.errors.map((e, i) => (
<div key={i} className="text-[11px] text-red-500 dark:text-red-400 font-mono break-all">
{e.path || '(全局)'} — {e.error}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
{/* 底部按钮 */}
<div className="px-5 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
{phase === 'config' && (
<>
<button
onClick={handleClose}
className="px-4 py-2.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 text-sm"
>
取消
</button>
<button
onClick={handleStart}
disabled={starting || imageCount === 0}
className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${accentBtn}`}
>
{starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
{imageCount === 0 ? '该文件夹没有图片' : `开始处理 ${imageCount} 张`}
</button>
</>
)}
{phase === 'running' && (
<button
onClick={handleCancel}
className="flex items-center gap-2 px-4 py-2.5 rounded-lg border border-red-300 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 text-sm"
>
<Square className="w-4 h-4" /> 停止任务
</button>
)}
{phase === 'done' && (
<>
<button
onClick={() => setPhase('config')}
className="px-4 py-2.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 text-sm"
>
再跑一批
</button>
<button
onClick={handleClose}
className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-white text-sm transition-colors ${accentBtn}`}
>
<Eye className="w-4 h-4" /> 完成,查看图片
</button>
</>
)}
</div>
</div>
</div>
);
}
export default BatchWatermarkModal;
+32 -1
View File
@@ -4,7 +4,7 @@
*/
import { useEffect, useRef } from 'react';
import { Trash2, Edit3, Move, Copy, FolderPlus } from 'lucide-react';
import { Trash2, Edit3, Move, Copy, FolderPlus, Star, Droplets, Eraser, Scissors, Film } from 'lucide-react';
function ContextMenu({ isOpen, position, onClose, options }) {
const menuRef = useRef(null);
@@ -136,6 +136,12 @@ export const menuItems = {
shortcut: 'F2',
action
}),
edit: (action) => ({
icon: <Edit3 size={16} />,
label: '编辑图片',
shortcut: 'E',
action
}),
move: (action) => ({
icon: <Move size={16} />,
label: '移动到',
@@ -147,6 +153,11 @@ export const menuItems = {
shortcut: 'Ctrl+C',
action
}),
favorite: (action, isFavorite = false) => ({
icon: <Star size={16} className={isFavorite ? 'fill-current text-amber-400' : ''} />,
label: isFavorite ? '取消收藏' : '收藏',
action
}),
newSiblingFolder: (action) => ({
icon: <FolderPlus size={16} />,
label: '新建同级文件夹',
@@ -157,6 +168,26 @@ export const menuItems = {
label: '新建子文件夹',
action
}),
batchAddWatermark: (action) => ({
icon: <Droplets size={16} />,
label: '批量加水印…',
action
}),
batchRemoveWatermark: (action) => ({
icon: <Eraser size={16} />,
label: '批量去水印…',
action
}),
videoEdit: (action) => ({
icon: <Scissors size={16} />,
label: '编辑视频(水印/字幕声音)…',
action
}),
aiVideo: (action) => ({
icon: <Film size={16} />,
label: 'AI 生成视频…',
action
}),
divider: () => ({ divider: true })
};
+203 -6
View File
@@ -1,15 +1,20 @@
import { useState, useEffect, useMemo, useRef } from 'react';
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, Star } from 'lucide-react';
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, ScanLine, Star, Bell, Github, Settings, ExternalLink, Wand2 } from 'lucide-react';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useUIStore } from '../stores/useUIStore';
import { useScanStore } from '../stores/useScanStore';
import { useTheme } from '../hooks/useTheme';
import { useHub } from '../hooks/useHub';
import { libraryAPI, scanAPI, watchAPI } from '../api';
import SettingsModal from './SettingsModal';
import AIGenModal from './AIGenModal';
import { createLogger } from '../utils/logger';
const logger = createLogger('Header');
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
function Header() {
const { currentLibraryId } = useLibraryStore();
const { searchKeywords, originalImages, selectedFolder, setSearchKeywords, filters, setFilters, resetFilters } = useImageStore();
@@ -18,10 +23,22 @@ function Header() {
const [showFilters, setShowFilters] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [isRescanning, setIsRescanning] = useState(false);
// 扫描进行中时禁用"重新扫描"按钮
const scanProgress = useScanStore((s) => s.scanProgress);
const [isMobile, setIsMobile] = useState(false);
const [showMobileSettings, setShowMobileSettings] = useState(false);
const [localSearchValue, setLocalSearchValue] = useState(searchKeywords);
const [showNotices, setShowNotices] = useState(false);
const [showSettings, setShowSettings] = useState(false);
const [settingsTab, setSettingsTab] = useState('ocr');
const [showAIGen, setShowAIGen] = useState(false);
const searchDebounceRef = useRef(null);
// 授权系统 hub:版本 / 公告 / 在线人数
const hub = useHub();
const announcements = hub.announcements || [];
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.3.0';
// 从全局 store 获取筛选状态
const selectedFormats = filters.formats || [];
@@ -29,6 +46,16 @@ function Header() {
const selectedOrientations = filters.orientations || [];
const selectedRatings = filters.ratings || [];
// 从 AI 生图弹窗跳设置(open:settings 事件,detail = 菜单 tab)
useEffect(() => {
const handler = (e) => {
setSettingsTab((e.detail && e.detail.tab) || 'ocr');
setShowSettings(true);
};
window.addEventListener('open:settings', handler);
return () => window.removeEventListener('open:settings', handler);
}, []);
// 检测移动端
useEffect(() => {
const checkMobile = () => {
@@ -251,9 +278,12 @@ function Header() {
setFilters({ ratings: newRatings });
};
const favoriteOnly = !!filters.favoriteOnly;
const toggleFavoriteOnly = () => setFilters({ favoriteOnly: !favoriteOnly });
// 清除筛选
const clearFilters = () => {
setFilters({ formats: [], sizes: [], orientations: [], ratings: [] });
setFilters({ formats: [], sizes: [], orientations: [], ratings: [], favoriteOnly: false });
};
const handleThumbnailHeightChange = async (height) => {
@@ -280,6 +310,26 @@ function Header() {
}
};
// 重新扫描:重新索引全部文件,并为缺少文字索引的旧图片补跑 OCR
const handleRescan = async () => {
if (!currentLibraryId || isRescanning || scanProgress) return;
if (!window.confirm('重新扫描将重新索引全部文件,并为缺少文字索引的图片补跑 OCR 识别。库越大耗时越长(进度会在页面上方显示),确认开始?')) {
return;
}
setIsRescanning(true);
try {
await scanAPI.fullScan(currentLibraryId);
// 扫描进度通过 Socket.IO 的 scanProgress 推送
} catch (error) {
console.error('Error rescan:', error);
alert('重新扫描失败: ' + error.message);
} finally {
setIsRescanning(false);
}
};
// 从 filterOptions 中提取可用选项
const availableFormats = filterOptions.formats;
const availableSizes = filterOptions.sizes.map(size => ({ label: size }));
@@ -294,6 +344,97 @@ function Header() {
);
const availableRatings = filterOptions.ratings;
// 右上角图标组:开源地址 / 通知 / 设置 / 版本号
const rightIcons = (
<>
<a
href={REPO_URL}
target="_blank"
rel="noreferrer"
title="开源地址"
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<Github className="w-5 h-5 text-gray-700 dark:text-gray-300" />
</a>
<div className="relative">
<button
onClick={() => setShowNotices((v) => !v)}
title="通知公告"
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors relative"
>
<Bell className="w-5 h-5 text-gray-700 dark:text-gray-300" />
{announcements.length > 0 && (
<span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-red-500"></span>
)}
</button>
{showNotices && (
<>
<div className="fixed inset-0 z-40" onClick={() => setShowNotices(false)}></div>
<div className="absolute right-0 mt-2 w-80 max-h-96 overflow-y-auto z-50 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-2xl p-3">
<div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 pb-2 mb-2 border-b border-gray-100 dark:border-gray-700">
<span>通知公告</span>
<span className="flex items-center gap-1">
{hub.online != null && <span className="text-green-600 dark:text-green-400">在线 {hub.online}</span>}
<span>{appVersion}</span>
</span>
</div>
{announcements.length === 0 ? (
<div className="text-sm text-gray-400 dark:text-gray-500 py-4 text-center">暂无公告</div>
) : (
<div className="space-y-2.5">
{announcements.map((a, i) => (
<div key={a.id || i} className="p-2.5 rounded-lg bg-gray-50 dark:bg-gray-900/60">
{a.title && (
<div className="text-sm font-medium text-gray-900 dark:text-white mb-1">{a.title}</div>
)}
<div className="text-xs text-gray-600 dark:text-gray-300 whitespace-pre-wrap leading-relaxed">{a.content}</div>
</div>
))}
</div>
)}
{hub.update_available && (
<a
href={hub.download_url || REPO_URL}
target="_blank"
rel="noreferrer"
className="mt-2 flex items-center justify-center gap-1 text-xs text-blue-600 dark:text-blue-400 hover:underline py-1.5"
>
发现新版本 {hub.latest},去更新
<ExternalLink className="w-3 h-3" />
</a>
)}
</div>
</>
)}
</div>
<button
onClick={() => setShowAIGen(true)}
title="AI 生图"
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<Wand2 className="w-5 h-5 text-purple-600 dark:text-purple-400" />
</button>
<button
onClick={() => setShowSettings(true)}
title="设置"
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<Settings className="w-5 h-5 text-gray-700 dark:text-gray-300" />
</button>
<span className="hidden sm:inline-block px-2 py-0.5 text-xs text-gray-500 dark:text-gray-400 border border-gray-200 dark:border-gray-700 rounded-full select-none">
{appVersion}
</span>
<SettingsModal open={showSettings} onClose={() => setShowSettings(false)} versionLabel={appVersion} initialTab={settingsTab} />
<AIGenModal open={showAIGen} onClose={() => setShowAIGen(false)} />
</>
);
// 移动端布局
if (isMobile) {
// 文件夹视图不显示搜索和筛选
@@ -303,7 +444,7 @@ function Header() {
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
{/* 顶部栏 */}
<div className="h-14 flex items-center justify-between px-4">
<h1 className="text-lg font-bold text-gray-900 dark:text-white">FlyPic</h1>
<h1 className="text-lg font-bold text-gray-900 dark:text-white">牛图</h1>
<div className="flex items-center gap-2">
<button
@@ -313,6 +454,15 @@ function Header() {
>
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
</button>
<button
onClick={handleRescan}
disabled={!currentLibraryId || isRescanning || !!scanProgress}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
title="重新扫描:重新索引全部文件并补跑 OCR 文字识别"
>
<ScanLine className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRescanning || scanProgress ? 'animate-pulse' : ''}`} />
</button>
<button
onClick={() => setShowMobileSettings(!showMobileSettings)}
@@ -331,6 +481,8 @@ function Header() {
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
)}
</button>
{rightIcons}
</div>
</div>
@@ -342,7 +494,7 @@ function Header() {
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="搜索图片..."
placeholder="搜索图片...(支持 OCR 图内文字)"
value={searchKeywords}
onChange={(e) => handleSearchChange(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"
@@ -491,6 +643,22 @@ function Header() {
</div>
</div>
)}
{/* 收藏筛选 */}
<div>
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">收藏</div>
<div className="flex flex-wrap gap-2">
<button
onClick={toggleFavoriteOnly}
className={`px-2 py-1 text-xs rounded-full flex items-center gap-1 ${
favoriteOnly
? 'bg-amber-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
>
<Star size={12} className={favoriteOnly ? 'fill-current' : ''} /> 只看收藏
</button>
</div>
</div>
</div>
)}
</header>
@@ -502,7 +670,7 @@ function Header() {
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
<div className="h-14 flex items-center justify-between px-6">
<div className="flex-shrink-0">
<h1 className="text-xl font-bold text-gray-900 dark:text-white">FlyPic</h1>
<h1 className="text-xl font-bold text-gray-900 dark:text-white">牛图</h1>
<p className="text-xs text-gray-500 dark:text-gray-400">轻量快速的图片素材库管理</p>
</div>
@@ -512,7 +680,7 @@ function Header() {
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="搜索图片... (多个关键词用空格分隔,即时搜索)"
placeholder="搜索图片...(支持 OCR 图内文字,多个关键词用空格分隔)"
value={localSearchValue}
onChange={(e) => handleSearchChange(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
@@ -566,6 +734,15 @@ function Header() {
>
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
</button>
<button
onClick={handleRescan}
disabled={!currentLibraryId || isRescanning || !!scanProgress}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
title="重新扫描:重新索引全部文件并补跑 OCR 文字识别"
>
<ScanLine className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRescanning || scanProgress ? 'animate-pulse' : ''}`} />
</button>
<button
onClick={toggleTheme}
@@ -578,6 +755,9 @@ function Header() {
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
)}
</button>
<div className="w-px h-6 bg-gray-200 dark:bg-gray-700 ml-1"></div>
{rightIcons}
</div>
</div>
@@ -700,6 +880,23 @@ function Header() {
)}
</div>
</div>
{/* 收藏筛选 */}
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">收藏</label>
<div className="flex flex-col gap-1.5">
<button
onClick={toggleFavoriteOnly}
className={`px-3 py-1.5 text-xs rounded transition-colors text-left flex items-center gap-1.5 ${
favoriteOnly
? 'bg-amber-500 text-white'
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
}`}
>
<Star size={14} className={favoriteOnly ? 'fill-current' : ''} /> 只看收藏
</button>
</div>
</div>
</div>
</div>
</div>
+38 -3
View File
@@ -2,7 +2,7 @@
* 图片单元格组件
*/
import { Play, FileText, Palette, Music, File } from 'lucide-react';
import { Play, FileText, Palette, Music, File, Star, ExternalLink } from 'lucide-react';
const ImageCell = ({
image,
@@ -12,8 +12,10 @@ const ImageCell = ({
editingFilename,
editInputRef,
getThumbnailUrl,
getOriginalUrl,
onImageClick,
onImageDoubleClick,
onToggleFavorite,
onContextMenu,
onDragStart,
onEditingChange,
@@ -72,9 +74,9 @@ const ImageCell = ({
}}
/>
{/* 文件类型标识 */}
{/* 文件类型标识(右让位给「新窗口打开」按钮) */}
{image.fileType && image.fileType !== 'image' && (
<div className={`absolute top-2 right-2 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${
<div className={`absolute top-2 right-11 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${
image.fileType === 'video' ? 'bg-blue-500 bg-opacity-90' :
image.fileType === 'audio' ? 'bg-pink-500 bg-opacity-90' :
image.fileType === 'document' ? 'bg-green-500 bg-opacity-90' :
@@ -91,7 +93,40 @@ const ImageCell = ({
</span>
</div>
)}
{/* 视频时长角标(右下角) */}
{image.fileType === 'video' && image.duration > 0 && (
<div className="absolute bottom-2 right-2 rounded px-1.5 py-0.5 bg-black/70 text-white text-xs font-mono tabular-nums pointer-events-none">
{Math.floor(image.duration / 60)}:{String(Math.floor(image.duration % 60)).padStart(2, '0')}
</div>
)}
{/* 在新窗口打开原图(右上角) */}
<a
href={getOriginalUrl ? getOriginalUrl(image) : ''}
target="_blank"
rel="noopener noreferrer"
title="在新窗口打开"
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
className="absolute top-2 right-2 z-10 p-1 rounded-full backdrop-blur-sm bg-black/40 hover:bg-black/70 transition-all opacity-0 group-hover:opacity-100"
>
<ExternalLink size={14} className="text-white" />
</a>
{/* 收藏标记 / 收藏按钮 */}
<button
type="button"
onClick={(e) => { e.stopPropagation(); onToggleFavorite?.(image); }}
title={image.favorite ? '取消收藏' : '收藏'}
className={`absolute top-2 left-2 z-10 p-1 rounded-full backdrop-blur-sm transition-all ${
image.favorite
? 'opacity-100 bg-amber-400/80'
: 'opacity-0 group-hover:opacity-100 bg-black/40'
}`}
>
<Star size={14} className={image.favorite ? 'fill-white text-white' : 'text-white'} />
</button>
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all pointer-events-none" />
</div>
File diff suppressed because it is too large. Load diff
+129 -6
View File
@@ -11,6 +11,7 @@ import { VariableSizeList as List } from 'react-window';
// Stores
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useUIStore } from '../stores/useUIStore';
// Custom Hooks
import { useWaterfallLayout } from '../hooks/useWaterfallLayout';
@@ -26,7 +27,7 @@ import { useInfiniteScroll } from '../hooks/useInfiniteScroll';
// Utils
import { filterImages } from '../utils/imageFilters';
import { imageAPI } from '../api';
import { imageAPI, fileAPI } from '../api';
// Components
import ImageCell from './ImageCell';
@@ -39,6 +40,8 @@ import UndoToast from './UndoToast';
import RatingToast from './RatingToast';
import FolderSelector from './FolderSelector';
import ConflictDialog from './ConflictDialog';
import VideoEditModal from './VideoEditModal';
import AIVideoModal from './AIVideoModal';
// 虚拟滚动阈值
const VIRTUAL_SCROLL_THRESHOLD = 50;
@@ -53,13 +56,16 @@ function ImageWaterfall() {
const {
images, selectedImage, setSelectedImage, selectedImages, setSelectedImages,
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder,
searchKeywords, filters, folders, setSelectedFolderItem
searchKeywords, filters, folders, setSelectedFolderItem, updateImage
} = useImageStore();
const { setEditingImage, setMergeImages } = useUIStore();
// 状态
const [photoIndex, setPhotoIndex] = useState(-1);
const [lastSelectedIndex, setLastSelectedIndex] = useState(null);
const [viewerFile, setViewerFile] = useState(null);
const [videoEditFile, setVideoEditFile] = useState(null); // 视频编辑弹窗
const [aiVideoOpen, setAiVideoOpen] = useState(false); // AI 生成视频弹窗
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, image: null });
// 统一图片移动/删除撤销顺序的栈:按操作时间顺序记录 'move' | 'delete'
const [undoStack, setUndoStack] = useState([]);
@@ -184,7 +190,7 @@ function ImageWaterfall() {
const getThumbnailUrl = useCallback((image) => {
if (!currentLibraryId || !image.thumbnailPath) return '';
const filename = image.thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(currentLibraryId, filename);
return imageAPI.getThumbnailUrl(currentLibraryId, filename, image.modifiedAt);
}, [currentLibraryId]);
const getOriginalUrl = useCallback((image) => {
@@ -213,6 +219,12 @@ function ImageWaterfall() {
const end = Math.max(lastSelectedIndex, imageIndex);
const rangeImages = flatImages.slice(start, end + 1);
setSelectedImages(rangeImages);
} else if ((image.fileType || 'image') === 'video') {
// 视频:普通单击 = 弹出播放
clearSelection();
setSelectedImage(image);
setLastSelectedIndex(imageIndex);
setViewerFile(image);
} else {
// 普通单击 = 选中
clearSelection();
@@ -276,6 +288,20 @@ function ImageWaterfall() {
e.dataTransfer.effectAllowed = 'move';
}, [selectedImages]);
const handleToggleFavorite = useCallback(async (image) => {
const targets = (selectedImages && selectedImages.length > 1 && selectedImages.includes(image))
? selectedImages : [image];
const newVal = image.favorite ? 0 : 1;
try {
for (const img of targets) {
await fileAPI.updateMetadata(currentLibraryId, img.path, { favorite: newVal });
updateImage(img.path, { favorite: newVal });
}
} catch (e) {
alert('收藏操作失败: ' + (e?.message || '未知错误'));
}
}, [currentLibraryId, selectedImages, updateImage]);
// 准备移动文件(用于右键菜单)
const handlePrepareMove = useCallback(() => {
const itemsToMove = selectedImages.length > 0
@@ -341,16 +367,45 @@ function ImageWaterfall() {
];
if (!isMultiSelection) {
if ((image?.fileType || 'image') === 'video') {
menuOptions.push(
menuItems.videoEdit(() => {
setContextMenu({ isOpen: false, position: null, image: null });
setVideoEditFile(image);
}),
menuItems.rename(() => {
setContextMenu({ isOpen: false, position: null, image: null });
handleStartRename(image);
})
);
} else {
menuOptions.push(
menuItems.edit(() => {
setContextMenu({ isOpen: false, position: null, image: null });
setEditingImage(image);
}),
menuItems.rename(() => {
setContextMenu({ isOpen: false, position: null, image: null });
handleStartRename(image);
})
);
}
} else if (selectedImages.filter((img) => (img.fileType || 'image') === 'image').length >= 2) {
// 多选 ≥2 张图片 → AI 生成视频
menuOptions.push(
menuItems.rename(() => {
menuItems.aiVideo(() => {
setContextMenu({ isOpen: false, position: null, image: null });
handleStartRename(image);
setAiVideoOpen(true);
})
);
}
menuOptions.push(
menuItems.move(handlePrepareMove),
menuItems.favorite(() => {
setContextMenu({ isOpen: false, position: null, image: null });
handleToggleFavorite(image);
}, image?.favorite),
menuItems.delete(async () => {
setContextMenu({ isOpen: false, position: null, image: null });
await handleQuickDelete();
@@ -358,7 +413,7 @@ function ImageWaterfall() {
);
return menuOptions;
}, [selectedImages, handlePrepareMove, handleStartRename, handleCopy, handleQuickDelete, setUndoToast]);
}, [selectedImages, handlePrepareMove, handleStartRename, handleCopy, handleQuickDelete, setUndoToast, handleToggleFavorite, setEditingImage]);
// 渲染单行
const renderRow = useCallback(({ index, style }) => {
@@ -388,8 +443,10 @@ function ImageWaterfall() {
editingFilename={editingFilename}
editInputRef={editInputRef}
getThumbnailUrl={getThumbnailUrl}
getOriginalUrl={getOriginalUrl}
onImageClick={handleImageClick}
onImageDoubleClick={handleImageDoubleClick}
onToggleFavorite={handleToggleFavorite}
onContextMenu={handleContextMenu}
onDragStart={handleDragStart}
onEditingChange={setEditingFilename}
@@ -408,6 +465,7 @@ function ImageWaterfall() {
renamingImage,
editingFilename,
getThumbnailUrl,
getOriginalUrl,
handleImageClick,
handleImageDoubleClick,
handleContextMenu,
@@ -471,6 +529,49 @@ function ImageWaterfall() {
>
<DragDropOverlay isVisible={isDraggingOver} />
<UploadProgress progress={uploadProgress} />
{/* 多选浮动操作条:显式删除入口(计数 = selectedImages ∪ selectedImage) */}
{(() => {
const union = [...selectedImages];
if (selectedImage && !union.some(img => img.path === selectedImage.path)) {
union.push(selectedImage);
}
const unionCount = union.length;
if (unionCount <= 1) return null;
return (
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-30 flex items-center gap-3 bg-gray-900/90 dark:bg-gray-800/90 backdrop-blur text-white rounded-full pl-5 pr-2 py-2 shadow-2xl">
<span className="text-sm whitespace-nowrap">已选 {unionCount} 张图片</span>
<button
onClick={() => {
setMergeImages(union);
setEditingImage(union[0]);
clearSelection();
}}
className="flex items-center gap-1.5 px-4 py-1.5 rounded-full bg-blue-600 hover:bg-blue-700 text-sm font-medium transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1V5zm9 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1V5zM4 14a1 1 0 011-1h6a1 1 0 011 1v5a1 1 0 01-1 1H5a1 1 0 01-1-1v-5zm9 1a1 1 0 001 1h4a1 1 0 001-1v-4a1 1 0 00-1-1h-4a1 1 0 00-1 1v4z" />
</svg>
合拼
</button>
<button
onClick={handleQuickDelete}
className="flex items-center gap-1.5 px-4 py-1.5 rounded-full bg-red-600 hover:bg-red-700 text-sm font-medium transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
移入回收站
</button>
<button
onClick={clearSelection}
className="px-3 py-1.5 rounded-full text-sm text-gray-300 hover:text-white hover:bg-white/10 transition-colors"
>
取消选择
</button>
</div>
);
})()}
<PhotoProvider
images={providerImages}
@@ -536,8 +637,10 @@ function ImageWaterfall() {
editingFilename={editingFilename}
editInputRef={editInputRef}
getThumbnailUrl={getThumbnailUrl}
getOriginalUrl={getOriginalUrl}
onImageClick={handleImageClick}
onImageDoubleClick={handleImageDoubleClick}
onToggleFavorite={handleToggleFavorite}
onContextMenu={handleContextMenu}
onDragStart={handleDragStart}
onEditingChange={setEditingFilename}
@@ -564,6 +667,26 @@ function ImageWaterfall() {
/>
)}
{/* 视频编辑弹窗 */}
{videoEditFile && (
<VideoEditModal
file={videoEditFile}
libraryId={currentLibraryId}
onClose={() => setVideoEditFile(null)}
onDone={() => { setVideoEditFile(null); window.location.reload(); }}
/>
)}
{/* AI 生成视频弹窗 */}
{aiVideoOpen && (
<AIVideoModal
libraryId={currentLibraryId}
images={selectedImages}
onClose={() => setAiVideoOpen(false)}
onDone={() => { setAiVideoOpen(false); window.location.reload(); }}
/>
)}
{/* 右键菜单 */}
<ContextMenu
isOpen={contextMenu.isOpen}
+2 -2
View File
@@ -82,7 +82,7 @@ export default function Login() {
<div className="inline-flex items-center justify-center mb-4">
<img
src="/ICON_256.PNG"
alt="FlyPic Logo"
alt="牛图 Logo"
className="w-20 h-20 object-contain"
onError={(e) => {
// 如果 ICON_256.PNG 加载失败,尝试 favicon.png
@@ -91,7 +91,7 @@ export default function Login() {
/>
</div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
FlyPic 飞图
牛图
</h1>
<p className="text-gray-600 dark:text-gray-400">
{hasPassword ? '请输入密码访问' : '首次使用,请设置访问密码'}
+7 -6
View File
@@ -15,7 +15,7 @@ const logger = createLogger('MainContent');
function MainContent() {
const { currentLibraryId } = useLibraryStore();
const { searchKeywords, filters, selectedFolder, setImages, setOriginalImages, imageLoadingState, images } = useImageStore();
const { searchKeywords, filters, selectedFolder, favoritesView, setImages, setOriginalImages, imageLoadingState, images, refreshTick } = useImageStore();
const { scanProgress } = useScanStore();
// 使用 ref 跟踪最新的请求上下文
@@ -47,8 +47,8 @@ function MainContent() {
const loadImages = useCallback(async (isInitialLoad = true) => {
if (!currentLibraryId) return;
// 如果没有选中文件夹且没有搜索条件,显示 Dashboard
if (!selectedFolder && !searchKeywords && filters.formats.length === 0) {
// 如果没有选中文件夹且没有搜索条件,显示 Dashboard(「我的收藏」视图除外)
if (!selectedFolder && !searchKeywords && filters.formats.length === 0 && !favoritesView) {
setImages([]);
useImageStore.getState().setImageLoadingState({
isLoading: false,
@@ -80,6 +80,7 @@ function MainContent() {
limit: 100
};
if (selectedFolder) params.folder = selectedFolder;
if (favoritesView) params.favorite = 1;
if (searchKeywords) params.keywords = searchKeywords;
if (filters.formats?.length > 0) params.formats = filters.formats.join(',');
@@ -128,7 +129,7 @@ function MainContent() {
currentRequestContextRef.current = null;
}
}
}, [currentLibraryId, searchKeywords, selectedFolder, setImages, setOriginalImages, cancelCurrentRequest]);
}, [currentLibraryId, searchKeywords, selectedFolder, favoritesView, setImages, setOriginalImages, cancelCurrentRequest]);
// 监听文件夹/搜索变化
useEffect(() => {
@@ -161,7 +162,7 @@ function MainContent() {
clearTimeout(debounceTimerRef.current);
}
};
}, [currentLibraryId, searchKeywords, selectedFolder, loadImages, cancelCurrentRequest]);
}, [currentLibraryId, searchKeywords, selectedFolder, favoritesView, refreshTick, loadImages, cancelCurrentRequest]);
// 恢复撤销前的文件夹状态
useEffect(() => {
@@ -232,7 +233,7 @@ function MainContent() {
{/* Content */}
<div className="flex-1 overflow-hidden">
{(!selectedFolder && !searchKeywords && filters.formats.length === 0) ? (
{(!selectedFolder && !searchKeywords && filters.formats.length === 0 && !favoritesView) ? (
<Dashboard />
) : (
<ImageWaterfall />
+452
View File
@@ -0,0 +1,452 @@
/**
* MergeCollage — 多图合拼面板
* - 常见合拼布局模板(横排/竖排/品字/宫格/一大N小)
* - 槽位从图库选图(搜索 + 分页)
* - 填了模型 KEY 后可 AI 自动从图库找相似图并自动合拼
* - 合成结果通过 onMerge(blob) 交还编辑器替换底图
*/
import { useState, useEffect, useCallback } from 'react';
import { X, Loader2, Sparkles } from 'lucide-react';
import { imageAPI, settingsAPI } from '../api';
import { getToken } from '../api/client';
import { useUIStore } from '../stores/useUIStore';
/** 布局模板:cells 为归一化矩形 [x, y, w, h],aspect 为输出画布宽高比 */
const LAYOUTS = [
{ id: '2h', name: '两图横排', aspect: 2, cells: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1]] },
{ id: '2v', name: '两图竖排', aspect: 0.5, cells: [[0, 0, 1, 0.5], [0, 0.5, 1, 0.5]] },
{ id: '3h', name: '三图横排', aspect: 3, cells: [[0, 0, 1/3, 1], [1/3, 0, 1/3, 1], [2/3, 0, 1/3, 1]] },
{ id: '3v', name: '三图竖排', aspect: 1/3, cells: [[0, 0, 1, 1/3], [0, 1/3, 1, 1/3], [0, 2/3, 1, 1/3]] },
{ id: '1+2', name: '一大两小', aspect: 1.5, cells: [[0, 0, 0.6, 1], [0.6, 0, 0.4, 0.5], [0.6, 0.5, 0.4, 0.5]] },
{ id: '2+1', name: '两小一大', aspect: 1.5, cells: [[0, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0, 0.5, 1, 0.5]] },
{ id: '2x2', name: '四宫格', aspect: 1, cells: [[0, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] },
{ id: '1+3', name: '一大三小', aspect: 1, cells: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1/3], [0.5, 1/3, 0.5, 1/3], [0.5, 2/3, 0.5, 1/3]] },
{ id: '3x2', name: '六宫格', aspect: 1.5, cells: [[0, 0, 1/3, 0.5], [1/3, 0, 1/3, 0.5], [2/3, 0, 1/3, 0.5], [0, 0.5, 1/3, 0.5], [1/3, 0.5, 1/3, 0.5], [2/3, 0.5, 1/3, 0.5]] },
{ id: '3x3', name: '九宫格', aspect: 1, cells: Array.from({ length: 9 }, (_, i) => [(i % 3) / 3, Math.floor(i / 3) / 3, 1/3, 1/3]) }
];
/** 按图片数量选默认布局:先找槽位数完全一致的,否则取能容纳的最小布局 */
function layoutForCount(n) {
if (n <= 1) return '2h';
const exact = LAYOUTS.find((l) => l.cells.length === n);
if (exact) return exact.id;
const bigger = LAYOUTS
.filter((l) => l.cells.length > n)
.sort((a, b) => a.cells.length - b.cells.length);
return bigger[0] ? bigger[0].id : '3x3';
}
const GAP_OPTIONS = [
{ value: 0, label: '无' },
{ value: 16, label: '细' },
{ value: 32, label: '粗' }
];
/** 缩略图 URL(无缩略图时回退原图) */
function thumbUrl(libId, rec) {
if (!rec) return '';
if (rec.thumbnailPath) {
const fn = rec.thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(libId, fn, rec.modifiedAt);
}
return imageAPI.getOriginalUrl(libId, rec.path);
}
function loadImg(src) {
return new Promise((resolve, reject) => {
const im = new Image();
im.onload = () => resolve(im);
im.onerror = () => reject(new Error('图片加载失败: ' + src));
im.src = src;
});
}
export default function MergeCollage({ image, libraryId, onMerge, setStatus, setBusy }) {
const [layoutId, setLayoutId] = useState('2h');
const [slots, setSlots] = useState([image, null]);
const [gap, setGap] = useState(16);
const [keyReady, setKeyReady] = useState(null); // null=未检查
const [pickerFor, setPickerFor] = useState(null); // 正在选图的槽位下标
const [pickQuery, setPickQuery] = useState('');
const [pickImages, setPickImages] = useState([]);
const [pickOffset, setPickOffset] = useState(0);
const [pickHasMore, setPickHasMore] = useState(false);
const [pickLoading, setPickLoading] = useState(false);
const layout = LAYOUTS.find((l) => l.id === layoutId) || LAYOUTS[0];
const filled = slots.filter(Boolean).length;
// 打开时:有多选种子图则自动填槽 + 选布局;否则当前图为第 1 格
useEffect(() => {
const st = useUIStore.getState();
const seeds = st.mergeImages;
if (seeds && seeds.length >= 1) {
const lid = layoutForCount(seeds.length);
const L = LAYOUTS.find((l) => l.id === lid);
setLayoutId(lid);
setSlots(L.cells.map((_, i) => seeds[i] || null));
st.setMergeImages(null);
} else {
setLayoutId('2h');
setSlots([image, null]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [image && image.path]);
// 检查模型 KEY 是否已配置
useEffect(() => {
settingsAPI.getSettings()
.then((d) => setKeyReady(!!(d.online && d.online.configured)))
.catch(() => setKeyReady(null));
}, []);
// 退出时清掉未消费的种子,避免下次误触发
useEffect(() => () => useUIStore.getState().setMergeImages(null), []);
const changeLayout = useCallback((id) => {
setLayoutId(id);
const L = LAYOUTS.find((l) => l.id === id);
setSlots((prev) => L.cells.map((_, i) => prev[i] || null));
}, []);
// ---------- 图库选择器 ----------
const loadPicker = useCallback(async (offset, kw) => {
setPickLoading(true);
try {
const params = { offset, limit: 48 };
if (kw && kw.trim()) params.keywords = kw.trim();
const r = await imageAPI.search(libraryId, params);
setPickImages((prev) => (offset === 0 ? r.images : [...prev, ...r.images]));
setPickOffset(offset + (r.images ? r.images.length : 0));
setPickHasMore(!!r.hasMore);
} catch (e) {
setStatus('加载图库失败: ' + (e.message || ''));
} finally {
setPickLoading(false);
}
}, [libraryId, setStatus]);
const openPicker = (idx) => {
setPickerFor(idx);
setPickQuery('');
setPickImages([]);
setPickOffset(0);
loadPicker(0, '');
};
const pickSearch = () => {
setPickImages([]);
loadPicker(0, pickQuery);
};
const assignSlot = (rec) => {
setSlots((prev) => {
const next = [...prev];
next[pickerFor] = rec;
return next;
});
setPickerFor(null);
};
// ---------- 合成渲染 ----------
const doRender = useCallback(async (slotList) => {
const cells = layout.cells;
const list = slotList || slots;
const usable = list.filter(Boolean);
if (usable.length < 2) {
setStatus('至少需要 2 张图片才能合拼');
return;
}
let W, H;
if (layout.aspect >= 1) { W = 2000; H = Math.round(2000 / layout.aspect); }
else { H = 2000; W = Math.round(2000 * layout.aspect); }
const off = document.createElement('canvas');
off.width = W;
off.height = H;
const ctx = off.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, W, H);
const g = gap;
try {
let done = 0;
for (let i = 0; i < cells.length; i++) {
const rec = list[i];
if (!rec) continue;
done += 1;
setBusy(`合拼生成中 ${done}/${usable.length}`);
const [cx, cy, cw, ch] = cells[i];
const x = cx * W + g / 2;
const y = cy * H + g / 2;
const w = cw * W - g;
const h = ch * H - g;
const im = await loadImg(imageAPI.getOriginalUrl(libraryId, rec.path));
const s = Math.max(w / im.width, h / im.height);
const dw = im.width * s;
const dh = im.height * s;
ctx.save();
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.clip();
ctx.drawImage(im, x + (w - dw) / 2, y + (h - dh) / 2, dw, dh);
ctx.restore();
im.onload = null;
im.src = '';
}
const blob = await new Promise((res, rej) =>
off.toBlob((b) => (b ? res(b) : rej(new Error('画布导出失败'))), 'image/png')
);
await onMerge(blob);
setStatus(`合拼完成(${usable.length} 张 · ${W}×${H}),可继续编辑后保存`);
} catch (e) {
setStatus('合拼失败: ' + (e.message || ''));
} finally {
setBusy('');
}
}, [layout, slots, gap, libraryId, onMerge, setStatus, setBusy]);
// ---------- AI 自动找相似图并合拼 ----------
const aiAutoMerge = async () => {
const emptyIdx = slots.map((s, i) => (s ? null : i)).filter((i) => i !== null);
if (!emptyIdx.length) {
return doRender(slots);
}
const seedRec = slots.find(Boolean) || image;
if (keyReady === false) {
setStatus('未配置模型 KEY:请到 设置 → OCR 识别 填写线上模型接口和 KEY');
return;
}
setBusy('AI 正在图库中找相似图');
try {
const resp = await fetch('/api/edit/find-similar', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `*** ${getToken()}`
},
body: JSON.stringify({
libraryId,
seedPath: seedRec.path,
count: emptyIdx.length,
excludePaths: slots.filter(Boolean).map((s) => s.path)
})
});
const j = await resp.json().catch(() => ({}));
if (!resp.ok) {
throw new Error((j.error && j.error.message) || `请求失败 (${resp.status})`);
}
const next = [...slots];
(j.images || []).forEach((img, k) => {
if (k < emptyIdx.length) next[emptyIdx[k]] = img;
});
setSlots(next);
setStatus(`AI 找到 ${(j.images || []).length} 张相似图,正在合拼…`);
await doRender(next);
} catch (e) {
setStatus('AI 合拼失败: ' + (e.message || ''));
setBusy('');
}
};
return (
<div className="space-y-3">
{/* 布局模板 */}
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300">合拼布局</div>
<div className="grid grid-cols-2 gap-1.5">
{LAYOUTS.map((L) => {
const active = L.id === layoutId;
return (
<button
key={L.id}
onClick={() => changeLayout(L.id)}
className={`p-1.5 rounded-lg border transition-colors ${
active
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/30'
: 'border-gray-200 dark:border-gray-600 hover:border-blue-300'
}`}
>
<div
className="relative w-full bg-gray-100 dark:bg-gray-700 rounded overflow-hidden"
style={{ paddingBottom: `${(1 / L.aspect) * 100}%` }}
>
{L.cells.map((c, i) => (
<span
key={i}
className={`absolute ${active ? 'bg-blue-400' : 'bg-gray-300 dark:bg-gray-500'}`}
style={{
left: `${c[0] * 100}%`,
top: `${c[1] * 100}%`,
width: `${c[2] * 100}%`,
height: `${c[3] * 100}%`,
border: '1px solid rgba(255,255,255,0.85)',
boxSizing: 'border-box'
}}
/>
))}
</div>
<div className={`text-[10px] text-center mt-1 ${active ? 'text-blue-600 dark:text-blue-400' : 'text-gray-500'}`}>
{L.name} · {L.cells.length}图
</div>
</button>
);
})}
</div>
{/* 槽位 */}
<div className="flex items-center justify-between">
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300">图片槽位</div>
<div className="text-[10px] text-gray-400">{filled}/{layout.cells.length} 已选</div>
</div>
<div className="grid grid-cols-3 gap-1.5">
{layout.cells.map((_, i) => {
const rec = slots[i];
return (
<div key={i} className="relative group aspect-square">
<button
onClick={() => openPicker(i)}
className="w-full h-full rounded border border-dashed border-gray-300 dark:border-gray-600 overflow-hidden hover:border-blue-400 transition-colors flex items-center justify-center bg-gray-50 dark:bg-gray-700/50"
title={rec ? '点击换图' : '点击从图库选图'}
>
{rec ? (
<img src={thumbUrl(libraryId, rec)} alt="" className="w-full h-full object-cover" />
) : (
<span className="text-gray-400 text-lg">+</span>
)}
</button>
{rec && (
<button
onClick={() => setSlots((prev) => { const n = [...prev]; n[i] = null; return n; })}
className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-red-500 text-white items-center justify-center hidden group-hover:flex leading-none text-[10px]"
title="清空此槽"
>
<X className="w-3 h-3" />
</button>
)}
</div>
);
})}
</div>
{/* 间距 */}
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 dark:text-gray-400">图片间距</span>
<div className="flex gap-1">
{GAP_OPTIONS.map((o) => (
<button
key={o.value}
onClick={() => setGap(o.value)}
className={`px-2 py-0.5 rounded text-[11px] border transition-colors ${
gap === o.value
? 'border-blue-500 text-blue-600 bg-blue-50 dark:bg-blue-900/30'
: 'border-gray-200 dark:border-gray-600 text-gray-500'
}`}
>
{o.label}
</button>
))}
</div>
</div>
{/* AI 自动合拼 */}
<button
onClick={aiAutoMerge}
disabled={filled < 1}
className="w-full py-2 rounded-lg bg-gradient-to-r from-violet-500 to-fuchsia-500 text-white text-sm hover:opacity-90 disabled:opacity-50 transition-opacity flex items-center justify-center gap-1.5"
>
<Sparkles className="w-4 h-4" />
AI 自动找相似图并合拼
</button>
{keyReady === false && (
<p className="text-[11px] text-amber-600 dark:text-amber-400 leading-relaxed">
未配置模型 KEY:到 设置 → OCR 识别 填写线上模型接口和 API Key 后,AI 可自动从图库找相似图。
</p>
)}
<p className="text-[11px] text-gray-400 leading-relaxed">
「AI 自动合拼」以第 1 张为参考,从图库找相似图填满空槽并直接生成;也可手动点槽选图后点下方按钮生成。
</p>
<button
onClick={() => doRender(slots)}
disabled={filled < 2}
className="w-full py-2 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
生成合拼({filled} 张)
</button>
{/* 图库选择器 */}
{pickerFor !== null && (
<div
className="fixed inset-0 z-[60] bg-black/60 flex items-center justify-center p-4"
onClick={() => setPickerFor(null)}
>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[80vh] flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center gap-2 px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<span className="text-sm font-medium text-gray-700 dark:text-gray-200 flex-shrink-0">
选择图片(第 {pickerFor + 1} 格)
</span>
<input
value={pickQuery}
onChange={(e) => setPickQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && pickSearch()}
placeholder="搜索文件名…"
className="flex-1 min-w-0 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-2 py-1.5 outline-none focus:border-blue-400"
/>
<button
onClick={pickSearch}
className="px-3 py-1.5 text-sm rounded bg-blue-600 text-white hover:bg-blue-700 flex-shrink-0"
>
搜索
</button>
<button
onClick={() => setPickerFor(null)}
className="p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 flex-shrink-0"
>
<X className="w-4 h-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-3">
<div className="grid grid-cols-4 sm:grid-cols-6 gap-2">
{pickImages.map((img) => (
<button
key={img.path}
onClick={() => assignSlot(img)}
className="aspect-square rounded overflow-hidden border border-gray-200 dark:border-gray-600 hover:border-blue-500 hover:ring-1 hover:ring-blue-500 transition-all"
title={img.filename}
>
<img
src={thumbUrl(libraryId, img)}
alt={img.filename}
loading="lazy"
className="w-full h-full object-cover"
/>
</button>
))}
{!pickImages.length && !pickLoading && (
<div className="col-span-full text-center text-sm text-gray-400 py-8">没有找到图片</div>
)}
{pickLoading && (
<div className="col-span-full flex items-center justify-center gap-2 text-sm text-gray-400 py-8">
<Loader2 className="w-4 h-4 animate-spin" /> 加载中…
</div>
)}
</div>
</div>
{pickHasMore && (
<div className="px-4 py-2.5 border-t border-gray-200 dark:border-gray-700 text-center">
<button
onClick={() => loadPicker(pickOffset, pickQuery)}
disabled={pickLoading}
className="px-4 py-1.5 text-sm rounded border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50"
>
加载更多(已 {pickImages.length} 张)
</button>
</div>
)}
</div>
</div>
)}
</div>
);
}
+15 -3
View File
@@ -15,7 +15,7 @@ const logger = createLogger('RightPanel');
function RightPanel() {
const { currentLibraryId } = useLibraryStore();
const { selectedImage, selectedImages, selectedFolder, selectedFolderItem, images, setSelectedImage, setSelectedImages, updateImage } = useImageStore();
const { setMobileView, isResizingPanels, resizingSide } = useUIStore();
const { setMobileView, isResizingPanels, resizingSide, setEditingImage } = useUIStore();
const { copyToClipboard } = useClipboardStore();
const [isMobile, setIsMobile] = useState(false);
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
@@ -423,7 +423,7 @@ function RightPanel() {
}
// Handle both forward and backslash
const filename = thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(currentLibraryId, filename);
return imageAPI.getThumbnailUrl(currentLibraryId, filename, selectedImage?.modifiedAt);
};
const getOriginalUrl = () => {
@@ -920,7 +920,7 @@ function RightPanel() {
setExportProgress(100);
const link = document.createElement('a');
link.href = URL.createObjectURL(zipBlob);
link.download = `FlyPic_导出_${imagesToExport.length}张_${Date.now()}.zip`;
link.download = `牛图_导出_${imagesToExport.length}张_${Date.now()}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
@@ -1563,6 +1563,18 @@ function RightPanel() {
{/* Actions - 仅桌面端显示 */}
{!isMobile && (
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0">
{/* 编辑图片(单选时) */}
{!isMultiSelect && selectedImage && (
<button
onClick={() => setEditingImage(selectedImage)}
className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
编辑图片
</button>
)}
{/* 复制按钮 */}
<button
onClick={copyMultipleImages}
+430
View File
@@ -0,0 +1,430 @@
import { useState, useEffect } from 'react';
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink, Wand2 } from 'lucide-react';
import { settingsAPI } from '../api';
const APP_VERSION = 'v1.3.0';
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
/**
* 设置弹窗:左侧菜单 + 右侧参数
* - OCR 识别:本地 tesseract / 线上接口切换、线上参数、测试
* - 关于:版本号 / 开源地址
*/
export default function SettingsModal({ open, onClose, versionLabel, initialTab }) {
const [active, setActive] = useState('ocr');
const [cfg, setCfg] = useState(null); // { provider, online:{url,model,apiKeyMasked} }
const [apiKeyInput, setApiKeyInput] = useState(''); // 新密钥(留空=保持原密钥)
const [ig, setIg] = useState(null); // imagegen 配置
const [igNewKey, setIgNewKey] = useState(''); // NewAPI 新密钥
const [igCustomKey, setIgCustomKey] = useState(''); // 自定义提供商新密钥
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [msg, setMsg] = useState(null); // { type, text }
useEffect(() => {
if (!open) return;
if (initialTab) setActive(initialTab);
setMsg(null);
setApiKeyInput('');
setIgNewKey('');
setIgCustomKey('');
settingsAPI.getSettings()
.then((d) => { setCfg({
provider: d?.provider || 'local',
online: {
url: d?.online?.url || 'https://ai.88531.cn/v1',
model: d?.online?.model || 'mimo-v2.6-flash',
apiKeyMasked: d?.online?.apiKeyMasked || ''
},
telemetry: d?.telemetry !== false
});
setIg({
provider: d?.imagegen?.provider || 'newapi',
newapi: {
url: d?.imagegen?.newapi?.url || 'http://192.168.68.19:3099/v1',
apiKeyMasked: d?.imagegen?.newapi?.apiKeyMasked || '',
hasKey: !!d?.imagegen?.newapi?.hasKey
},
custom: {
url: d?.imagegen?.custom?.url || '',
model: d?.imagegen?.custom?.model || '',
apiKeyMasked: d?.imagegen?.custom?.apiKeyMasked || ''
}
});
})
.catch((e) => setMsg({ type: 'error', text: '读取设置失败: ' + (e.data?.message || e.message) }));
}, [open]);
if (!open) return null;
const patch = (p) => setCfg((c) => ({ ...c, ...p, online: { ...c.online, ...(p.online || {}) } }));
const handleSave = async () => {
setSaving(true);
setMsg(null);
try {
const payload = {
ocr: {
provider: cfg.provider,
online: {
url: cfg.online.url,
model: cfg.online.model,
apiKey: apiKeyInput // 空字符串 = 保留原密钥
}
},
...(ig ? {
imagegen: {
provider: ig.provider,
newapi: {
url: ig.newapi.url,
apiKey: igNewKey || '' // 空 = 保持原密钥
},
custom: {
url: ig.custom.url,
model: ig.custom.model,
apiKey: igCustomKey || ''
}
}
} : {})
};
const data = await settingsAPI.updateSettings(payload);
setCfg((c) => ({ ...(c || {}), ...data, online: { ...(c?.online || {}), ...(data?.online || {}) } }));
if (data?.imagegen) {
setIg({
provider: data.imagegen.provider || 'newapi',
newapi: {
url: data.imagegen.newapi?.url || '',
apiKeyMasked: data.imagegen.newapi?.apiKeyMasked || '',
hasKey: !!data.imagegen.newapi?.hasKey
},
custom: {
url: data.imagegen.custom?.url || '',
model: data.imagegen.custom?.model || '',
apiKeyMasked: data.imagegen.custom?.apiKeyMasked || ''
}
});
}
setApiKeyInput('');
setIgNewKey('');
setIgCustomKey('');
setMsg({ type: 'ok', text: '已保存,新配置立即生效' });
} catch (e) {
setMsg({ type: 'error', text: '保存失败: ' + (e.data?.message || e.message) });
} finally {
setSaving(false);
}
};
const handleTest = async () => {
setTesting(true);
setMsg(null);
try {
// 若用户改了线上参数但没保存,测试时带上输入框内容
const apiKey = apiKeyInput || undefined;
const d = await settingsAPI.testOcr({
provider: cfg.provider,
url: cfg.online.url,
model: cfg.online.model,
...(cfg.provider === 'online' && apiKey ? { apiKey } : {})
});
if (d && typeof d.ms === 'number') {
setMsg({ type: 'ok', text: `识别成功(${d.ms}ms):${(d.text || '').slice(0, 80) || '(空)'}` });
} else {
setMsg({ type: 'error', text: (d && d.message) || '识别失败' });
}
} catch (e) {
setMsg({ type: 'error', text: '测试失败: ' + (e.data?.message || e.message) });
} finally {
setTesting(false);
}
};
const menus = [
{ key: 'ocr', label: 'OCR 识别', icon: ScanText },
{ key: 'aigen', label: 'AI 生图', icon: Wand2 },
{ key: 'about', label: '关于', icon: Info }
];
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] overflow-hidden flex"
onClick={(e) => e.stopPropagation()}
>
{/* 左侧菜单 */}
<div className="w-44 flex-shrink-0 border-r border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 p-3 flex flex-col">
<div className="text-sm font-semibold text-gray-900 dark:text-white px-2 py-2">设置</div>
{menus.map((m) => (
<button
key={m.key}
onClick={() => { setActive(m.key); setMsg(null); }}
className={`flex items-center gap-2 px-3 py-2.5 rounded-lg text-sm transition-colors ${
active === m.key
? 'bg-blue-50 dark:bg-blue-500/20 text-blue-700 dark:text-blue-300 font-medium'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<m.icon className="w-4 h-4" />
{m.label}
</button>
))}
</div>
{/* 右侧参数 */}
<div className="flex-1 p-6 overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
{active === 'ocr' ? 'OCR 识别设置' : active === 'aigen' ? 'AI 生图设置' : '关于'}
</h2>
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
{msg && (
<div className={`mb-4 px-3 py-2 rounded-lg text-sm ${
msg.type === 'ok' ? 'bg-green-50 text-green-700 dark:bg-green-500/15 dark:text-green-300'
: 'bg-red-50 text-red-700 dark:bg-red-500/15 dark:text-red-300'
}`}>{msg.text}</div>
)}
{active === 'ocr' && cfg && (
<div className="space-y-5">
<p className="text-sm text-gray-500 dark:text-gray-400">
OCR 用于「图内文字搜索」:识别图片中的文字并建立索引,扫描素材库时自动执行。
</p>
{/* 识别方式 */}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">识别方式</label>
<div className="space-y-2">
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={cfg.provider === 'local'}
onChange={() => patch({ provider: 'local' })}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">本地 OCR(tesseract)</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">免费离线,中英文识别,随容器内置,无需任何配置</span>
</span>
</label>
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={cfg.provider === 'online'}
onChange={() => patch({ provider: 'online' })}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">线上 OCR(视觉大模型)</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">识别率更高,需 OpenAI 兼容接口(/v1/chat/completions)</span>
</span>
</label>
</div>
</div>
{/* 线上参数 */}
{cfg.provider === 'online' && (
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
<input
type="text"
value={cfg.online.url}
onChange={(e) => patch({ online: { url: e.target.value } })}
placeholder="https://ai.88531.cn/v1(默认)"
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">模型名称</label>
<input
type="text"
value={cfg.online.model}
onChange={(e) => patch({ online: { model: e.target.value } })}
placeholder="mimo-v2.6-flash(默认)"
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
<input
type="password"
value={apiKeyInput}
onChange={(e) => setApiKeyInput(e.target.value)}
placeholder={cfg.online.apiKeyMasked ? `已配置(${cfg.online.apiKeyMasked}),留空保持不变` : 'sk-...'}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
</div>
)}
<div className="flex items-center gap-3">
<button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50"
>
<Save className="w-4 h-4" />
{saving ? '保存中...' : '保存'}
</button>
<button
onClick={handleTest}
disabled={testing}
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
>
<FlaskConical className="w-4 h-4" />
{testing ? '测试中...' : '测试识别'}
</button>
</div>
</div>
)}
{active === 'aigen' && cfg && ig && (
<div className="space-y-5">
<p className="text-xs text-gray-500 dark:text-gray-400">
AI 生图默认走内置 NewAPI(Pollinations + CF Workers AI 两个生图渠道);也可以切换到自己的 OpenAI 兼容提供商。密钥只保存在本机,不出服务器。
</p>
<div>
<div className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">生图通道</div>
<div className="space-y-2">
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={ig.provider === 'newapi'}
onChange={() => setIg((v) => ({ ...v, provider: 'newapi' }))}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">内置 NewAPI(推荐)</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">
Pollinations / CF Workers AI 两大生图模型,开箱即用
{ig.newapi.hasKey ? ',Key 已配置' : ',未配置 Key'}
</span>
</span>
</label>
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={ig.provider === 'custom'}
onChange={() => setIg((v) => ({ ...v, provider: 'custom' }))}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">自定义提供商</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">任意 OpenAI 兼容 /v1/images/generations 接口(OpenAI、Stability、中转站等)</span>
</span>
</label>
</div>
</div>
{ig.provider === 'newapi' && (
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
<input
type="text"
value={ig.newapi.url}
onChange={(e) => setIg((v) => ({ ...v, newapi: { ...v.newapi, url: e.target.value } }))}
placeholder="http://192.168.68.19:3099/v1(默认)"
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
<input
type="password"
value={igNewKey}
onChange={(e) => setIgNewKey(e.target.value)}
placeholder={ig.newapi.apiKeyMasked ? `已配置(${ig.newapi.apiKeyMasked}),留空保持不变` : 'NewAPI 令牌(留空则用服务器环境变量)'}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
</div>
)}
{ig.provider === 'custom' && (
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
<input
type="text"
value={ig.custom.url}
onChange={(e) => setIg((v) => ({ ...v, custom: { ...v.custom, url: e.target.value } }))}
placeholder="https://api.openai.com/v1"
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">模型名称</label>
<input
type="text"
value={ig.custom.model}
onChange={(e) => setIg((v) => ({ ...v, custom: { ...v.custom, model: e.target.value } }))}
placeholder="gpt-image-1 / flux-dev / stable-diffusion-xl ..."
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
<input
type="password"
value={igCustomKey}
onChange={(e) => setIgCustomKey(e.target.value)}
placeholder={ig.custom.apiKeyMasked ? `已配置(${ig.custom.apiKeyMasked}),留空保持不变` : 'sk-...'}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
</div>
)}
<div className="flex items-center gap-3">
<button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50"
>
<Save className="w-4 h-4" />
{saving ? '保存中...' : '保存'}
</button>
<span className="text-xs text-gray-400 dark:text-gray-500">保存后立即生效,无需重启</span>
</div>
</div>
)}
{active === 'about' && (
<div className="space-y-4 text-sm">
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
<span className="text-gray-500 dark:text-gray-400">当前版本</span>
<span className="font-medium text-gray-900 dark:text-white">{versionLabel || APP_VERSION}</span>
</div>
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
<span className="text-gray-500 dark:text-gray-400">项目名称</span>
<span className="font-medium text-gray-900 dark:text-white">牛图 素材库</span>
</div>
<div className="flex items-center justify-between py-2">
<span className="text-gray-500 dark:text-gray-400">开源地址</span>
<a
href={REPO_URL}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 text-blue-600 dark:text-blue-400 hover:underline"
>
<Github className="w-4 h-4" />
gitea.88531.cn/jinghui/flypic
<ExternalLink className="w-3 h-3" />
</a>
</div>
<p className="text-xs text-gray-400 dark:text-gray-500 pt-2">
牛图(FlyPic)基于 ZangXincz/FlyPic 二次开发,修复多项问题并新增 OCR 图内文字搜索、线上 OCR、授权系统接入等能力。
</p>
</div>
)}
</div>
</div>
</div>
);
}
+148 -6
View File
@@ -1,5 +1,5 @@
import { useState, useMemo, useEffect, useRef, useCallback } from 'react';
import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, ChevronsDown } from 'lucide-react';
import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, ChevronsDown, FolderPlus, Star } from 'lucide-react';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useScanStore } from '../stores/useScanStore';
@@ -11,6 +11,7 @@ import ContextMenu, { menuItems } from './ContextMenu';
import UndoToast from './UndoToast';
import FolderSelector from './FolderSelector';
import ConflictDialog from './ConflictDialog';
import BatchWatermarkModal from './BatchWatermarkModal';
import { createLogger } from '../utils/logger';
const logger = createLogger('Sidebar');
@@ -37,7 +38,7 @@ function Sidebar() {
expandLibrarySelector,
resetExpandLibrarySelector
} = useLibraryStore();
const { folders, selectedFolder, totalImageCount, setSelectedFolder, setSelectedFolderItem } = useImageStore();
const { folders, selectedFolder, totalImageCount, favoritesView, setFavoritesView, favoriteTick, setSelectedFolder, setSelectedFolderItem, bumpRefresh } = useImageStore();
const { isScanning } = useScanStore();
const [showAddLibrary, setShowAddLibrary] = useState(false);
@@ -51,6 +52,8 @@ function Sidebar() {
const [missingLibrary, setMissingLibrary] = useState(null); // 切换时发现的丢失素材库
const [isLibrarySelectorOpen, setIsLibrarySelectorOpen] = useState(false); // 素材库选择器展开状态
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, folder: null });
// 批量水印弹窗 { mode: 'add'|'remove', folder }
const [batchWatermark, setBatchWatermark] = useState(null);
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
const [dragOverFolder, setDragOverFolder] = useState(null); // 拖拽悬停的文件夹
@@ -95,6 +98,28 @@ function Sidebar() {
setUndoToast({ isVisible: false, message: '', count: 0 });
}, [selectedFolder]);
// 收藏数量角标(素材库切换、收藏状态变化时刷新)
const [favoriteCount, setFavoriteCount] = useState(0);
useEffect(() => {
if (!currentLibraryId) return;
let alive = true;
imageAPI.getCount(currentLibraryId, { favorite: 1 })
.then(res => { if (alive) setFavoriteCount(res?.count ?? 0); })
.catch(() => { /* 角标失败不影响主功能 */ });
return () => { alive = false; };
}, [currentLibraryId, favoriteTick]);
// 点击「我的收藏」:进入收藏视图(不选中任何文件夹)
const handleFavoritesClick = () => {
onUserActionStart();
setSelectedFolder(null);
setSelectedFolderItem(null);
const { clearSelection } = useImageStore.getState();
clearSelection();
setFavoritesView(true);
logger.user('打开我的收藏');
};
// 响应全局状态:显示新建素材库表单
useEffect(() => {
if (showAddLibraryForm) {
@@ -825,6 +850,45 @@ function Sidebar() {
}, 50);
};
// 完成创建文件夹(回车/失焦提交)
const handleFinishCreateFolder = async () => {
if (!creatingFolder) return;
const name = (newFolderName || '').trim();
if (!name) {
handleCancelCreateFolder();
return;
}
if (!currentLibraryId) {
handleCancelCreateFolder();
return;
}
// 拼接完整相对路径
const parent = creatingFolder.parentPath || '';
const fullPath = parent ? `${parent}/${name}` : name;
try {
await fileAPI.createFolder(currentLibraryId, fullPath);
logger.file(`✅ 创建文件夹: ${fullPath}`);
// 刷新文件夹树
const foldersRes = await imageAPI.getFolders(currentLibraryId);
const { setFolders } = useImageStore.getState();
setFolders(foldersRes.folders);
} catch (error) {
logger.error('❌ 创建文件夹失败:', error);
alert(error?.data?.error || error?.message || '创建文件夹失败');
} finally {
setCreatingFolder(null);
setNewFolderName('');
}
};
// 取消创建文件夹(Esc)
const handleCancelCreateFolder = useCallback(() => {
setCreatingFolder(null);
setNewFolderName('');
}, []);
const handleAddLibrary = async () => {
// 扫描期间禁止添加素材库
if (isScanning()) {
@@ -930,9 +994,9 @@ function Sidebar() {
'⚠️ 文件夹权限不足\n\n' +
errorMessage + '\n\n' +
'操作步骤:\n' +
'1. 应用中心找到 FlyPic 应用\n' +
'1. 应用中心找到 牛图 应用\n' +
'2. 点击 应用设置\n' +
'3. 将该文件夹添加到 FlyPic 应用的读写权限'
'3. 将该文件夹添加到 牛图 应用的读写权限'
);
} else {
alert('添加素材库失败: ' + errorMessage);
@@ -1436,6 +1500,19 @@ function Sidebar() {
onOpenOther={handleMissingOpenOther}
onCreateNew={handleMissingCreateNew}
/>
{/* 批量水印弹窗(加水印 / 去水印) */}
<BatchWatermarkModal
isOpen={!!batchWatermark}
mode={batchWatermark?.mode}
folder={batchWatermark?.folder}
libraryId={currentLibraryId}
onClose={() => setBatchWatermark(null)}
onFinished={(result) => {
logger.file(`批量水印任务完成: ${batchWatermark?.folder}`, result);
bumpRefresh(); // 让图片区重新加载(覆盖模式下缩略图已更新)
}}
/>
{/* Library Management */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
@@ -1593,17 +1670,50 @@ function Sidebar() {
<ChevronsDown className="w-4 h-4" />
)}
</button>
<button
onClick={() => handleStartCreateFolder('child', selectedFolder || '')}
className="px-2 py-1.5 border border-gray-300 dark:border-gray-600 rounded hover:bg-green-100 dark:hover:bg-green-900 text-green-600 dark:text-green-400 transition-colors"
title="新建文件夹(在当前文件夹下)"
>
<FolderPlus className="w-4 h-4" />
</button>
</div>
{/* 根级新建文件夹输入框(当前未选中文件夹时挂在树顶) */}
{creatingFolder && creatingFolder.type === 'child' && !creatingFolder.basePath && (
<div className="flex items-center py-1.5 rounded bg-green-50 dark:bg-green-900/30 px-1">
<div className="w-5 mr-1" />
<Folder className="w-4 h-4 mr-2 text-green-500 flex-shrink-0" />
<input
ref={newFolderInputRef}
type="text"
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleFinishCreateFolder();
} else if (e.key === 'Escape') {
e.preventDefault();
handleCancelCreateFolder();
}
}}
onBlur={handleFinishCreateFolder}
onClick={(e) => e.stopPropagation()}
autoFocus
className="flex-1 text-sm text-gray-700 dark:text-gray-300 bg-transparent border-none outline-none focus:outline-none underline decoration-2 decoration-green-500 underline-offset-2"
/>
</div>
)}
</div>
<div className="space-y-1">
{/* 全部图片选项 */}
<div
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${selectedFolder === null
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${selectedFolder === null && !favoritesView
? 'bg-blue-50 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={() => setSelectedFolder(null)}
onClick={() => { setFavoritesView(false); setSelectedFolder(null); }}
>
<div className="w-5 mr-1" />
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
@@ -1615,6 +1725,28 @@ function Sidebar() {
</span>
</div>
{/* 我的收藏 */}
<div
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${favoritesView
? 'bg-amber-50 dark:bg-amber-900/30'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={handleFavoritesClick}
title="查看我收藏的图片"
>
<div className="w-5 mr-1" />
<Star
size={16}
className={`mr-2 flex-shrink-0 ${favoritesView ? 'text-amber-500 fill-amber-500' : 'text-amber-500'}`}
/>
<span className={`text-sm font-medium flex-1 ${favoritesView ? 'text-amber-700 dark:text-amber-300' : 'text-gray-700 dark:text-gray-200'}`}>
我的收藏
</span>
<span className="text-xs text-gray-500 dark:text-gray-300 ml-2">
{favoriteCount}
</span>
</div>
{/* 分隔线 */}
{(filteredFolders.length > 0 || folders.length > 0) && (
<div className="h-px bg-gray-200 dark:bg-gray-700 my-2" />
@@ -1646,6 +1778,16 @@ function Sidebar() {
menuItems.divider(),
menuItems.rename(() => handleStartRenameFolder(contextMenu.folder)),
menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
menuItems.divider(),
menuItems.batchAddWatermark(() => {
setContextMenu({ isOpen: false, position: null, folder: null });
setBatchWatermark({ mode: 'add', folder: contextMenu.folder.path });
}),
menuItems.batchRemoveWatermark(() => {
setContextMenu({ isOpen: false, position: null, folder: null });
setBatchWatermark({ mode: 'remove', folder: contextMenu.folder.path });
}),
menuItems.divider(),
menuItems.delete(async () => {
setContextMenu({ isOpen: false, position: null, folder: null });
await handleDeleteFolder(contextMenu.folder.path);
+342
View File
@@ -0,0 +1,342 @@
/**
* 视频编辑弹窗
* 四项常用编辑:加水印 / 去水印 / 添加字幕+声音 / 去掉字幕+声音
* 后端:POST /api/video/edit(同步处理,另存为新图或覆盖原视频)
*/
import { useState } from 'react';
import { X, Droplets, Eraser, Type, Scissors, Loader2 } from 'lucide-react';
import { imageAPI } from '../api';
const ACTIONS = [
{ key: 'watermark-add', label: '加水印', icon: Droplets },
{ key: 'watermark-remove', label: '去水印', icon: Eraser },
{ key: 'subtitle-audio', label: '加字幕声音', icon: Type },
{ key: 'strip', label: '去字幕声音', icon: Scissors }
];
const POSITIONS = [
{ key: 'bottom-right', label: '右下角' },
{ key: 'bottom-left', label: '左下角' },
{ key: 'top-right', label: '右上角' },
{ key: 'top-left', label: '左上角' },
{ key: 'top-center', label: '顶部居中' },
{ key: 'bottom-center', label: '底部居中' },
{ key: 'center', label: '画面居中' }
];
// 去水印预设区域(百分比,与批量水印一致)
const WM_REGIONS = [
{ key: 'bottom-right', label: '右下角', region: { x: 68, y: 86, w: 30, h: 11 } },
{ key: 'bottom-left', label: '左下角', region: { x: 2, y: 86, w: 30, h: 11 } },
{ key: 'top-right', label: '右上角', region: { x: 68, y: 3, w: 30, h: 11 } },
{ key: 'top-left', label: '左上角', region: { x: 2, y: 3, w: 30, h: 11 } },
{ key: 'center', label: '画面居中', region: { x: 35, y: 42, w: 30, h: 16 } },
{ key: 'bottom-bar', label: '底部横条', region: { x: 0, y: 88, w: 100, h: 11 } },
{ key: 'right-bar', label: '右侧竖条', region: { x: 85, y: 0, w: 15, h: 100 } },
{ key: 'custom', label: '自定义', region: null }
];
const VOICES = [
{ key: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声·自然)' },
{ key: 'zh-CN-YunxiNeural', label: '云希(男声·温暖)' },
{ key: 'zh-CN-YunjianNeural', label: '云健(男声·浑厚)' },
{ key: 'zh-CN-XiaoyiNeural', label: '晓伊(女声·活泼)' },
{ key: 'zh-CN-YunyangNeural', label: '云扬(男声·播音)' },
{ key: 'zh-CN-liaoning-XiaobeiNeural', label: '晓北(东北话)' },
{ key: 'zh-TW-HsiaoChenNeural', label: '晓臻(台湾腔)' }
];
const clampPct = (n) => Math.max(0, Math.min(100, Number(n) || 0));
function VideoEditModal({ file, libraryId, onClose, onDone }) {
const [action, setAction] = useState('watermark-add');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [outputMode, setOutputMode] = useState('new');
// 加水印
const [wmText, setWmText] = useState('');
const [wmPos, setWmPos] = useState('bottom-right');
const [wmSize, setWmSize] = useState(4);
const [wmOpacity, setWmOpacity] = useState(0.6);
const [wmColor, setWmColor] = useState('#ffffff');
const [wmTile, setWmTile] = useState(false);
// 去水印
const [regionKey, setRegionKey] = useState('bottom-right');
const [region, setRegion] = useState({ x: 68, y: 86, w: 30, h: 11 });
// 字幕声音
const [subText, setSubText] = useState('');
const [voice, setVoice] = useState(VOICES[0].key);
const [audioMode, setAudioMode] = useState('tts'); // tts | none
const [subSize, setSubSize] = useState(5);
// 去字幕声音
const [rmAudio, setRmAudio] = useState(true);
const [rmSub, setRmSub] = useState(true);
if (!file) return null;
const thumbUrl = file.thumbnailPath
? imageAPI.getThumbnailUrl(libraryId, file.thumbnailPath.replace(/\\/g, '/').split('/').pop(), file.modifiedAt)
: '';
const handleSubmit = async () => {
setError('');
let options = {};
if (action === 'watermark-add') {
if (!wmText.trim()) { setError('请填写水印文字'); return; }
options = { text: wmText.trim(), position: wmPos, fontSizePct: wmSize, opacity: wmOpacity, color: wmColor, tile: wmTile };
} else if (action === 'watermark-remove') {
options = { region };
} else if (action === 'subtitle-audio') {
if (!subText.trim()) { setError('请填写字幕内容'); return; }
options = {
subtitleText: subText.trim(),
ttsText: audioMode === 'tts' ? subText.trim() : '',
voice,
audioMode: audioMode === 'tts' ? 'tts' : 'none',
fontSizePct: subSize,
opacity: 0.95
};
} else if (action === 'strip') {
if (!rmAudio && !rmSub) { setError('请至少勾选一项'); return; }
options = { removeAudio: rmAudio, removeSubtitle: rmSub };
}
setBusy(true);
try {
const res = await fetch('/api/video/edit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ libraryId, path: file.path, action, options, output: outputMode })
});
const data = await res.json().catch(() => ({}));
if (!res.ok || data.error) throw new Error(data.error || `处理失败 (${res.status})`);
onDone && onDone(data.path);
onClose();
} catch (e) {
setError(e.message || '处理失败');
} finally {
setBusy(false);
}
};
const label = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1';
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
return (
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4" onClick={busy ? undefined : onClose}>
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[92vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
{/* 头部 */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800 z-10">
<div className="flex items-center gap-2">
<Scissors className="w-5 h-5 text-blue-500" />
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">视频编辑</h2>
<span className="text-xs text-gray-500 dark:text-gray-400 truncate max-w-xs ml-2">{file.filename}</span>
</div>
<button onClick={onClose} disabled={busy} className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
{/* 功能切换 */}
<div className="grid grid-cols-4 gap-2 px-5 pt-4">
{ACTIONS.map((a) => {
const Icon = a.icon;
return (
<button
key={a.key}
onClick={() => { setAction(a.key); setError(''); }}
disabled={busy}
className={`flex flex-col items-center gap-1 py-3 rounded-lg border text-sm transition-colors ${
action === a.key
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-300'
: 'border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-750'
}`}
>
<Icon className="w-5 h-5" />
{a.label}
</button>
);
})}
</div>
<div className="p-5 space-y-4">
{/* 预览缩略图 + 去水印区域框 */}
{thumbUrl && (
<div className="relative rounded-lg overflow-hidden bg-black max-h-64 mx-auto" style={{ aspectRatio: '16/9' }}>
<img src={thumbUrl} alt="" className="w-full h-full object-contain" />
{action === 'watermark-remove' && (
<div
className="absolute border-2 border-red-500 bg-red-500 bg-opacity-20"
style={{
left: `${clampPct(region.x)}%`,
top: `${clampPct(region.y)}%`,
width: `${Math.max(1, Math.min(100 - clampPct(region.x), region.w))}%`,
height: `${Math.max(1, Math.min(100 - clampPct(region.y), region.h))}%`
}}
/>
)}
</div>
)}
{/* ===== 加水印 ===== */}
{action === 'watermark-add' && (
<>
<div>
<label className={label}>水印文字</label>
<input className={input} value={wmText} onChange={(e) => setWmText(e.target.value)} placeholder="例如:© 资享网 或 88531.cn" maxLength={50} />
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className={label}>位置</label>
<select className={input} value={wmPos} onChange={(e) => setWmPos(e.target.value)}>
{POSITIONS.map((p) => <option key={p.key} value={p.key}>{p.label}</option>)}
</select>
</div>
<div>
<label className={label}>颜色</label>
<input type="color" className="h-10 w-full cursor-pointer rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700" value={wmColor} onChange={(e) => setWmColor(e.target.value)} />
</div>
<div>
<label className={label}>字号(画面高度 {wmSize}%)</label>
<input type="range" min="2" max="12" step="1" value={wmSize} onChange={(e) => setWmSize(Number(e.target.value))} className="w-full" />
</div>
<div>
<label className={label}>不透明度 {Math.round(wmOpacity * 100)}%</label>
<input type="range" min="0.1" max="1" step="0.05" value={wmOpacity} onChange={(e) => setWmOpacity(Number(e.target.value))} className="w-full" />
</div>
</div>
<label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input type="checkbox" checked={wmTile} onChange={(e) => setWmTile(e.target.checked)} />
平铺整个画面(九宫格水印)
</label>
</>
)}
{/* ===== 去水印 ===== */}
{action === 'watermark-remove' && (
<>
<div>
<label className={label}>水印位置预设(红框 = 将被抹除的区域)</label>
<div className="grid grid-cols-4 gap-2">
{WM_REGIONS.map((p) => (
<button
key={p.key}
onClick={() => { setRegionKey(p.key); if (p.region) setRegion(p.region); }}
className={`py-2 text-xs rounded border ${
regionKey === p.key
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-300'
: 'border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400'
}`}
>{p.label}</button>
))}
</div>
</div>
{regionKey === 'custom' && (
<div className="grid grid-cols-4 gap-3">
{['x', 'y', 'w', 'h'].map((k) => (
<div key={k}>
<label className={label}>{{ x: '左', y: '上', w: '宽', h: '高' }[k]} (%)</label>
<input type="number" min="0" max="100" className={input} value={region[k]} onChange={(e) => setRegion({ ...region, [k]: clampPct(e.target.value) })} />
</div>
))}
</div>
)}
<p className="text-xs text-gray-500 dark:text-gray-400">提示:去水印通过平滑插值抹除区域,适合纯色/简单背景的台标与角标。</p>
</>
)}
{/* ===== 加字幕声音 ===== */}
{action === 'subtitle-audio' && (
<>
<div>
<label className={label}>字幕内容(每行一条,多行按顺序分段显示)</label>
<textarea
className={`${input} h-28 resize-y`}
value={subText}
onChange={(e) => setSubText(e.target.value)}
placeholder={'第一段字幕\n第二段字幕\n第三段字幕'}
/>
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<label className={label}>声音</label>
<select className={input} value={audioMode} onChange={(e) => setAudioMode(e.target.value)}>
<option value="tts">AI 朗读字幕(推荐)</option>
<option value="none">仅加字幕,不加声音</option>
</select>
</div>
{audioMode === 'tts' && (
<div>
<label className={label}>朗读音色</label>
<select className={input} value={voice} onChange={(e) => setVoice(e.target.value)}>
{VOICES.map((v) => <option key={v.key} value={v.key}>{v.label}</option>)}
</select>
</div>
)}
<div>
<label className={label}>字号(画面高度 {subSize}%)</label>
<input type="range" min="3" max="9" step="1" value={subSize} onChange={(e) => setSubSize(Number(e.target.value))} className="w-full mt-2" />
</div>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400">开启朗读时字幕逐段与配音同步显示,生成的新视频会替换原音轨。</p>
</>
)}
{/* ===== 去字幕声音 ===== */}
{action === 'strip' && (
<>
<div className="space-y-2">
<label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input type="checkbox" checked={rmAudio} onChange={(e) => setRmAudio(e.target.checked)} />
去掉声音(静音,视频直拷无损)
</label>
<label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input type="checkbox" checked={rmSub} onChange={(e) => setRmSub(e.target.checked)} />
去掉内嵌字幕轨
</label>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400">注:对已“烧录”进画面的字幕/水印无效(那是像素),烧录内容请用「去水印」。</p>
</>
)}
{/* 输出方式 */}
<div className="pt-2 border-t border-gray-200 dark:border-gray-700">
<label className={label}>输出方式</label>
<div className="flex gap-4">
<label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input type="radio" checked={outputMode === 'new'} onChange={() => setOutputMode('new')} />
另存为新视频(原视频不动)
</label>
<label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input type="radio" checked={outputMode === 'overwrite'} onChange={() => setOutputMode('overwrite')} />
覆盖原视频
</label>
</div>
</div>
{error && <div className="text-sm text-red-600 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg px-3 py-2">{error}</div>}
<div className="flex justify-end gap-3 pt-2">
<button onClick={onClose} disabled={busy} className="px-4 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50">
取消
</button>
<button
onClick={handleSubmit}
disabled={busy}
className="px-5 py-2 text-sm rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-medium disabled:opacity-50 flex items-center gap-2"
>
{busy && <Loader2 className="w-4 h-4 animate-spin" />}
{busy ? '处理中,请稍候…' : '开始处理'}
</button>
</div>
</div>
</div>
</div>
);
}
export default VideoEditModal;
+98
View File
@@ -0,0 +1,98 @@
/**
* AI 生图 · 常用热门提示词库
* 分类 + 预设提示词(中英混合,flux 系模型对英文提示词效果更稳)
* 点击条目 = 追加/替换输入框内容
*/
export const PROMPT_CATEGORIES = [
{
key: 'hot',
label: '🔥 热门',
prompts: [
{ name: '赛博朋克城市夜景', prompt: 'cyberpunk city at night, neon lights, rain reflections, flying cars, ultra detailed, cinematic lighting' },
{ name: '治愈系猫咪', prompt: 'a fluffy cat sitting on windowsill, warm afternoon sunlight, soft focus, cozy atmosphere, photorealistic' },
{ name: '水晶球微缩世界', prompt: 'miniature world inside a glass snow globe on wooden table, macro photography, dreamy bokeh, studio lighting' },
{ name: '复古胶片人像', prompt: 'vintage film portrait, kodak portra 400, soft natural light, nostalgic mood, grain texture' },
{ name: '极简几何壁纸', prompt: 'minimalist geometric wallpaper, pastel gradient colors, clean shapes, flat design, 4k' }
]
},
{
key: 'portrait',
label: '👤 头像人像',
prompts: [
{ name: '动漫男头', prompt: 'anime boy avatar, short black hair, hoodie, city background at dusk, detailed illustration, vibrant colors' },
{ name: '动漫女头', prompt: 'anime girl avatar, long silver hair, flower crown, soft pastel colors, clean lineart, studio ghibli style' },
{ name: '3D 卡通头像', prompt: '3D cartoon avatar of a young man, Pixar style, round face, big eyes, soft studio lighting, plain background' },
{ name: '写真级人像', prompt: 'professional headshot portrait, shallow depth of field, natural window light, high detail skin texture, 85mm lens' },
{ name: '像素风头像', prompt: 'pixel art avatar, 64x64, retro game style, bold outlines, limited palette, cute expression' }
]
},
{
key: 'wallpaper',
label: '🖼 壁纸风景',
prompts: [
{ name: '雪山日出', prompt: 'snow mountain range at sunrise, golden alpenglow, crystal clear lake reflection, ultra wide angle, 8k landscape' },
{ name: '海上星河', prompt: 'milky way over calm ocean, starry night, long exposure photography, deep blue tones, tranquil scene' },
{ name: '梯田晨雾', prompt: 'terraced rice fields with morning mist, layered mountains, traditional chinese landscape painting mood, aerial view' },
{ name: '梦幻森林', prompt: 'enchanted forest with glowing mushrooms and fireflies, volumetric light rays, fantasy atmosphere, highly detailed' },
{ name: '沙漠驼队', prompt: 'camel caravan crossing golden sand dunes at sunset, long shadows, warm tones, national geographic style' }
]
},
{
key: 'anime',
label: '✨ 动漫插画',
prompts: [
{ name: '樱花下的少女', prompt: 'anime girl under cherry blossom tree, petals falling, spring breeze, pastel colors, detailed anime illustration' },
{ name: '机甲战士', prompt: 'giant mecha robot standing in ruined city, dramatic angle, sci-fi anime style, detailed mechanical parts, dynamic lighting' },
{ name: '魔法使', prompt: 'young wizard casting spell, glowing runes, dark library background, fantasy anime illustration, vibrant magic effects' },
{ name: '校园日常', prompt: 'anime scene of students walking home at sunset, warm orange sky, slice of life, clean lineart, makoto shinkai style' },
{ name: '和风少女', prompt: 'girl in kimono holding wagashi, traditional japanese room, tatami, soft light, detailed anime art' }
]
},
{
key: 'commerce',
label: '🛍 电商海报',
prompts: [
{ name: '产品主图', prompt: 'product photography of a perfume bottle on marble pedestal, soft gradient background, studio lighting, luxury feel, high-end commercial shot' },
{ name: '美食海报', prompt: 'gourmet burger with melted cheese, steam rising, dark moody background, commercial food photography, appetizing, sharp detail' },
{ name: '双十一促销', prompt: 'e-commerce sale banner, red and gold color scheme, floating gift boxes and confetti, modern 3d render, festive atmosphere' },
{ name: '化妆品展示', prompt: 'cosmetic serum bottle surrounded by fresh flowers and water drops, clean white background, fresh and natural, commercial photo' },
{ name: '数码新品', prompt: 'smartphone floating above glowing platform, tech product render, blue and purple neon accents, futuristic commercial style' }
]
},
{
key: 'icon3d',
label: '🧊 图标3D',
prompts: [
{ name: '3D 立体图标', prompt: '3d icon of a treasure chest, glossy material, soft shadows, pastel gradient background, clay render style, cute and round' },
{ name: '玻璃质感', prompt: 'glassmorphism 3d icon of cloud storage, translucent frosted glass, floating, soft studio light, clean background' },
{ name: '卡通食物', prompt: 'cute 3d icon of a ramen bowl, kawaii style, thick outlines, vibrant colors, glossy plastic material' },
{ name: '徽章印章', prompt: '3d golden badge icon with star, metallic material, embossed, dark blue background, premium look' },
{ emoji: '🎮', name: '游戏手柄', prompt: '3d gamepad icon, retro controller, matte plastic material, playful colors, soft ambient occlusion, icon design' }
]
},
{
key: 'art',
label: '🎨 艺术风格',
prompts: [
{ name: '浮世绘海浪', prompt: 'great wave in ukiyo-e style, hokusai inspired, woodblock print texture, indigo blue palette, traditional japanese art' },
{ name: '梵高星空', prompt: 'starry night style painting, swirling sky, thick brushstrokes, post-impressionism, oil painting texture' },
{ name: '水彩花卉', prompt: 'delicate watercolor flowers, loose brushstrokes, soft edges, white background, botanical illustration style' },
{ name: '低多边形', prompt: 'low poly landscape with pine forest and mountains, faceted geometry, vibrant sunset colors, digital art' },
{ name: '水墨仙鹤', prompt: 'chinese ink wash painting of crane flying over lotus, minimal brush strokes, elegant, rice paper texture' }
]
},
{
key: 'scene',
label: '🏠 室内场景',
prompts: [
{ name: '温馨书房', prompt: 'cozy home library with floor to ceiling bookshelves, leather armchair, warm lamp light, rainy window, photorealistic' },
{ name: '北欧客厅', prompt: 'scandinavian living room, white walls, light wood furniture, large plants, natural daylight, interior design photo' },
{ name: '咖啡角落', prompt: 'small cafe corner with espresso machine, pastries display, morning light through glass, hygge atmosphere' },
{ name: '阁楼卧室', prompt: 'attic bedroom with slanted window, fairy lights, linen bedding, plants, soft morning light, aesthetic photo' },
{ name: '赛博房间', prompt: 'futuristic bedroom with holographic screens, neon strip lights, minimalist furniture, cyberpunk interior' }
]
}
];
export default PROMPT_CATEGORIES;
+42
View File
@@ -0,0 +1,42 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { hubAPI } from '../api/endpoints/hub';
/**
* 轮询 hub:新版本 + 公告 + 在线人数
* 失败开放:接口不可用时状态保持默认,不影响页面使用
*/
export function useHub(pollMs = 60000) {
const [status, setStatus] = useState({
version: '',
latest: '',
update_available: false,
changelog: '',
download_url: '',
announcements: [],
popup: [],
online: null,
hub_ok: false
});
const timerRef = useRef(null);
const refresh = useCallback(async () => {
try {
const data = await hubAPI.getHub();
if (data && typeof data === 'object') {
setStatus((prev) => ({ ...prev, ...data }));
}
} catch {
// 失败开放
}
}, []);
useEffect(() => {
refresh();
timerRef.current = setInterval(refresh, pollMs);
return () => clearInterval(timerRef.current);
}, [refresh, pollMs]);
return { ...status, refresh };
}
export default useHub;
+7 -5
View File
@@ -28,11 +28,13 @@ export const useImageDelete = () => {
* 快速删除(乐观更新,立即响应)
*/
const handleQuickDelete = useCallback(async () => {
const items = selectedImages.length > 0
? selectedImages.map(img => ({ type: 'file', path: img.path }))
: selectedImage
? [{ type: 'file', path: selectedImage.path }]
: [];
// 并集:selectedImages(ctrl/shift 多选)∪ selectedImage(普通单击)
// 否则「先单击一张再 ctrl 多选」时会漏删单击那张
const union = [...selectedImages];
if (selectedImage && !union.some(img => img.path === selectedImage.path)) {
union.push(selectedImage);
}
const items = union.map(img => ({ type: 'file', path: img.path }));
if (items.length === 0) return;
+1
View File
@@ -50,6 +50,7 @@ export const useInfiniteScroll = () => {
limit: LOAD_CONFIG.pageSize
};
if (selectedFolder) params.folder = selectedFolder;
if (useImageStore.getState().favoritesView) params.favorite = 1;
if (searchKeywords) params.keywords = searchKeywords;
if (filters.formats?.length > 0) params.formats = filters.formats.join(',');
+27 -7
View File
@@ -28,6 +28,7 @@ export const useWaterfallLayout = (images, options = {}) => {
// 使用 ref 记录上次宽度,避免频繁 setState
const lastWidthRef = { current: 0 };
let debounceTimer = null;
let fallbackTimer = null;
const emitSize = (width, height) => {
// 仅当差异超过阈值时更新,减少重算次数
@@ -57,21 +58,37 @@ export const useWaterfallLayout = (images, options = {}) => {
return false;
};
const attachObserver = () => {
if (resizeObserver || !containerRef.current) return;
resizeObserver = new ResizeObserver(() => {
// 拖动时跳过更新,避免频繁重算布局
if (useUIStore.getState().isResizingPanels) return;
measureAndEmit();
});
resizeObserver.observe(containerRef.current);
};
const tryInit = () => {
if (measureAndEmit()) {
// 成功获取宽度,设置 ResizeObserver
if (containerRef.current) {
resizeObserver = new ResizeObserver(() => {
// 拖动时跳过更新,避免频繁重算布局
if (useUIStore.getState().isResizingPanels) return;
measureAndEmit();
});
resizeObserver.observe(containerRef.current);
attachObserver();
if (fallbackTimer) {
clearInterval(fallbackTimer);
fallbackTimer = null;
}
} else if (retryCount < maxRetries) {
// 重试
retryCount++;
requestAnimationFrame(tryInit);
} else if (!fallbackTimer) {
// rAF 重试耗尽后低频轮询兜底,避免 containerWidth 永久卡 0 导致网格空白
fallbackTimer = setInterval(() => {
if (measureAndEmit()) {
attachObserver();
clearInterval(fallbackTimer);
fallbackTimer = null;
}
}, 500);
}
};
@@ -85,6 +102,9 @@ export const useWaterfallLayout = (images, options = {}) => {
if (debounceTimer) {
clearTimeout(debounceTimer);
}
if (fallbackTimer) {
clearInterval(fallbackTimer);
}
};
}, []);
+21 -11
View File
@@ -107,40 +107,50 @@ body {
color: #7a7a7a; /* 占位符颜色调亮 */
}
/* Custom scrollbar */
/* Custom scrollbar(加粗:16px,便于拖动) */
::-webkit-scrollbar {
width: 8px;
height: 8px;
width: 16px;
height: 16px;
}
::-webkit-scrollbar-track {
background: transparent;
background: rgba(0, 0, 0, 0.04);
border-radius: 8px;
}
/* 亮色主题滚动条 */
::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.15); /* 降低不透明度,更柔和 */
border-radius: 4px;
background: rgba(0, 0, 0, 0.3); /* 整条 16px 都是可拖动块 */
border-radius: 8px;
transition: background 0.2s ease;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 0, 0, 0.25); /* 悬停时稍微明显 */
background: rgba(0, 0, 0, 0.5); /* 悬停更明显 */
}
/* Firefox 滚动条 */
* {
scrollbar-width: auto;
scrollbar-color: rgba(0, 0, 0, 0.28) rgba(0, 0, 0, 0.04);
}
/* 暗色主题滚动条 - 护眼优化 */
.dark ::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.03); /* 极淡背景 */
background: rgba(255, 255, 255, 0.05); /* 极淡背景 */
}
.dark ::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15); /* 降低亮度,减少刺激 */
border-radius: 4px;
background: rgba(255, 255, 255, 0.35); /* 提高可见度 */
transition: background 0.2s ease;
}
.dark ::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.25); /* 悬停时更明显 */
background: rgba(255, 255, 255, 0.55); /* 悬停更明显 */
}
.dark * {
scrollbar-color: rgba(255, 255, 255, 0.32) rgba(255, 255, 255, 0.05);
}
/* Toast 滑入动画 */
+23 -4
View File
@@ -20,15 +20,25 @@ export const useImageStore = create((set, get) => ({
// 搜索和过滤
searchKeywords: '',
// 左侧导航「我的收藏」视图(独立于文件夹浏览)
favoritesView: false,
setFavoritesView: (v) => set({ favoritesView: v }),
// 收藏数量变化信号(收藏/取消收藏后 +1,侧栏角标据此刷新)
favoriteTick: 0,
filters: {
formats: [],
sizes: [], // 文件大小范围筛选
orientations: [], // 图片方向筛选(多选): ['horizontal', 'vertical', 'square']
ratings: [], // 评分筛选(多选): [0, 1, 2, 3, 4, 5]
favoriteOnly: false, // 仅看收藏
},
// 原始图片列表(用于生成筛选选项,不受筛选影响)
originalImages: [],
// 列表刷新信号(编辑器另存新图后 +1,MainContent 监听后重新拉取)
refreshTick: 0,
bumpRefresh: () => set((state) => ({ refreshTick: state.refreshTick + 1 })),
// 加载状态
imageLoadingState: {
@@ -74,7 +84,11 @@ export const useImageStore = create((set, get) => ({
// 文件夹操作
setFolders: (folders) => set({ folders }),
setSelectedFolder: (folder) => set({ selectedFolder: folder }),
setSelectedFolder: (folder) => set((state) => ({
selectedFolder: folder,
// 进入任何文件夹即退出「我的收藏」视图;置空(回全部图片)由调用方自行清 favoritesView
favoritesView: folder ? false : state.favoritesView
})),
setSelectedFolderItem: (folderItem) => set({ selectedFolderItem: folderItem }),
@@ -91,7 +105,8 @@ export const useImageStore = create((set, get) => ({
formats: [],
sizes: [],
orientations: [],
ratings: []
ratings: [],
favoriteOnly: false
}
}),
@@ -112,11 +127,15 @@ export const useImageStore = create((set, get) => ({
images: state.images.map(img =>
img.path === oldPath ? { ...img, ...newData } : img
),
originalImages: state.originalImages.map(img =>
originalImages: state.originalImages.map(img =>
img.path === oldPath ? { ...img, ...newData } : img
),
selectedImage: state.selectedImage?.path === oldPath
? { ...state.selectedImage, ...newData }
: state.selectedImage
: state.selectedImage,
// 收藏状态变化 → 通知侧栏刷新收藏角标
favoriteTick: newData && newData.favorite !== undefined
? state.favoriteTick + 1
: state.favoriteTick
}))
}));
+9 -1
View File
@@ -17,7 +17,15 @@ export const useUIStore = create((set) => ({
// 面板调整状态
isResizingPanels: false,
resizingSide: null, // 'left' | 'right' | null
// 图片编辑器(打开的图片记录,null=关闭)
editingImage: null,
setEditingImage: (image) => set({ editingImage: image }),
// 合拼种子图(多选后点「合拼」带入编辑器,null=无)
mergeImages: null,
setMergeImages: (images) => set({ mergeImages: images }),
// 主题操作
setTheme: (theme) => set({ theme }),
+8 -2
View File
@@ -48,13 +48,14 @@ export const matchSizeRange = (sizeKB, range) => {
* @returns {Array} 筛选后的图片列表
*/
export const filterImages = (images, filters) => {
const { formats, sizes, orientations, ratings } = filters;
const { formats, sizes, orientations, ratings, favoriteOnly } = filters;
// 如果没有任何筛选条件,直接返回原始图片
if ((!formats || formats.length === 0) &&
(!sizes || sizes.length === 0) &&
(!orientations || orientations.length === 0) &&
(!ratings || ratings.length === 0)) {
(!ratings || ratings.length === 0) &&
!favoriteOnly) {
return images;
}
@@ -66,6 +67,11 @@ export const filterImages = (images, filters) => {
}
}
// 收藏筛选
if (favoriteOnly) {
if (!img.favorite) return false;
}
// 文件大小筛选
if (sizes && sizes.length > 0) {
const sizeKB = img.size / 1024;
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* FlyPic 前端日志系统
* 牛图(FlyPic)前端日志系统
* 专注于用户操作和UI交互日志
*
* 日志分类:
+1179 -17
View File
File diff suppressed because it is too large. Load diff