334 lines
14 KiB
JavaScript
334 lines
14 KiB
JavaScript
const Controller = require('egg').Controller;
|
||
|
||
class AuthController extends Controller {
|
||
async bind() {
|
||
const { ctx, app } = this;
|
||
const { roomId, warehouse, computerId } = ctx.request.body;
|
||
const code = ctx.request.body.code || '';
|
||
const printer = ctx.request.body.printer || '';
|
||
console.log('Received bind request with parameters:', { roomId, code, printer, warehouse, computerId });
|
||
if (!roomId || !warehouse || !computerId) {
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: '缺少必要参数: roomId, warehouse, computerId',
|
||
};
|
||
return;
|
||
}
|
||
|
||
try {
|
||
// 检查房间是否在线
|
||
const roomData = await app.redis.get(roomId);
|
||
if (!roomData) {
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: '房间不在线',
|
||
};
|
||
return;
|
||
}
|
||
|
||
// 生成 JWT 和刷新令牌
|
||
const jwtToken = app.jwt.sign({ code, printer, warehouse, computerId }, app.config.jwt.secret, {
|
||
expiresIn: '1h',
|
||
});
|
||
const refreshToken = app.jwt.sign({ code, printer, warehouse, computerId }, app.config.jwt.secret, {
|
||
expiresIn: '100years',
|
||
});
|
||
console.log('发送消息到room:', roomId, { jwtToken, refreshToken });
|
||
if (app.ws.getRooms) {
|
||
const rooms = await app.ws.getRooms();
|
||
console.log('所有活跃房间:', rooms);
|
||
}
|
||
|
||
const tokenExpireTime = Date.now() + 3600 * 1000; // 1 hour
|
||
const res = await app.ws.sendTo(roomId, JSON.stringify({ data: { jwtToken, refreshToken, tokenExpireTime }, method: 'bind.tokenInfo' }));
|
||
console.log('消息发送结果:', res);
|
||
|
||
// 判断消息是否发送成功
|
||
if (res !== 1) {
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: '房间不在线',
|
||
};
|
||
return;
|
||
}
|
||
|
||
// 下发令牌
|
||
ctx.body = {
|
||
message: '令牌生成成功',
|
||
jwtToken,
|
||
refreshToken,
|
||
status: 'success',
|
||
};
|
||
} catch (error) {
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: `绑定失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
// 外部通知注销电脑(强制下线)
|
||
async logout() {
|
||
const { ctx, app } = this;
|
||
const { warehouse, computerId } = ctx.request.body;
|
||
|
||
if (!warehouse || !computerId) {
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: '缺少必要参数: warehouse, computerId',
|
||
};
|
||
return;
|
||
}
|
||
|
||
try {
|
||
// 1. 核实数据库:确认电脑存在
|
||
const computerInfo = await app.mysql.get('wms').get('wms_print_computer', {
|
||
warehouse_id: warehouse,
|
||
id: computerId,
|
||
});
|
||
|
||
if (!computerInfo) {
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: '未在数据库中找到该电脑信息',
|
||
};
|
||
return;
|
||
}
|
||
|
||
console.log(`注销电脑: warehouse=${warehouse}, computerId=${computerId}, deleted_at=${computerInfo.deleted_at}`);
|
||
|
||
// 2. 从 Redis 查找电脑是否在线
|
||
const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`;
|
||
const cachedInfo = await app.redis.get(computerInfoKey);
|
||
|
||
if (!cachedInfo) {
|
||
// 电脑不在线,但数据库验证已通过,返回成功(已离线无需操作)
|
||
ctx.body = {
|
||
status: 'success',
|
||
message: '电脑当前离线,无需注销',
|
||
};
|
||
return;
|
||
}
|
||
|
||
const { uniqueId } = JSON.parse(cachedInfo);
|
||
|
||
// 3. 向客户端发送解绑注销命令
|
||
const res = await app.ws.sendTo(uniqueId, JSON.stringify({
|
||
method: 'setting.unbind',
|
||
data: { reason: '管理员强制注销' },
|
||
}));
|
||
|
||
// 4. 清理 Redis 中的在线状态
|
||
await app.redis.del(computerInfoKey);
|
||
await app.redis.del(uniqueId);
|
||
console.log(`已清理 Redis: ${computerInfoKey}, ${uniqueId}`);
|
||
|
||
if (res !== 1) {
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: '发送注销命令失败,电脑可能已断开连接',
|
||
};
|
||
return;
|
||
}
|
||
|
||
ctx.body = {
|
||
status: 'success',
|
||
message: '注销命令已发送',
|
||
};
|
||
} catch (error) {
|
||
console.error('注销电脑时发生错误:', error);
|
||
ctx.body = {
|
||
status: 'fail',
|
||
message: `注销失败: ${error.message}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
// 外部通知电脑信息变更(拉取最新数据并推送给客户端)
|
||
// 自动检测 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' };
|
||
return;
|
||
}
|
||
|
||
try {
|
||
// 1. 从数据库拉取最新电脑信息
|
||
const computerInfo = await app.mysql.get('wms').get('wms_print_computer', {
|
||
warehouse_id: warehouse,
|
||
id: computerId,
|
||
});
|
||
|
||
if (!computerInfo) {
|
||
ctx.body = { status: 'fail', message: '未在数据库中找到该电脑信息' };
|
||
return;
|
||
}
|
||
|
||
// 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;
|
||
|
||
console.log(`刷新电脑信息: warehouse=${warehouse}, computerId=${computerId}, is_recording: ${oldIsRecording} → ${newIsRecording}`);
|
||
|
||
// 3. 组装下发的 info 数据
|
||
const infoData = {
|
||
name: computerInfo.name || '',
|
||
status: computerInfo.status,
|
||
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 || '',
|
||
};
|
||
|
||
// 4. 查找目标电脑是否在线
|
||
const cachedInfo = await app.redis.get(computerInfoKey);
|
||
|
||
// === 场景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, _source: 'refreshInfo-recording' };
|
||
await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300);
|
||
|
||
console.log(`[setInfo] 来源=refreshInfo(录制), computer=${computerId}, warehouse=${warehouse}`);
|
||
app.ws.sendTo(cached.uniqueId, JSON.stringify({
|
||
method: 'setting.setInfo',
|
||
data: updatedData,
|
||
message: '录制电脑配置已更新,请连接frpc',
|
||
}));
|
||
}
|
||
|
||
ctx.body = {
|
||
status: 'success',
|
||
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, _source: 'refreshInfo-unrecording' };
|
||
await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300);
|
||
|
||
console.log(`[setInfo] 来源=refreshInfo(取消录制), computer=${computerId}, warehouse=${warehouse}`);
|
||
// 同时推送不带 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 updatedData = { ...cached, ...infoData, _source: 'refreshInfo-normal' };
|
||
await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300);
|
||
|
||
console.log(`[setInfo] 来源=refreshInfo(普通), computer=${computerId}, warehouse=${warehouse}`);
|
||
const res = await app.ws.sendTo(cached.uniqueId, JSON.stringify({
|
||
method: 'setting.setInfo',
|
||
data: updatedData,
|
||
message: '电脑信息已更新',
|
||
}));
|
||
|
||
ctx.body = {
|
||
status: res === 1 ? 'success' : 'fail',
|
||
message: res === 1 ? '信息已推送' : '推送失败,电脑可能已断开',
|
||
data: infoData,
|
||
};
|
||
} catch (error) {
|
||
console.error('刷新电脑信息时发生错误:', error);
|
||
ctx.body = { status: 'fail', message: `刷新失败: ${error.message}` };
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = AuthController; |