314 lines
14 KiB
JavaScript
314 lines
14 KiB
JavaScript
import { WebSocketServer } from 'ws';
|
||
import path from 'path';
|
||
import fs from 'fs';
|
||
import { pathToFileURL } from 'url';
|
||
import { isRecordingMode } from '../utils/runtime.js';
|
||
|
||
class WSServer {
|
||
/**
|
||
* @param {number|number[]} portCandidates 单个端口或端口候选数组
|
||
* @param {object} app Main 实例
|
||
* @param {object} options WebSocketServer 额外选项
|
||
*/
|
||
constructor(portCandidates, app, options = {}) {
|
||
this.portCandidates = Array.isArray(portCandidates)
|
||
? portCandidates.filter(p => Number.isFinite(p) && p > 0)
|
||
: (Number.isFinite(portCandidates) && portCandidates > 0 ? [portCandidates] : [8081]);
|
||
this.port = null; // 实际监听的端口(_start 成功后赋值)
|
||
this.options = options;
|
||
this.server = null;
|
||
this.clients = new Set();
|
||
this.services = app.services;
|
||
this.app = app;
|
||
this._eventHandlers = {};
|
||
this._start();
|
||
this._bindAppEvents();
|
||
}
|
||
|
||
_bindAppEvents() {
|
||
this._eventHandlers.printerComponentStatusChange = (data) => {
|
||
this.broadcast({ success: true, method: 'printerComponent.statusChange', result: data });
|
||
};
|
||
this._eventHandlers.wsClientStatusChange = (data) => {
|
||
this.broadcast({ success: true, method: 'wsClient.statusChange', result: data });
|
||
};
|
||
this._eventHandlers.generateCode = (code) => {
|
||
console.log('生成绑定码事件触发,数据:', code);
|
||
if (this.clients.size > 0) {
|
||
console.log("当前连接客户端数量:", this.clients.size);
|
||
this.broadcast({ success: true, method: 'bind.generateCode', result: code.randomCode });
|
||
const refreshDelay = (code.createdAt + (300 - 50) * 1000) - Date.now();
|
||
console.log("下次刷新绑定码时间:", new Date(Date.now() + refreshDelay).toLocaleTimeString());
|
||
if (this.app.CodeTimer) {
|
||
clearTimeout(this.app.CodeTimer);
|
||
}
|
||
this.app.CodeTimer = setTimeout(() => {
|
||
if (this.clients.size > 0) {
|
||
this.app.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||
}
|
||
}, refreshDelay);
|
||
}
|
||
};
|
||
this._eventHandlers.printerList = (data) => {
|
||
this.broadcast({ success: true, method: 'printer.getWindowsPrinters', result: data });
|
||
};
|
||
this._eventHandlers.updateDownloadProgress = (data) => {
|
||
this.broadcast({ success: true, method: 'update.downloadProgress', result: data });
|
||
};
|
||
this._eventHandlers.infoChanged = (data) => {
|
||
this.broadcast({ success: true, method: 'setting.infoChanged', result: data });
|
||
};
|
||
this._eventHandlers.frpcStatusChange = (data) => {
|
||
this.broadcast({ success: true, method: 'frpc.statusChange', result: data });
|
||
};
|
||
this._eventHandlers.migrationNeeded = (data) => {
|
||
this.broadcast({ success: true, method: 'setting.migrationNeeded', result: data });
|
||
};
|
||
|
||
this.app.on('printerComponentStatusChange', this._eventHandlers.printerComponentStatusChange);
|
||
this.app.on('wsClientStatusChange', this._eventHandlers.wsClientStatusChange);
|
||
this.app.on('generateCode', this._eventHandlers.generateCode);
|
||
this.app.on('printerList', this._eventHandlers.printerList);
|
||
this.app.on('updateDownloadProgress', this._eventHandlers.updateDownloadProgress);
|
||
this.app.on('infoChanged', this._eventHandlers.infoChanged);
|
||
this.app.on('frpcStatusChange', this._eventHandlers.frpcStatusChange);
|
||
this.app.on('migrationNeeded', this._eventHandlers.migrationNeeded);
|
||
}
|
||
|
||
_unbindAppEvents() {
|
||
if (!this._eventHandlers) {
|
||
return;
|
||
}
|
||
|
||
if (this._eventHandlers.printerComponentStatusChange) {
|
||
this.app.off('printerComponentStatusChange', this._eventHandlers.printerComponentStatusChange);
|
||
}
|
||
if (this._eventHandlers.wsClientStatusChange) {
|
||
this.app.off('wsClientStatusChange', this._eventHandlers.wsClientStatusChange);
|
||
}
|
||
if (this._eventHandlers.generateCode) {
|
||
this.app.off('generateCode', this._eventHandlers.generateCode);
|
||
}
|
||
if (this._eventHandlers.printerList) {
|
||
this.app.off('printerList', this._eventHandlers.printerList);
|
||
}
|
||
if (this._eventHandlers.updateDownloadProgress) {
|
||
this.app.off('updateDownloadProgress', this._eventHandlers.updateDownloadProgress);
|
||
}
|
||
if (this._eventHandlers.infoChanged) {
|
||
this.app.off('infoChanged', this._eventHandlers.infoChanged);
|
||
}
|
||
if (this._eventHandlers.frpcStatusChange) {
|
||
this.app.off('frpcStatusChange', this._eventHandlers.frpcStatusChange);
|
||
}
|
||
if (this._eventHandlers.migrationNeeded) {
|
||
this.app.off('migrationNeeded', this._eventHandlers.migrationNeeded);
|
||
}
|
||
|
||
this._eventHandlers = {};
|
||
}
|
||
_start() {
|
||
const tryPort = (index) => {
|
||
if (index >= this.portCandidates.length) {
|
||
console.error('[WSServer] 所有端口均被占用:', this.portCandidates);
|
||
return;
|
||
}
|
||
const candidate = this.portCandidates[index];
|
||
const server = new WebSocketServer({ port: candidate, ...this.options });
|
||
|
||
server.on('listening', () => {
|
||
this.port = candidate;
|
||
this.server = server;
|
||
console.log('[WSServer] WS 服务已启动,端口:', candidate);
|
||
this.app.emit('wsServerReady', { port: candidate });
|
||
});
|
||
|
||
server.on('error', (err) => {
|
||
if (err.code === 'EADDRINUSE') {
|
||
console.warn('[WSServer] 端口 %d 被占用,尝试下一个', candidate);
|
||
tryPort(index + 1);
|
||
return;
|
||
}
|
||
console.error('[WSServer] 端口 %d 启动失败:', candidate, err.message);
|
||
tryPort(index + 1);
|
||
});
|
||
|
||
server.on('connection', (ws, req) => {
|
||
this.clients.add(ws);
|
||
if (typeof this.onConnection === 'function') {
|
||
this.onConnection(ws, req);
|
||
}
|
||
ws.on('message', (msg) => {
|
||
this._handleMessage(ws, msg);
|
||
});
|
||
ws.on('close', () => {
|
||
this.clients.delete(ws);
|
||
if (this.clients.size === 0 && this.app.CodeTimer) {
|
||
clearTimeout(this.app.CodeTimer);
|
||
console.log('所有客户端已断开,清除绑定码定时器', this.app.CodeTimer);
|
||
this.app.CodeTimer = null;
|
||
}
|
||
console.log('[WSServer] 客户端断开,当前连接数:', this.clients.size);
|
||
});
|
||
ws.on('error', (err) => {
|
||
this.clients.delete(ws);
|
||
console.log('[WSServer] 客户端错误:', err.message);
|
||
});
|
||
});
|
||
};
|
||
|
||
tryPort(0);
|
||
}
|
||
async onConnection(ws, req) {
|
||
const tasks = [];
|
||
|
||
// 发送绑定状态
|
||
if (this.services.setting && typeof this.services.setting.info === 'function') {
|
||
try {
|
||
const info = this.services.setting.info(); // 同步调用
|
||
ws.send(JSON.stringify({ success: true, method: 'setting.info', result: info }));
|
||
} catch (err) {
|
||
ws.send(JSON.stringify({ success: false, message: '获取绑定状态失败: ' + err.message }));
|
||
}
|
||
} else {
|
||
ws.send(JSON.stringify({
|
||
success: false,
|
||
message: 'setting.info 服务不可用',
|
||
debug: {
|
||
availableServices: Object.keys(this.services || {}),
|
||
settingType: typeof this.services?.setting,
|
||
settingKeys: this.services?.setting ? Object.keys(this.services.setting) : []
|
||
}
|
||
}));
|
||
}
|
||
|
||
// 发送打印组件列表(录制模式跳过)
|
||
if (isRecordingMode(this.app.config)) {
|
||
// 录制模式:静默跳过,不发送错误
|
||
} else if (this.services.printerComponent && typeof this.services.printerComponent.getAll === 'function') {
|
||
try {
|
||
const components = this.services.printerComponent.getAll(); // 同步调用
|
||
ws.send(JSON.stringify({ success: true, method: 'printerComponent.getAll', result: components }));
|
||
} catch (err) {
|
||
ws.send(JSON.stringify({ success: false, message: '获取打印组件列表失败: ' + err.message }));
|
||
}
|
||
} else {
|
||
ws.send(JSON.stringify({ success: false, message: 'printerComponent.getAll 服务不可用' }));
|
||
}
|
||
|
||
// 发送打印机列表(录制模式跳过)
|
||
if (isRecordingMode(this.app.config)) {
|
||
// 录制模式:静默跳过
|
||
} else if (this.services.printer && typeof this.services.printer.getWindowsPrinters === 'function') {
|
||
tasks.push(
|
||
this.services.printer.getWindowsPrinters()
|
||
);
|
||
} else {
|
||
ws.send(JSON.stringify({ success: false, message: 'printer.getWindowsPrinters 服务不可用' }));
|
||
}
|
||
|
||
// 发送 WebSocket 客户端状态
|
||
if (this.app.wsClient) {
|
||
ws.send(JSON.stringify({ success: true, method: 'wsClient.statusChange', result: { status: this.app.wsClient.status } }));
|
||
}
|
||
// 发送 frpc 初始状态(弥补时序:frpc 可能在 wsServer 启动前就已就绪)
|
||
if (this.services.frpc && typeof this.services.frpc.getStatus === 'function') {
|
||
try {
|
||
const frpcStatus = this.services.frpc.getStatus();
|
||
ws.send(JSON.stringify({ success: true, method: 'frpc.statusChange', result: frpcStatus }));
|
||
} catch (err) {
|
||
ws.send(JSON.stringify({ success: false, message: '获取 frpc 状态失败: ' + err.message }));
|
||
}
|
||
}
|
||
if (!this.app.config.token) {
|
||
//检测是否随机码过期
|
||
if (this.app.randomCode) {
|
||
console.log('当前随机码:', this.app.randomCode);
|
||
console.log('当前时间:', new Date().toLocaleTimeString());
|
||
console.log('随机码过期时间:', new Date(this.app.randomCode.createdAt + this.app.randomCode.expiresIn * 1000).toLocaleTimeString());
|
||
}
|
||
if (this.app.randomCode && this.app.randomCode.createdAt + this.app.randomCode.expiresIn * 1000 > Date.now() && this.app.randomCode.randomCode) {
|
||
this.app.emit('generateCode', this.app.randomCode);
|
||
} else {
|
||
this.app.randomCode = null;
|
||
this.app.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||
}
|
||
}
|
||
// 并行执行所有任务
|
||
await Promise.all(tasks);
|
||
}
|
||
async _handleMessage(ws, msg) {
|
||
// 兼容 Buffer 类型消息
|
||
if (Buffer.isBuffer(msg)) {
|
||
msg = msg.toString('utf8');
|
||
}
|
||
//console.log('[WSServer] 收到消息:', msg);
|
||
let parsed;
|
||
try {
|
||
parsed = typeof msg === 'string' ? JSON.parse(msg) : msg;
|
||
} catch {
|
||
ws.send(JSON.stringify({ success: false, message: '消息解析失败' }));
|
||
return;
|
||
}
|
||
const { method, data, _callId, _msgId } = parsed;
|
||
// 统一回显请求 ID:优先 _msgId(Electron 桥接),兼容 _callId(页面直连)
|
||
const replyId = _msgId || _callId;
|
||
if (!method) {
|
||
ws.send(JSON.stringify({ success: false, message: 'method不能为空', _msgId: replyId, _callId: replyId }));
|
||
return;
|
||
}
|
||
// 支持多级目录结构,如 index.index.index
|
||
const methodPath = method.split('.');
|
||
let serviceFn = this.services;
|
||
for (let i = 0; i < methodPath.length; i++) {
|
||
serviceFn = serviceFn[methodPath[i]];
|
||
if (!serviceFn) break;
|
||
}
|
||
if (typeof serviceFn === 'function') {
|
||
try {
|
||
const result = await serviceFn(data);
|
||
ws.send(JSON.stringify({ success: true, method, result, _msgId: replyId, _callId: replyId }));
|
||
} catch (err) {
|
||
//console.log(err);
|
||
ws.send(JSON.stringify({ success: false, method, message: '服务方法执行失败: ' + err.message, _msgId: replyId, _callId: replyId }));
|
||
}
|
||
} else {
|
||
ws.send(JSON.stringify({
|
||
success: false,
|
||
method,
|
||
message: '未找到对应服务方法',
|
||
_msgId: replyId,
|
||
_callId: replyId,
|
||
debug: {
|
||
method,
|
||
methodPath,
|
||
availableServices: Object.keys(this.services || {}),
|
||
topLevelTargetType: typeof this.services?.[methodPath[0]],
|
||
topLevelTargetKeys: this.services?.[methodPath[0]] ? Object.keys(this.services[methodPath[0]]) : []
|
||
}
|
||
}));
|
||
}
|
||
}
|
||
|
||
broadcast(data) {
|
||
const message = typeof data === 'string' ? data : JSON.stringify(data);
|
||
for (const client of this.clients) {
|
||
if (client.readyState === WebSocket.OPEN) {
|
||
client.send(message);
|
||
//console.log('[WSServer] 广播消息:', message);
|
||
}
|
||
}
|
||
}
|
||
|
||
close() {
|
||
if (this.server) {
|
||
this.server.close();
|
||
this.clients.clear();
|
||
//console.log('[WSServer] 服务端关闭');
|
||
}
|
||
this._unbindAppEvents();
|
||
}
|
||
}
|
||
|
||
export default WSServer;
|