diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a26e99..98b579f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # 更新日志 +## 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 图片文字搜索。 diff --git a/README.md b/README.md index 481ac99..fae57e5 100644 --- a/README.md +++ b/README.md @@ -20,13 +20,34 @@ - 文字存入索引库 `ocr_text` 列(带索引),**搜索时文件名和图片内文字同时匹配** - OCR 失败不影响扫描主流程;镜像内已预装 tesseract 及中英文语言包 -### 3. Bug 修复 +### 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 密钥与管理员密码哈希,禁止入库) -### 4. 交互保持原样 +### 7. 交互保持原样 - 图片区保持原交互:**单击选中、Ctrl/Shift 多选、双击放大预览**(未改动) @@ -54,6 +75,10 @@ services: - 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) ``` ```bash diff --git a/backend/package.json b/backend/package.json index c5ad74b..f3c6d27 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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" } -} +} \ No newline at end of file diff --git a/backend/server.js b/backend/server.js index f856cb6..47b864a 100644 --- a/backend/server.js +++ b/backend/server.js @@ -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(); diff --git a/backend/src/app.js b/backend/src/app.js index 8ea1194..5f8c0f2 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -83,6 +83,8 @@ 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'); app.use('/api/auth', authRouter); app.use('/api/library', libraryRouter); @@ -90,6 +92,8 @@ 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.get('/api/health', (req, res) => { diff --git a/backend/src/middleware/authMiddleware.js b/backend/src/middleware/authMiddleware.js index b5f7fbb..0bee6be 100644 --- a/backend/src/middleware/authMiddleware.js +++ b/backend/src/middleware/authMiddleware.js @@ -61,7 +61,8 @@ function createAuthMiddleware(getPasswordHash, getJwtSecret) { '/api/auth/status', '/api/auth/login', '/api/auth/setup', - '/api/health' + '/api/health', + '/api/hub' // 版本检查/公告(无敏感数据) ]; // 前缀匹配的公开路径(缩略图 & 原图资源) diff --git a/backend/src/routes/hub.js b/backend/src/routes/hub.js new file mode 100644 index 0000000..5c96360 --- /dev/null +++ b/backend/src/routes/hub.js @@ -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; diff --git a/backend/src/routes/settings.js b/backend/src/routes/settings.js new file mode 100644 index 0000000..f2d316e --- /dev/null +++ b/backend/src/routes/settings.js @@ -0,0 +1,99 @@ +/** + * 应用设置路由 + * 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(); + 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 + } + }); +}); + +router.put('/', (req, res) => { + try { + const saved = saveSettings(req.body || {}); + 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 + } + }); + } 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 = ` + + FlyPic OCR Test 2026 + `; + 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; diff --git a/backend/utils/hub.js b/backend/utils/hub.js new file mode 100644 index 0000000..e05cab6 --- /dev/null +++ b/backend/utils/hub.js @@ -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 }; diff --git a/backend/utils/ocr.js b/backend/utils/ocr.js index f9a2ced..16f1502 100644 --- a/backend/utils/ocr.js +++ b/backend/utils/ocr.js @@ -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} 识别出的文字(清理后的纯文本) */ -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} 识别出的文字 + */ +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 }; diff --git a/backend/utils/settings.js b/backend/utils/settings.js new file mode 100644 index 0000000..3309d9d --- /dev/null +++ b/backend/utils/settings.js @@ -0,0 +1,77 @@ +/** + * 应用设置(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 心跳/版本/公告上报开关 +}; + +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 + }; + } 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; + 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 }; diff --git a/docker-compose.yml b/docker-compose.yml index 8377433..b1be2a8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,6 +17,10 @@ services: - PORT=15002 - FRONTEND_DIST=/app/backend/public - NODE_ENV=production + # 授权系统(CardAuth):版本推送 / 公告 / 在线人数统计 —— 失败开放,不可达不影响使用 + - HUB_URL=https://auth.88531.cn/api + - HUB_PROJECT_ID=15 + - HUB_API_KEY=${HUB_API_KEY:-} # 如需挂载多个素材库,取消注释并修改路径: # volumes: # - /vol1/1000/图片库:/data/library1:ro diff --git a/frontend/src/api/endpoints/hub.js b/frontend/src/api/endpoints/hub.js new file mode 100644 index 0000000..a0ab3ef --- /dev/null +++ b/frontend/src/api/endpoints/hub.js @@ -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; diff --git a/frontend/src/api/endpoints/settings.js b/frontend/src/api/endpoints/settings.js new file mode 100644 index 0000000..4dfafcd --- /dev/null +++ b/frontend/src/api/endpoints/settings.js @@ -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; diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js index 88b5f91..015676e 100644 --- a/frontend/src/api/index.js +++ b/frontend/src/api/index.js @@ -6,11 +6,14 @@ 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'; export const libraryAPI = library; export const imageAPI = image; export const scanAPI = scan; export { fileAPI }; +export { settingsAPI, hubAPI }; export { api, APIError } from './client'; diff --git a/frontend/src/components/Header.jsx b/frontend/src/components/Header.jsx index 1077701..b25807d 100644 --- a/frontend/src/components/Header.jsx +++ b/frontend/src/components/Header.jsx @@ -1,15 +1,19 @@ 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, Star, Bell, Github, Settings, ExternalLink } 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 { 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(); @@ -21,7 +25,14 @@ function Header() { 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 searchDebounceRef = useRef(null); + + // 授权系统 hub:版本 / 公告 / 在线人数 + const hub = useHub(); + const announcements = hub.announcements || []; + const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.2.0'; // 从全局 store 获取筛选状态 const selectedFormats = filters.formats || []; @@ -294,6 +305,88 @@ function Header() { ); const availableRatings = filterOptions.ratings; + // 右上角图标组:开源地址 / 通知 / 设置 / 版本号 + const rightIcons = ( + <> + + + + +
+ + + {showNotices && ( + <> +
setShowNotices(false)}>
+
+
+ 通知公告 + + {hub.online != null && 在线 {hub.online}} + {appVersion} + +
+ {announcements.length === 0 ? ( +
暂无公告
+ ) : ( +
+ {announcements.map((a, i) => ( +
+ {a.title && ( +
{a.title}
+ )} +
{a.content}
+
+ ))} +
+ )} + {hub.update_available && ( + + 发现新版本 {hub.latest},去更新 + + + )} +
+ + )} +
+ + + + + {appVersion} + + + setShowSettings(false)} versionLabel={appVersion} /> + + ); + // 移动端布局 if (isMobile) { // 文件夹视图不显示搜索和筛选 @@ -331,6 +424,8 @@ function Header() { )} + + {rightIcons} @@ -342,7 +437,7 @@ function Header() { 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" @@ -512,7 +607,7 @@ function Header() { 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" @@ -578,6 +673,9 @@ function Header() { )} + +
+ {rightIcons} diff --git a/frontend/src/components/SettingsModal.jsx b/frontend/src/components/SettingsModal.jsx new file mode 100644 index 0000000..b6b9981 --- /dev/null +++ b/frontend/src/components/SettingsModal.jsx @@ -0,0 +1,265 @@ +import { useState, useEffect } from 'react'; +import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink } from 'lucide-react'; +import { settingsAPI } from '../api'; + +const APP_VERSION = 'v1.2.0'; +const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic'; + +/** + * 设置弹窗:左侧菜单 + 右侧参数 + * - OCR 识别:本地 tesseract / 线上接口切换、线上参数、测试 + * - 关于:版本号 / 开源地址 + */ +export default function SettingsModal({ open, onClose, versionLabel }) { + const [active, setActive] = useState('ocr'); + const [cfg, setCfg] = useState(null); // { provider, online:{url,model,apiKeyMasked} } + const [apiKeyInput, setApiKeyInput] = useState(''); // 新密钥(留空=保持原密钥) + const [saving, setSaving] = useState(false); + const [testing, setTesting] = useState(false); + const [msg, setMsg] = useState(null); // { type, text } + + useEffect(() => { + if (!open) return; + setMsg(null); + setApiKeyInput(''); + 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 + })) + .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 // 空字符串 = 保留原密钥 + } + } + }; + const data = await settingsAPI.updateSettings(payload); + setCfg((c) => ({ ...(c || {}), ...data, online: { ...(c?.online || {}), ...(data?.online || {}) } })); + setApiKeyInput(''); + 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: 'about', label: '关于', icon: Info } + ]; + + return ( +
+
e.stopPropagation()} + > + {/* 左侧菜单 */} +
+
设置
+ {menus.map((m) => ( + + ))} +
+ + {/* 右侧参数 */} +
+
+

+ {active === 'ocr' ? 'OCR 识别设置' : '关于'} +

+ +
+ + {msg && ( +
{msg.text}
+ )} + + {active === 'ocr' && cfg && ( +
+

+ OCR 用于「图内文字搜索」:识别图片中的文字并建立索引,扫描素材库时自动执行。 +

+ + {/* 识别方式 */} +
+ +
+ + +
+
+ + {/* 线上参数 */} + {cfg.provider === 'online' && ( +
+
+ + 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" + /> +
+
+ + 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" + /> +
+
+ + 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" + /> +
+
+ )} + +
+ + +
+
+ )} + + {active === 'about' && ( +
+
+ 当前版本 + {versionLabel || APP_VERSION} +
+
+ 项目名称 + FlyPic 素材库 +
+ +

+ FlyPic 基于 ZangXincz/FlyPic 二次开发,修复多项问题并新增 OCR 图内文字搜索、线上 OCR、授权系统接入等能力。 +

+
+ )} +
+
+
+ ); +} diff --git a/frontend/src/hooks/useHub.js b/frontend/src/hooks/useHub.js new file mode 100644 index 0000000..25e705e --- /dev/null +++ b/frontend/src/hooks/useHub.js @@ -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;