feat: frp 录制电脑编排 + frps NewProxy 插件验证接口 + frpc 配置下发

This commit is contained in:
liufumingren 2026-07-26 19:44:08 +08:00
parent 56c8121590
commit fc9e514f93
5 changed files with 280 additions and 36 deletions

View File

@ -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}` };
}
}
}

123
app/controller/frp.js Normal file
View File

@ -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;

View File

@ -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);
};

View File

@ -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); // 删除旧的打印机信息

View File

@ -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,