From fc9e514f9337da4cf7ca72ea29e3c9061ef2783b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 26 Jul 2026 19:44:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20frp=20=E5=BD=95=E5=88=B6=E7=94=B5?= =?UTF-8?q?=E8=84=91=E7=BC=96=E6=8E=92=20+=20frps=20NewProxy=20=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E9=AA=8C=E8=AF=81=E6=8E=A5=E5=8F=A3=20+=20frpc=20?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E4=B8=8B=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/auth.js | 165 ++++++++++++++++++++++++++++++--------- app/controller/frp.js | 123 +++++++++++++++++++++++++++++ app/router.js | 1 + app/service/auth.js | 17 ++++ config/config.default.js | 10 +++ 5 files changed, 280 insertions(+), 36 deletions(-) create mode 100644 app/controller/frp.js diff --git a/app/controller/auth.js b/app/controller/auth.js index 0f3d168..aba44f6 100644 --- a/app/controller/auth.js +++ b/app/controller/auth.js @@ -143,15 +143,13 @@ class AuthController extends Controller { } // 外部通知电脑信息变更(拉取最新数据并推送给客户端) + // 自动检测 is_recording 变化,编排 frpc 启停 async refreshInfo() { const { ctx, app } = this; const { warehouse, computerId } = ctx.request.body; if (!warehouse || !computerId) { - ctx.body = { - status: 'fail', - message: '缺少必要参数: warehouse, computerId', - }; + ctx.body = { status: 'fail', message: '缺少必要参数: warehouse, computerId' }; return; } @@ -163,72 +161,167 @@ class AuthController extends Controller { }); if (!computerInfo) { - ctx.body = { - status: 'fail', - message: '未在数据库中找到该电脑信息', - }; + ctx.body = { status: 'fail', message: '未在数据库中找到该电脑信息' }; return; } - console.log(`刷新电脑信息: warehouse=${warehouse}, computerId=${computerId}`); + // 2. 检查旧缓存,对比 is_recording 是否变化 + const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`; + const oldCached = await app.redis.get(computerInfoKey); + const oldIsRecording = oldCached ? JSON.parse(oldCached).is_recording : null; + const newIsRecording = computerInfo.is_recording || 0; - // 2. 组装下发的 info 数据 + console.log(`刷新电脑信息: warehouse=${warehouse}, computerId=${computerId}, is_recording: ${oldIsRecording} → ${newIsRecording}`); + + // 3. 组装下发的 info 数据 const infoData = { name: computerInfo.name || '', status: computerInfo.status, - is_recording: computerInfo.is_recording || 0, + is_recording: newIsRecording, recording_size_value: computerInfo.recording_size_value || 0, recording_size_unit: computerInfo.recording_size_unit || '', remote_play_url: computerInfo.remote_play_url || '', recording_directory: computerInfo.recording_directory || '', }; - // 3. 查找电脑是否在线 - const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`; + // 4. 查找目标电脑是否在线 const cachedInfo = await app.redis.get(computerInfoKey); - if (!cachedInfo) { - // 电脑不在线,无需推送 + // === 场景A:电脑从非录制 → 录制,需要编排 frpc === + if (newIsRecording === 1 && oldIsRecording !== 1) { + console.log(`电脑 ${computerId} 被设置为录制电脑,开始编排 frpc`); + + // 4a. 扫描同仓库所有在线电脑 + const warehousePattern = `warehouse:${warehouse}:printer:*`; + const onlineKeys = []; + let cursor = '0'; + do { + const [nextCursor, keys] = await app.redis.scan(cursor, 'MATCH', warehousePattern, 'COUNT', 100); + cursor = nextCursor; + onlineKeys.push(...keys); + } while (cursor !== '0'); + + console.log(`仓库 ${warehouse} 在线电脑: ${onlineKeys.join(', ')}`); + + // 4b. 通知其他在线电脑断开 frpc + const disconnectPromises = []; + for (const key of onlineKeys) { + if (key === computerInfoKey) continue; // 跳过自己 + const otherData = await app.redis.get(key); + if (!otherData) continue; + const other = JSON.parse(otherData); + const otherComputerId = key.split(':').pop(); + console.log(`通知电脑 ${otherComputerId} 断开 frpc`); + + disconnectPromises.push( + app.ws.sendTo(other.uniqueId, JSON.stringify({ + method: 'setting.frpcDisconnect', + data: { reason: '同仓库录制电脑已变更' }, + })) + ); + // 清理其他电脑的 Redis 在线状态 + await app.redis.del(key); + await app.redis.del(other.uniqueId); + } + + // 4c. 等待其他电脑断开(最多 5 秒) + if (disconnectPromises.length > 0) { + const timeout = app.config.frp.disconnect_timeout || 5000; + await Promise.race([ + Promise.allSettled(disconnectPromises), + new Promise(resolve => setTimeout(resolve, timeout)), + ]); + console.log('其他电脑 frpc 断开通知已发出,等待完成'); + } + + // 4d. 生成 frp token 并更新目标电脑 + if (cachedInfo) { + const cached = JSON.parse(cachedInfo); + // 生成 frp 专用 token + const frpToken = app.jwt.sign( + { warehouse, computerId, purpose: 'frp' }, + app.config.jwt.secret, + { expiresIn: '24h' } + ); + const frpConfig = { + subdomain: `${app.config.frp.subdomain_prefix || 'w'}${warehouse}-c${computerId}`, + server_addr: app.config.frp.server_addr, + server_port: app.config.frp.server_port, + auth_token: app.config.frp.auth_token, + local_port: app.config.frp.local_port, + token: frpToken, + }; + const updatedData = { ...cached, ...infoData, frp: frpConfig }; + await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300); + + app.ws.sendTo(cached.uniqueId, JSON.stringify({ + method: 'setting.setInfo', + data: updatedData, + message: '录制电脑配置已更新,请连接frpc', + })); + } + ctx.body = { status: 'success', - message: '电脑当前离线,信息已保存,上线后将自动获取最新信息', + message: `录制电脑已设置,已通知 ${disconnectPromises.length} 台其他电脑断开 frpc`, + data: infoData, }; return; } + // === 场景B:电脑从录制 → 非录制,断开 frpc === + if (newIsRecording === 0 && oldIsRecording === 1) { + console.log(`电脑 ${computerId} 被取消录制,通知断开 frpc`); + + if (cachedInfo) { + const cached = JSON.parse(cachedInfo); + app.ws.sendTo(cached.uniqueId, JSON.stringify({ + method: 'setting.frpcDisconnect', + data: { reason: '录制电脑已被取消' }, + })); + const updatedData = { ...cached, ...infoData, frp: null }; + await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300); + + // 同时推送不带 frp 的更新 info + app.ws.sendTo(cached.uniqueId, JSON.stringify({ + method: 'setting.setInfo', + data: updatedData, + message: '录制电脑已取消', + })); + } + + ctx.body = { + status: 'success', + message: '录制电脑已取消,frpc 断开通知已发送', + data: infoData, + }; + return; + } + + // === 场景C:普通信息变更(is_recording 未变化或首次上线) === + if (!cachedInfo) { + ctx.body = { status: 'success', message: '电脑当前离线,信息已保存,上线后将自动获取最新信息' }; + return; + } + const cached = JSON.parse(cachedInfo); - const { uniqueId } = cached; - - // 4. 合并完整数据并更新 Redis 缓存 const updatedData = { ...cached, ...infoData }; await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300); - // 5. 向客户端推送最新信息 - const res = await app.ws.sendTo(uniqueId, JSON.stringify({ + const res = await app.ws.sendTo(cached.uniqueId, JSON.stringify({ method: 'setting.setInfo', - data: { ...cached, ...infoData }, + data: updatedData, message: '电脑信息已更新', })); - if (res !== 1) { - ctx.body = { - status: 'fail', - message: '推送信息失败,电脑可能已断开连接', - }; - return; - } - ctx.body = { - status: 'success', - message: '信息已推送', + status: res === 1 ? 'success' : 'fail', + message: res === 1 ? '信息已推送' : '推送失败,电脑可能已断开', data: infoData, }; } catch (error) { console.error('刷新电脑信息时发生错误:', error); - ctx.body = { - status: 'fail', - message: `刷新失败: ${error.message}`, - }; + ctx.body = { status: 'fail', message: `刷新失败: ${error.message}` }; } } } diff --git a/app/controller/frp.js b/app/controller/frp.js new file mode 100644 index 0000000..bcaf843 --- /dev/null +++ b/app/controller/frp.js @@ -0,0 +1,123 @@ +const { Controller } = require('egg'); + +/** + * frps NewProxy 插件验证接口 + * frps 每次创建代理时调用此接口验证 subdomain 归属 + */ +class FrpController extends Controller { + async newProxy() { + const { ctx, app } = this; + const { op, content } = ctx.request.body; + + console.log('[Frp Plugin] 收到验证请求:', JSON.stringify(ctx.request.body)); + + if (op !== 'NewProxy') { + ctx.status = 200; + ctx.body = { reject: false, unchange: true }; + return; + } + + if (!content || !content.subdomain) { + console.log('[Frp Plugin] 拒绝: 缺少 subdomain'); + ctx.status = 403; + ctx.body = { reject: true, rejectReason: '缺少 subdomain' }; + return; + } + + const subdomain = content.subdomain; + console.log(`[Frp Plugin] 验证 subdomain: ${subdomain}`); + + // 解析 subdomain: w{warehouse}-c{computerId} + const match = subdomain.match(/^w(\d+)-c(\d+)$/); + if (!match) { + console.log(`[Frp Plugin] 拒绝: subdomain 格式不正确: ${subdomain}`); + ctx.status = 403; + ctx.body = { reject: true, rejectReason: 'subdomain 格式不正确' }; + return; + } + + const warehouse = match[1]; + const computerId = match[2]; + console.log(`[Frp Plugin] 解析结果: warehouse=${warehouse}, computerId=${computerId}`); + + try { + // 1. 检查 Redis:该电脑是否在线且为录制电脑 + const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`; + const cachedInfo = await app.redis.get(computerInfoKey); + + if (!cachedInfo) { + console.log(`[Frp Plugin] 拒绝: 电脑不在线 warehouse=${warehouse}, computerId=${computerId}`); + ctx.status = 403; + ctx.body = { reject: true, rejectReason: '电脑不在线' }; + return; + } + + const onlineInfo = JSON.parse(cachedInfo); + if (onlineInfo.is_recording !== 1) { + console.log(`[Frp Plugin] 拒绝: 电脑不是录制电脑 warehouse=${warehouse}, computerId=${computerId}, is_recording=${onlineInfo.is_recording}`); + ctx.status = 403; + ctx.body = { reject: true, rejectReason: '电脑不是录制电脑' }; + return; + } + + // 2. 检查 DB:该电脑是否存在且未被删除 + const computerInfo = await app.mysql.get('wms').get('wms_print_computer', { + warehouse_id: warehouse, + id: computerId, + }); + + if (!computerInfo) { + console.log(`[Frp Plugin] 拒绝: 数据库中不存在 warehouse=${warehouse}, computerId=${computerId}`); + ctx.status = 403; + ctx.body = { reject: true, rejectReason: '数据库中不存在该电脑' }; + return; + } + + if (computerInfo.deleted_at) { + console.log(`[Frp Plugin] 拒绝: 电脑已删除 warehouse=${warehouse}, computerId=${computerId}`); + ctx.status = 403; + ctx.body = { reject: true, rejectReason: '电脑已被删除' }; + return; + } + + // 3. 检查同仓库是否已有其他录制电脑在线 + const warehousePattern = `warehouse:${warehouse}:printer:*`; + let cursor = '0'; + let hasOtherRecording = false; + do { + const [nextCursor, keys] = await app.redis.scan(cursor, 'MATCH', warehousePattern, 'COUNT', 100); + cursor = nextCursor; + for (const key of keys) { + if (key === computerInfoKey) continue; + const otherData = await app.redis.get(key); + if (!otherData) continue; + const other = JSON.parse(otherData); + if (other.is_recording === 1) { + console.log(`[Frp Plugin] 拒绝: 同仓库已有其他录制电脑在线: ${key}`); + hasOtherRecording = true; + break; + } + } + if (hasOtherRecording) break; + } while (cursor !== '0'); + + if (hasOtherRecording) { + ctx.status = 200; + ctx.body = { reject: true, rejectReason: '同仓库已有其他录制电脑在线' }; + return; + } + + // 全部验证通过 + console.log(`[Frp Plugin] 通过: warehouse=${warehouse}, computerId=${computerId}, name=${computerInfo.name}`); + ctx.status = 200; + ctx.body = { reject: false, unchange: true }; + + } catch (error) { + console.error('[Frp Plugin] 验证异常:', error); + ctx.status = 403; + ctx.body = { reject: true, rejectReason: `验证异常: ${error.message}` }; + } + } +} + +module.exports = FrpController; diff --git a/app/router.js b/app/router.js index 7e58468..d4727d7 100644 --- a/app/router.js +++ b/app/router.js @@ -7,6 +7,7 @@ module.exports = app => { router.post('/auth/bind', controller.auth.bind); router.post('/auth/logout', controller.auth.logout); router.post('/auth/refreshInfo', controller.auth.refreshInfo); + router.post('/frp/newProxy', controller.frp.newProxy); router.post('/sendToRoom', controller.home.sendToRoom); app.ws.route('/ws', controller.print.ws); }; \ No newline at end of file diff --git a/app/service/auth.js b/app/service/auth.js index 7af0637..45a6763 100644 --- a/app/service/auth.js +++ b/app/service/auth.js @@ -43,6 +43,23 @@ class AuthService extends BaseService { data.recording_size_unit = computerInfo.recording_size_unit || ''; data.remote_play_url = computerInfo.remote_play_url || ''; data.recording_directory = computerInfo.recording_directory || ''; + + // 如果是录制电脑,生成 frp 连接配置 + if (data.is_recording === 1) { + const frpToken = app.jwt.sign( + { warehouse, computerId, purpose: 'frp' }, + app.config.jwt.secret, + { expiresIn: '24h' } + ); + data.frp = { + subdomain: `${app.config.frp.subdomain_prefix || 'w'}${warehouse}-c${computerId}`, + server_addr: app.config.frp.server_addr, + server_port: app.config.frp.server_port, + auth_token: app.config.frp.auth_token, + local_port: app.config.frp.local_port, + token: frpToken, + }; + } } this.app.redis.del(key); // 删除旧的打印机信息 diff --git a/config/config.default.js b/config/config.default.js index 951f714..72992cb 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -75,6 +75,16 @@ module.exports = appInfo => { config.jwt = { secret: 'E5#ex.g@,GfL_8?', // 请替换为自己的密钥 }; + config.frp = { + server_addr: 'o.gztbyc.com', // frps 地址 + server_port: 6005, // frps bindPort + auth_token: 'a,13579,bmingming))*^', // frps auth.token + subdomain_host: 'o.gztbyc.com', // 子域名后缀 + vhost_http_port: 18080, // frps HTTP 代理端口(内部) + local_port: 8080, // 客户端本地 web 服务端口 + subdomain_prefix: 'w', // 子域名前缀 + disconnect_timeout: 5000, // 等待其他电脑断开 frpc 的超时(ms) + }; return { ...config, ...userConfig,