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 前缀
This commit is contained in:
jinghui committed 2026-11-16 21:57:03 +08:00
1 parent ffb47a0f81
commit 50c53a5e21
18 files changed
+961 -15

No files matched your search

+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();
+4
View File
@@ -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) => {
+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' // 版本检查/公告(无敏感数据)
];
// 前缀匹配的公开路径(缩略图 & 原图资源)
+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;
+99
View File
@@ -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 = `<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;
+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 };
+77
View File
@@ -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 };