1
This commit is contained in:
parent
b0cbc3c666
commit
da67b15465
@ -10,7 +10,7 @@
|
|||||||
"reconnectInterval": 3000
|
"reconnectInterval": 3000
|
||||||
},
|
},
|
||||||
"refreshTokenExpireTime": 0,
|
"refreshTokenExpireTime": 0,
|
||||||
"tokenExpireTime": 1780469814666,
|
"tokenExpireTime": 1780684406126,
|
||||||
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3ODA0NjYyMTQsImV4cCI6MTc4MDQ2OTgxNH0.kR9RugjGPeSLijWn4Enq93Hf2Pn63DToxS6C82ElzxE",
|
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3ODA2ODA4MDYsImV4cCI6MTc4MDY4NDQwNn0.O3Kzn4dVqkzSY8YT6nN_RpulznGPq4_LY6SY6o30cGk",
|
||||||
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3Nzg2MTAwNDMsImV4cCI6NDkzNDM3MDA0M30.JkOtPdc6VA5IDxy6E6Pqk5nffmE5VagoXtXYr7cNLZc"
|
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3YXJlaG91c2UiOiIxMDAwMDAiLCJjb21wdXRlcklkIjoiMjgiLCJpYXQiOjE3Nzg2MTAwNDMsImV4cCI6NDkzNDM3MDA0M30.JkOtPdc6VA5IDxy6E6Pqk5nffmE5VagoXtXYr7cNLZc"
|
||||||
}
|
}
|
||||||
23
core/main.js
23
core/main.js
@ -41,6 +41,7 @@ class Main extends EventEmitter {
|
|||||||
reconnectInterval: this.config.remoteWs.reconnectInterval || 3000
|
reconnectInterval: this.config.remoteWs.reconnectInterval || 3000
|
||||||
}, this);
|
}, this);
|
||||||
this.wsServer = new WSServer(this.config.wsPort, this);
|
this.wsServer = new WSServer(this.config.wsPort, this);
|
||||||
|
console.log('[Main] 本地 WS 服务已启动,端口:', this.config.wsPort);
|
||||||
this._initWmiPrinterMonitor();
|
this._initWmiPrinterMonitor();
|
||||||
this.app.on('printerWmiStatusChange', (data) => {
|
this.app.on('printerWmiStatusChange', (data) => {
|
||||||
//console.log('打印机状态变化事件触发,数据:', data);
|
//console.log('打印机状态变化事件触发,数据:', data);
|
||||||
@ -112,35 +113,15 @@ class Main extends EventEmitter {
|
|||||||
await this._loadServices();
|
await this._loadServices();
|
||||||
}
|
}
|
||||||
|
|
||||||
restartLocalWsServer(newPort) {
|
|
||||||
const port = Number(newPort);
|
|
||||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
||||||
throw new Error('wsPort 无效');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.wsServer) {
|
|
||||||
this.wsServer.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.config.wsPort = port;
|
|
||||||
this.wsServer = new WSServer(port, this);
|
|
||||||
return {
|
|
||||||
wsPort: port
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async restartBackendRuntime(options = {}) {
|
async restartBackendRuntime(options = {}) {
|
||||||
const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 3001;
|
const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 3001;
|
||||||
if (!Number.isInteger(wsPort) || wsPort < 1 || wsPort > 65535) {
|
|
||||||
throw new Error('wsPort 无效');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。
|
// 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。
|
||||||
if (hasProcessArg('--backend-runner') || hasProcessArg('--service-runner')) {
|
if (hasProcessArg('--backend-runner') || hasProcessArg('--service-runner')) {
|
||||||
return { wsPort };
|
return { wsPort };
|
||||||
}
|
}
|
||||||
|
|
||||||
this.restartLocalWsServer(wsPort);
|
this.config.wsPort = wsPort;
|
||||||
|
|
||||||
if (this.wsClient) {
|
if (this.wsClient) {
|
||||||
this.wsClient.close();
|
this.wsClient.close();
|
||||||
|
|||||||
@ -2,8 +2,9 @@
|
|||||||
<id>printserver.exe</id>
|
<id>printserver.exe</id>
|
||||||
<name>PrintServer</name>
|
<name>PrintServer</name>
|
||||||
<description>printServer backend service</description>
|
<description>printServer backend service</description>
|
||||||
<executable>C:\Program Files\nodejs\node.exe</executable>
|
<executable>D:\printServer\node_modules\electron\dist\electron.exe</executable>
|
||||||
<argument>D:\printServer\index.js</argument>
|
<argument>D:\printServer</argument>
|
||||||
|
<argument>--service-runner</argument>
|
||||||
<logmode>rotate</logmode>
|
<logmode>rotate</logmode>
|
||||||
<startmode>Automatic</startmode>
|
<startmode>Automatic</startmode>
|
||||||
<stoptimeout>30sec</stoptimeout>
|
<stoptimeout>30sec</stoptimeout>
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
const { app, BrowserWindow, Menu, Tray, nativeImage } = require('electron');
|
const { app, BrowserWindow, Menu, Tray, nativeImage, ipcMain } = require('electron');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const net = require('net');
|
const net = require('net');
|
||||||
const { spawn } = require('child_process');
|
const { spawn } = require('child_process');
|
||||||
@ -9,6 +9,9 @@ let tray = null;
|
|||||||
let isQuitting = false;
|
let isQuitting = false;
|
||||||
let serverStarted = false;
|
let serverStarted = false;
|
||||||
let backendProcess = null;
|
let backendProcess = null;
|
||||||
|
let backendApp = null; // 开发模式:后端 Main 实例
|
||||||
|
let backendWS = null; // 打包模式:后端 WS 桥接
|
||||||
|
let backendWSCleanup = []; // 事件取消函数列表
|
||||||
let reconcileTimer = null;
|
let reconcileTimer = null;
|
||||||
let reconcilePromise = null;
|
let reconcilePromise = null;
|
||||||
|
|
||||||
@ -38,7 +41,9 @@ async function startLocalServer() {
|
|||||||
|
|
||||||
serverStarted = true;
|
serverStarted = true;
|
||||||
const entryFile = path.join(__dirname, '..', 'index.js');
|
const entryFile = path.join(__dirname, '..', 'index.js');
|
||||||
await import(pathToFileURL(entryFile).href);
|
const indexModule = await import(pathToFileURL(entryFile).href);
|
||||||
|
backendApp = indexModule.default; // 获取 Main 单例
|
||||||
|
console.log('[Main] 后端已加载,services:', Object.keys(backendApp.services || {}));
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasArg(flag) {
|
function hasArg(flag) {
|
||||||
@ -83,12 +88,50 @@ function isPortReachable(port) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function isBackendReady() {
|
async function isBackendReady() {
|
||||||
const [httpReady, wsReady] = await Promise.all([
|
return isPortReachable(3001);
|
||||||
isPortReachable(3000),
|
}
|
||||||
isPortReachable(3001)
|
|
||||||
]);
|
|
||||||
|
|
||||||
return httpReady && wsReady;
|
// ─── 打包模式:WS 桥接(连接子进程的本地 WS 服务) ───
|
||||||
|
let _bridgeConnectPromise = null;
|
||||||
|
async function ensureBackendBridge() {
|
||||||
|
if (!app.isPackaged || backendApp) return;
|
||||||
|
if (backendWS && backendWS.readyState === 1) return;
|
||||||
|
if (_bridgeConnectPromise) return _bridgeConnectPromise;
|
||||||
|
|
||||||
|
_bridgeConnectPromise = (async function () {
|
||||||
|
var config = await readRuntimeConfig();
|
||||||
|
var wsPort = config.wsPort || 3001;
|
||||||
|
var mod = await import('ws');
|
||||||
|
var WebSocketImpl = mod.default || mod.WebSocket || require('ws');
|
||||||
|
|
||||||
|
return new Promise(function (resolve, reject) {
|
||||||
|
var ws = new WebSocketImpl('ws://127.0.0.1:' + wsPort);
|
||||||
|
var connected = false;
|
||||||
|
ws.on('open', function () {
|
||||||
|
connected = true;
|
||||||
|
backendWS = ws;
|
||||||
|
console.log('[Bridge] 已连接后端 WS, port:', wsPort);
|
||||||
|
ws.on('message', function (msg) {
|
||||||
|
try {
|
||||||
|
var data = JSON.parse(msg.toString());
|
||||||
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
|
mainWindow.webContents.send('service:event', data);
|
||||||
|
}
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
});
|
||||||
|
ws.on('close', function () { backendWS = null; _bridgeConnectPromise = null; });
|
||||||
|
ws.on('error', function () { backendWS = null; _bridgeConnectPromise = null; });
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
ws.on('error', function (err) { if (!connected) { _bridgeConnectPromise = null; reject(err); } });
|
||||||
|
setTimeout(function () { if (!connected) { _bridgeConnectPromise = null; reject(new Error('Bridge timeout')); } }, 5000);
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|
||||||
|
try { await _bridgeConnectPromise; } catch (e) {
|
||||||
|
console.error('[Bridge] 连接失败:', e.message);
|
||||||
|
_bridgeConnectPromise = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readRuntimeConfig() {
|
async function readRuntimeConfig() {
|
||||||
@ -96,6 +139,256 @@ async function readRuntimeConfig() {
|
|||||||
return configUtil.read();
|
return configUtil.read();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ────────── IPC 处理 ──────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调用后端服务方法(开发模式直接调用,打包模式通过内部 WS 桥接)
|
||||||
|
*/
|
||||||
|
async function handleServiceCall(method, data, allowRetry) {
|
||||||
|
// 特殊方法:获取远端 WSClient 当前状态
|
||||||
|
if (method === 'wsClient.getStatus') {
|
||||||
|
if (backendApp && backendApp.wsClient) {
|
||||||
|
return { success: true, method, result: { status: backendApp.wsClient.status, url: backendApp.wsClient.url } };
|
||||||
|
}
|
||||||
|
// 打包模式:通过桥接获取
|
||||||
|
if (backendWS && backendWS.readyState === 1) {
|
||||||
|
var _ws = backendWS;
|
||||||
|
return new Promise(function (resolve) {
|
||||||
|
var mid = method + '_' + Date.now() + '_' + Math.random().toString(36).slice(2);
|
||||||
|
var settled = false;
|
||||||
|
var handler = function (raw) {
|
||||||
|
if (settled) return;
|
||||||
|
try {
|
||||||
|
var resp = JSON.parse(raw.toString());
|
||||||
|
if (resp.method === method || resp._msgId === mid) {
|
||||||
|
settled = true;
|
||||||
|
if (_ws && _ws.removeListener) _ws.removeListener('message', handler);
|
||||||
|
resolve(resp);
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
};
|
||||||
|
_ws.on('message', handler);
|
||||||
|
_ws.send(JSON.stringify({ method: method, data: data, _msgId: mid }));
|
||||||
|
setTimeout(function () {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
if (_ws && _ws.removeListener) _ws.removeListener('message', handler);
|
||||||
|
resolve({ success: false, method: method, message: 'Bridge timeout' });
|
||||||
|
}, 10000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { success: false, method, message: 'WSClient not ready' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 开发模式:进程内直接调用
|
||||||
|
if (backendApp && backendApp.services) {
|
||||||
|
var methodPath = method.split('.');
|
||||||
|
var fn = backendApp.services;
|
||||||
|
for (var i = 0; i < methodPath.length; i++) {
|
||||||
|
fn = fn[methodPath[i]];
|
||||||
|
if (!fn) break;
|
||||||
|
}
|
||||||
|
if (typeof fn === 'function') {
|
||||||
|
try {
|
||||||
|
var result = await fn(data);
|
||||||
|
return { success: true, method: method, result: result };
|
||||||
|
} catch (err) {
|
||||||
|
return { success: false, method: method, message: err.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { success: false, method: method, message: '服务方法未找到: ' + method };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打包模式:通过 WS 桥接转发到子进程
|
||||||
|
if (backendWS && backendWS.readyState === 1) {
|
||||||
|
var _ws2 = backendWS;
|
||||||
|
return new Promise(function (resolve) {
|
||||||
|
var mid = method + '_' + Date.now() + '_' + Math.random().toString(36).slice(2);
|
||||||
|
var settled = false;
|
||||||
|
var handler = function (raw) {
|
||||||
|
if (settled) return;
|
||||||
|
try {
|
||||||
|
var resp = JSON.parse(raw.toString());
|
||||||
|
if (resp.method === method || resp._msgId === mid) {
|
||||||
|
settled = true;
|
||||||
|
if (_ws2 && _ws2.removeListener) _ws2.removeListener('message', handler);
|
||||||
|
resolve(resp);
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
};
|
||||||
|
_ws2.on('message', handler);
|
||||||
|
_ws2.send(JSON.stringify({ method: method, data: data, _msgId: mid }));
|
||||||
|
setTimeout(function () {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
if (_ws2 && _ws2.removeListener) _ws2.removeListener('message', handler);
|
||||||
|
resolve({ success: false, method: method, message: 'Bridge timeout' });
|
||||||
|
}, 10000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打包模式:桥接未就绪,尝试重新建立连接(仅重试一次,防止无限递归)
|
||||||
|
if (allowRetry !== false && app.isPackaged && !backendApp) {
|
||||||
|
await ensureBackendBridge();
|
||||||
|
if (backendWS && backendWS.readyState === 1) {
|
||||||
|
return handleServiceCall(method, data, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, method: method, message: '后端尚未就绪' };
|
||||||
|
}
|
||||||
|
|
||||||
|
ipcMain.handle('service:call', async (_event, method, data) => {
|
||||||
|
return handleServiceCall(method, data, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 获取后端连接状态 */
|
||||||
|
ipcMain.handle('service:getBackendStatus', () => {
|
||||||
|
if (backendApp) return 'connected';
|
||||||
|
if (backendWS && backendWS.readyState === 1) return 'connected';
|
||||||
|
return 'connecting';
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册后端事件 → 渲染进程转发(替代 WSServer.onConnection / _bindAppEvents)
|
||||||
|
*/
|
||||||
|
function setupEventForwarding() {
|
||||||
|
if (!backendApp) return;
|
||||||
|
cleanupEventForwarding();
|
||||||
|
|
||||||
|
const forward = (eventMethod) => (data) => {
|
||||||
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
|
mainWindow.webContents.send('service:event', {
|
||||||
|
success: true,
|
||||||
|
method: eventMethod,
|
||||||
|
result: data
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 与 WSServer._bindAppEvents 相同的事件集
|
||||||
|
backendApp.on('printerComponentStatusChange', forward('printerComponent.statusChange'));
|
||||||
|
|
||||||
|
// wsClient 状态变化改用防抖转发,避免短暂断开/重连导致 UI 闪烁
|
||||||
|
let wsStatusDebounceTimer = null;
|
||||||
|
const forwardWsStatus = (data) => {
|
||||||
|
if (wsStatusDebounceTimer) {
|
||||||
|
clearTimeout(wsStatusDebounceTimer);
|
||||||
|
wsStatusDebounceTimer = null;
|
||||||
|
}
|
||||||
|
// connected 立即转发;disconnected/error 延迟 2 秒确认
|
||||||
|
const delayMs = data.status === 'connected' ? 0 : 2000;
|
||||||
|
wsStatusDebounceTimer = setTimeout(() => {
|
||||||
|
wsStatusDebounceTimer = null;
|
||||||
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
|
mainWindow.webContents.send('service:event', {
|
||||||
|
success: true,
|
||||||
|
method: 'wsClient.statusChange',
|
||||||
|
result: data
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, delayMs);
|
||||||
|
};
|
||||||
|
backendApp.on('wsClientStatusChange', forwardWsStatus);
|
||||||
|
|
||||||
|
// 推送当前 WSClient 状态(弥补监听注册前已连接的时序缺口)
|
||||||
|
if (backendApp.wsClient?.status) {
|
||||||
|
forwardWsStatus({ status: backendApp.wsClient.status, url: backendApp.wsClient.url });
|
||||||
|
}
|
||||||
|
|
||||||
|
backendApp.on('printerList', forward('printer.getWindowsPrinters'));
|
||||||
|
|
||||||
|
const generateCodeHandler = (code) => {
|
||||||
|
console.log('[IPC] generateCode 事件转发, randomCode:', code?.randomCode);
|
||||||
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
|
mainWindow.webContents.send('service:event', {
|
||||||
|
success: true,
|
||||||
|
method: 'bind.generateCode',
|
||||||
|
result: code.randomCode
|
||||||
|
});
|
||||||
|
console.log('[IPC] service:event 已发送 -> bind.generateCode');
|
||||||
|
} else {
|
||||||
|
console.log('[IPC] mainWindow 不可用, 无法转发');
|
||||||
|
}
|
||||||
|
// 码过期前 5 秒自动刷新
|
||||||
|
if (code.createdAt && code.expiresIn) {
|
||||||
|
var refreshAt = code.createdAt + code.expiresIn * 1000 - 5000;
|
||||||
|
var delay = Math.max(0, refreshAt - Date.now());
|
||||||
|
if (backendApp._codeRefreshTimer) clearTimeout(backendApp._codeRefreshTimer);
|
||||||
|
var remaining = Math.round(delay / 1000);
|
||||||
|
console.log('[IPC] 绑定码刷新定时器已设置, ' + remaining + ' 秒后触发');
|
||||||
|
backendApp._codeRefreshTimer = setTimeout(function () {
|
||||||
|
console.log('[IPC] 绑定码刷新定时器触发');
|
||||||
|
console.log('[IPC] hasToken:', !!backendApp.config?.token, 'wsClientStatus:', backendApp.wsClient?.status);
|
||||||
|
if (!backendApp.config?.token && backendApp.wsClient?.status === 'connected') {
|
||||||
|
console.log('[IPC] 请求新绑定码');
|
||||||
|
backendApp.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||||||
|
} else {
|
||||||
|
console.log('[IPC] 跳过刷新: token=' + !!backendApp.config?.token + ' ws=' + backendApp.wsClient?.status);
|
||||||
|
}
|
||||||
|
}, delay);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
backendApp.on('generateCode', generateCodeHandler);
|
||||||
|
|
||||||
|
backendApp.on('updateDownloadProgress', forward('update.downloadProgress'));
|
||||||
|
|
||||||
|
// ─── 主动请求绑定码(替代 WSServer.onConnection),仅首次未绑定时请求一次 ───
|
||||||
|
let bindCodeRequested = false;
|
||||||
|
const requestBindCode = () => {
|
||||||
|
if (bindCodeRequested || backendApp.config?.token) return;
|
||||||
|
bindCodeRequested = true;
|
||||||
|
|
||||||
|
if (backendApp.randomCode &&
|
||||||
|
backendApp.randomCode.createdAt + backendApp.randomCode.expiresIn * 1000 > Date.now() &&
|
||||||
|
backendApp.randomCode.randomCode) {
|
||||||
|
backendApp.emit('generateCode', backendApp.randomCode);
|
||||||
|
} else if (backendApp.wsClient?.status === 'connected') {
|
||||||
|
backendApp.randomCode = null;
|
||||||
|
backendApp.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 监听 WSClient 连接事件,连接后尝试请求绑定码
|
||||||
|
const wsStatusHandler = (data) => {
|
||||||
|
if (data.status === 'connected') {
|
||||||
|
requestBindCode();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
backendApp.on('wsClientStatusChange', wsStatusHandler);
|
||||||
|
|
||||||
|
// 如果 WSClient 已连接,立即尝试
|
||||||
|
if (backendApp.wsClient?.status === 'connected') {
|
||||||
|
requestBindCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
backendWSCleanup = [
|
||||||
|
() => backendApp.off('printerComponentStatusChange'),
|
||||||
|
() => {
|
||||||
|
if (wsStatusDebounceTimer) { clearTimeout(wsStatusDebounceTimer); wsStatusDebounceTimer = null; }
|
||||||
|
backendApp.off('wsClientStatusChange', forwardWsStatus);
|
||||||
|
},
|
||||||
|
() => backendApp.off('printerList'),
|
||||||
|
() => backendApp.off('generateCode', generateCodeHandler),
|
||||||
|
() => backendApp.off('updateDownloadProgress'),
|
||||||
|
() => backendApp.off('wsClientStatusChange', wsStatusHandler)
|
||||||
|
];
|
||||||
|
|
||||||
|
console.log('[Main] 事件转发已注册');
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupEventForwarding() {
|
||||||
|
for (const cleanup of backendWSCleanup) {
|
||||||
|
try { cleanup(); } catch (_) { /* ignore */ }
|
||||||
|
}
|
||||||
|
backendWSCleanup = [];
|
||||||
|
if (backendApp && backendApp._codeRefreshTimer) {
|
||||||
|
clearTimeout(backendApp._codeRefreshTimer);
|
||||||
|
backendApp._codeRefreshTimer = null;
|
||||||
|
}
|
||||||
|
console.log('[Main] 事件转发已清理');
|
||||||
|
}
|
||||||
|
|
||||||
async function getWindowsServiceHelper() {
|
async function getWindowsServiceHelper() {
|
||||||
return loadWorkspaceModule('utils/windowsService.js');
|
return loadWorkspaceModule('utils/windowsService.js');
|
||||||
}
|
}
|
||||||
@ -209,6 +502,10 @@ function startReconcileLoop() {
|
|||||||
reconcileBackendState().catch((error) => {
|
reconcileBackendState().catch((error) => {
|
||||||
console.error('[Runtime] 状态同步失败:', error);
|
console.error('[Runtime] 状态同步失败:', error);
|
||||||
});
|
});
|
||||||
|
// 同时确保 WS 桥接保持连接
|
||||||
|
ensureBackendBridge().catch((error) => {
|
||||||
|
console.error('[Bridge] 周期重连失败:', error && error.message);
|
||||||
|
});
|
||||||
}, RECONCILE_INTERVAL_MS);
|
}, RECONCILE_INTERVAL_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -239,18 +536,9 @@ function loadMainPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
readRuntimeConfig()
|
mainWindow.loadFile(MAIN_FILE).catch(() => {
|
||||||
.then((config) => {
|
setTimeout(loadMainPage, 1000);
|
||||||
const wsPort = Number(config?.wsPort) || 3001;
|
});
|
||||||
return mainWindow.loadFile(MAIN_FILE, {
|
|
||||||
query: {
|
|
||||||
wsPort: String(wsPort)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
setTimeout(loadMainPage, 1000);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function createMainWindow() {
|
function createMainWindow() {
|
||||||
@ -265,7 +553,8 @@ function createMainWindow() {
|
|||||||
icon: ICON_ICO_PATH,
|
icon: ICON_ICO_PATH,
|
||||||
webPreferences: {
|
webPreferences: {
|
||||||
contextIsolation: true,
|
contextIsolation: true,
|
||||||
nodeIntegration: false
|
nodeIntegration: false,
|
||||||
|
preload: path.join(__dirname, 'preload.cjs')
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -321,6 +610,8 @@ async function bootstrap() {
|
|||||||
|
|
||||||
await reconcileBackendState();
|
await reconcileBackendState();
|
||||||
startReconcileLoop();
|
startReconcileLoop();
|
||||||
|
await ensureBackendBridge(); // 打包模式:建立与后端子进程的 WS 桥接
|
||||||
|
setupEventForwarding();
|
||||||
createMainWindow();
|
createMainWindow();
|
||||||
createTray();
|
createTray();
|
||||||
}
|
}
|
||||||
|
|||||||
48
electron/preload.cjs
Normal file
48
electron/preload.cjs
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
const { contextBridge, ipcRenderer } = require('electron');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预加载脚本 — 通过 contextBridge 暴露安全的 IPC API 到渲染进程。
|
||||||
|
* 渲染进程通过 window.printServerAPI 调用,不再直接连接 WebSocket。
|
||||||
|
*/
|
||||||
|
contextBridge.exposeInMainWorld('printServerAPI', {
|
||||||
|
/**
|
||||||
|
* 调用后端服务方法(替代 wsSendWithCallback)
|
||||||
|
* @param {string} method 服务方法路径,如 'printer.getWindowsPrinters'
|
||||||
|
* @param {any} data 请求参数
|
||||||
|
* @returns {Promise<{success: boolean, method: string, result: any}>}
|
||||||
|
*/
|
||||||
|
callService: (method, data) =>
|
||||||
|
ipcRenderer.invoke('service:call', method, data),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听服务端推送事件(替代 wsOn)
|
||||||
|
* @param {string} method 事件名
|
||||||
|
* @param {Function} callback 接收 {success, method, result}
|
||||||
|
* @returns {Function} 取消订阅函数
|
||||||
|
*/
|
||||||
|
onEvent: (method, callback) => {
|
||||||
|
const handler = (_event, payload) => {
|
||||||
|
if (payload.method === method) callback(payload);
|
||||||
|
};
|
||||||
|
ipcRenderer.on('service:event', handler);
|
||||||
|
return () => ipcRenderer.removeListener('service:event', handler);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取后端连接状态
|
||||||
|
* @returns {Promise<string>} 'connected' | 'disconnected'
|
||||||
|
*/
|
||||||
|
getBackendStatus: () =>
|
||||||
|
ipcRenderer.invoke('service:getBackendStatus'),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听后端连接状态变化(替代 setWsClientStatus 回调)
|
||||||
|
* @param {Function} callback
|
||||||
|
* @returns {Function} 取消订阅函数
|
||||||
|
*/
|
||||||
|
onBackendStatusChange: (callback) => {
|
||||||
|
const handler = (_event, status) => callback(status);
|
||||||
|
ipcRenderer.on('backend:status', handler);
|
||||||
|
return () => ipcRenderer.removeListener('backend:status', handler);
|
||||||
|
}
|
||||||
|
});
|
||||||
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "printserver",
|
"name": "printserver",
|
||||||
"version": "1.0.10",
|
"version": "1.0.14",
|
||||||
"main": "electron/main.cjs",
|
"main": "electron/main.cjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node index.js",
|
"start": "node index.js",
|
||||||
@ -44,6 +44,7 @@
|
|||||||
"views/**/*",
|
"views/**/*",
|
||||||
"index.js",
|
"index.js",
|
||||||
"package.json",
|
"package.json",
|
||||||
|
"!electron/assets/icon-gray.svg",
|
||||||
"!config.json",
|
"!config.json",
|
||||||
"!临时/**/*",
|
"!临时/**/*",
|
||||||
"!开发日志/**/*",
|
"!开发日志/**/*",
|
||||||
|
|||||||
@ -8,14 +8,23 @@ const configPath = path.join(__dirname, '../config.json');
|
|||||||
class BindService extends service {
|
class BindService extends service {
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
this.generateCode = this.generateCode.bind(this); // 确保上下文绑定
|
this.generateCode = this.generateCode.bind(this);
|
||||||
this.tokenInfo = this.tokenInfo.bind(this); // 确保上下文绑定
|
this.tokenInfo = this.tokenInfo.bind(this);
|
||||||
|
this.getCurrentCode = this.getCurrentCode.bind(this);
|
||||||
}
|
}
|
||||||
generateCode(data) {
|
generateCode(data) {
|
||||||
const {app} = this;
|
const {app} = this;
|
||||||
this.app.randomCode = data;
|
this.app.randomCode = data;
|
||||||
this.app.emit('generateCode', data);
|
this.app.emit('generateCode', data);
|
||||||
}
|
}
|
||||||
|
// 获取当前缓存的随机码(渲染进程挂载后调用,弥补 IPC 事件可能早于监听注册的时序问题)
|
||||||
|
getCurrentCode() {
|
||||||
|
const { app } = this;
|
||||||
|
if (app.randomCode && app.randomCode.createdAt + app.randomCode.expiresIn * 1000 > Date.now()) {
|
||||||
|
return app.randomCode.randomCode;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
tokenInfo(data) {
|
tokenInfo(data) {
|
||||||
const {app} = this;
|
const {app} = this;
|
||||||
app.config.token = data.jwtToken;
|
app.config.token = data.jwtToken;
|
||||||
|
|||||||
@ -107,10 +107,14 @@ class SettingService extends service {
|
|||||||
}
|
}
|
||||||
// 解绑(WebSocket/HTTP 通用,无 ctx 依赖)
|
// 解绑(WebSocket/HTTP 通用,无 ctx 依赖)
|
||||||
unbind() {
|
unbind() {
|
||||||
const { config } = this;
|
const { config, app } = this;
|
||||||
config.token = '';
|
config.token = '';
|
||||||
configUtil.write(config);
|
configUtil.write(config);
|
||||||
this.app.isBind = false;
|
app.isBind = false;
|
||||||
|
// 解绑后主动请求新绑定码
|
||||||
|
if (app.wsClient?.status === 'connected') {
|
||||||
|
app.wsClient.send({ method: 'bind.generateCode', data: {} });
|
||||||
|
}
|
||||||
return { ok: true, message: '解绑成功' };
|
return { ok: true, message: '解绑成功' };
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -194,7 +198,7 @@ class SettingService extends service {
|
|||||||
}
|
}
|
||||||
async setInfo(data) {
|
async setInfo(data) {
|
||||||
const { config, app } = this;
|
const { config, app } = this;
|
||||||
config.name = data.name;
|
config.name = data.computerInfo?.name || data.name || '';
|
||||||
console.log("设置打印台信息", data);
|
console.log("设置打印台信息", data);
|
||||||
app.info = data;
|
app.info = data;
|
||||||
configUtil.write(config);
|
configUtil.write(config);
|
||||||
|
|||||||
596
views/index.html
596
views/index.html
@ -74,6 +74,7 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@ -81,11 +82,15 @@
|
|||||||
color: var(--text);
|
color: var(--text);
|
||||||
background: linear-gradient(150deg, #f8fbff 0%, var(--bg) 72%);
|
background: linear-gradient(150deg, #f8fbff 0%, var(--bg) 72%);
|
||||||
padding: 12px;
|
padding: 12px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
#app {
|
#app {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: calc(100vh - 24px);
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
background: var(--panel);
|
background: var(--panel);
|
||||||
border: 1px solid var(--line);
|
border: 1px solid var(--line);
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
@ -537,7 +542,7 @@
|
|||||||
|
|
||||||
<div class="tabbar">
|
<div class="tabbar">
|
||||||
<button class="tab" :class="{ active: activeTab === 'overview' }" @click="activeTab = 'overview'">运行总览</button>
|
<button class="tab" :class="{ active: activeTab === 'overview' }" @click="activeTab = 'overview'">运行总览</button>
|
||||||
<button class="tab" :class="{ active: activeTab === 'extension' }" @click="activeTab = 'extension'">端口设置</button>
|
<button class="tab" :class="{ active: activeTab === 'extension' }" @click="activeTab = 'extension'">设置</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="content">
|
<div class="content">
|
||||||
@ -586,17 +591,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tab-panel" v-show="activeTab === 'extension'">
|
<div class="tab-panel" v-show="activeTab === 'extension'">
|
||||||
<div class="placeholder">
|
<div class="update-card">
|
||||||
<h3 style="margin:0 0 12px 0;color:#2c425d;">端口设置</h3>
|
|
||||||
<div class="form-row">
|
|
||||||
<label for="wsPort">本地 WS 端口</label>
|
|
||||||
<input id="wsPort" type="number" min="1" max="65535" v-model.number="portForm.wsPort">
|
|
||||||
<button class="refresh-btn" @click="savePorts" :disabled="portSaving || restartingBackend">保存并重连</button>
|
|
||||||
</div>
|
|
||||||
<div class="hint">保存后会自动重启后端,并让页面重新连接到新的 WS 端口。</div>
|
|
||||||
<div class="inline-ok" v-if="saveMessage">{{ saveMessage }}</div>
|
|
||||||
|
|
||||||
<div class="update-card">
|
|
||||||
<h4 class="update-title">应用更新</h4>
|
<h4 class="update-title">应用更新</h4>
|
||||||
<div class="update-meta">
|
<div class="update-meta">
|
||||||
<span>当前版本:{{ updateState.currentVersion || '-' }}</span>
|
<span>当前版本:{{ updateState.currentVersion || '-' }}</span>
|
||||||
@ -627,12 +622,7 @@
|
|||||||
<span class="status-dot" :style="{ backgroundColor: wsStatus[wsClientStatus].color }"></span>
|
<span class="status-dot" :style="{ backgroundColor: wsStatus[wsClientStatus].color }"></span>
|
||||||
<span>本地服务:<strong :style="{color: wsStatus[wsClientStatus].color}">{{ wsStatus[wsClientStatus].title }}</strong></span>
|
<span>本地服务:<strong :style="{color: wsStatus[wsClientStatus].color}">{{ wsStatus[wsClientStatus].title }}</strong></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="status-item">
|
|
||||||
<span class="status-dot" :style="{ backgroundColor: isServices ? '#107c10' : '#c42b1c' }"></span>
|
|
||||||
<span>服务注册:
|
|
||||||
<strong class="status-link" :style="{ color: isServices ? '#107c10' : '#c42b1c' }" @click="isServices ? unregister() : register()">{{ isServices ? '已注册' : '未注册' }}</strong>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="status-item">
|
<div class="status-item">
|
||||||
<span class="status-dot" :style="{ backgroundColor: wsStatus[wsServerStatus].color }"></span>
|
<span class="status-dot" :style="{ backgroundColor: wsStatus[wsServerStatus].color }"></span>
|
||||||
<span>服务器连接:<strong :style="{color: wsStatus[wsServerStatus].color}">{{ wsStatus[wsServerStatus].title }}</strong></span>
|
<span>服务器连接:<strong :style="{color: wsStatus[wsServerStatus].color}">{{ wsStatus[wsServerStatus].title }}</strong></span>
|
||||||
@ -641,10 +631,11 @@
|
|||||||
<span class="status-dot" :style="{ backgroundColor: isBind ? '#107c10' : '#c42b1c' }"></span>
|
<span class="status-dot" :style="{ backgroundColor: isBind ? '#107c10' : '#c42b1c' }"></span>
|
||||||
<span>打印服务绑定:<strong :style="{ color: isBind ? '#107c10' : '#c42b1c' }">{{ isBind ? '已绑定' : '未绑定' }}</strong></span>
|
<span>打印服务绑定:<strong :style="{ color: isBind ? '#107c10' : '#c42b1c' }">{{ isBind ? '已绑定' : '未绑定' }}</strong></span>
|
||||||
</div>
|
</div>
|
||||||
<button class="status-action" @click="checkUpdate(true)" :disabled="updateChecking">{{ updateChecking ? '检查中...' : '检查更新' }}</button>
|
<button class="status-action" id="btnCheckUpdate">{{ updateChecking ? '检查中...' : '检查更新' }}</button>
|
||||||
<button class="status-action restart" @click="confirmRestartBackend" :disabled="restartingBackend">{{ restartingBackend ? '重启中...' : '重启服务' }}</button>
|
<button class="status-action restart" id="btnRestartBackend">{{ restartingBackend ? '重启中...' : '重启服务' }}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function initApp() {
|
(function initApp() {
|
||||||
if (!window.__depsReady) {
|
if (!window.__depsReady) {
|
||||||
@ -658,106 +649,10 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let ws;
|
// ─── IPC 通讯层 ───
|
||||||
const runtimeParams = new URLSearchParams(window.location.search || '');
|
// 使用 window.printServerAPI(由 preload.cjs 通过 contextBridge 注入)
|
||||||
const runtimeWsPort = Number(runtimeParams.get('wsPort')) || 3001;
|
// callService(method, data) → Promise
|
||||||
let wsUrl = `ws://127.0.0.1:${runtimeWsPort}`;
|
// onEvent(method, callback) → unsubscribe function
|
||||||
let reconnectTimer = null;
|
|
||||||
function setWsClientStatus(status) {
|
|
||||||
const app = document.getElementById('app').__vue__;
|
|
||||||
if (!app) return;
|
|
||||||
if (typeof app.onLocalWsStatusChange === 'function') {
|
|
||||||
app.onLocalWsStatusChange(status);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
app.wsClientStatus = status;
|
|
||||||
}
|
|
||||||
// 全局事件监听器注册表
|
|
||||||
let wsMethodListeners = {};
|
|
||||||
// 只定义一次 wsOn
|
|
||||||
function wsOn(method, callback) {
|
|
||||||
if (!wsMethodListeners[method]) wsMethodListeners[method] = [];
|
|
||||||
wsMethodListeners[method].push(callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
function connectWS() {
|
|
||||||
setWsClientStatus(reconnectTimer ? 'reconnecting' : 'connecting');
|
|
||||||
ws = new WebSocket(wsUrl);
|
|
||||||
ws.onopen = function () {
|
|
||||||
console.log('WebSocket 已连接');
|
|
||||||
if (reconnectTimer) {
|
|
||||||
clearTimeout(reconnectTimer);
|
|
||||||
reconnectTimer = null;
|
|
||||||
}
|
|
||||||
setWsClientStatus('connected');
|
|
||||||
};
|
|
||||||
ws.onmessage = function (event) {
|
|
||||||
try {
|
|
||||||
const resp = JSON.parse(event.data);
|
|
||||||
if (resp.method && wsMethodListeners[resp.method]) {
|
|
||||||
wsMethodListeners[resp.method].forEach(cb => cb(resp));
|
|
||||||
}
|
|
||||||
} catch (e) { }
|
|
||||||
};
|
|
||||||
ws.onclose = function () {
|
|
||||||
console.log('WebSocket 断开,3秒后重连');
|
|
||||||
setWsClientStatus('reconnecting');
|
|
||||||
reconnectTimer = setTimeout(connectWS, 3000);
|
|
||||||
};
|
|
||||||
ws.onerror = function (err) {
|
|
||||||
console.log('WebSocket 错误:', err);
|
|
||||||
// 统一由 onclose 处理重连与状态,避免 error/disconnected 来回抖动。
|
|
||||||
if (ws && ws.readyState !== WebSocket.CLOSED) {
|
|
||||||
ws.close();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function reconnectWSWithPort(nextWsPort) {
|
|
||||||
const portNum = Number(nextWsPort) || runtimeWsPort;
|
|
||||||
wsUrl = `ws://127.0.0.1:${portNum}`;
|
|
||||||
|
|
||||||
if (reconnectTimer) {
|
|
||||||
clearTimeout(reconnectTimer);
|
|
||||||
reconnectTimer = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ws) {
|
|
||||||
try {
|
|
||||||
ws.onclose = null;
|
|
||||||
ws.close();
|
|
||||||
} catch (e) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
connectWS();
|
|
||||||
}
|
|
||||||
connectWS();
|
|
||||||
|
|
||||||
// 封装 ws 发送并监听回调
|
|
||||||
function wsSendWithCallback(method, data, callback) {
|
|
||||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
||||||
// Directly update the status instead of showing an alert
|
|
||||||
setWsClientStatus('reconnecting');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
function handler(event) {
|
|
||||||
try {
|
|
||||||
const resp = JSON.parse(event.data);
|
|
||||||
if (resp.method === method) {
|
|
||||||
ws.removeEventListener('message', handler);
|
|
||||||
callback(resp);
|
|
||||||
}
|
|
||||||
} catch (e) { }
|
|
||||||
}
|
|
||||||
ws.addEventListener('message', handler);
|
|
||||||
ws.send(JSON.stringify({ method, data }));
|
|
||||||
}
|
|
||||||
// 按钮事件绑定需在 DOM 渲染后执行
|
|
||||||
window.onload = function () {
|
|
||||||
var refreshBtn = document.getElementById('refreshPrinters');
|
|
||||||
if (refreshBtn) {
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
new Vue({
|
new Vue({
|
||||||
el: '#app',
|
el: '#app',
|
||||||
@ -767,17 +662,12 @@
|
|||||||
components: [],
|
components: [],
|
||||||
statusList: [],
|
statusList: [],
|
||||||
isBind: false,
|
isBind: false,
|
||||||
wsClientStatus: 'disconnected',
|
wsClientStatus: 'connected',
|
||||||
wsServerStatus: 'disconnected',
|
wsServerStatus: 'disconnected',
|
||||||
name: '',
|
name: '',
|
||||||
saveMessage: '',
|
|
||||||
portSaving: false,
|
|
||||||
restartingBackend: false,
|
restartingBackend: false,
|
||||||
updateChecking: false,
|
updateChecking: false,
|
||||||
updatingInApp: false,
|
updatingInApp: false,
|
||||||
portForm: {
|
|
||||||
wsPort: runtimeWsPort
|
|
||||||
},
|
|
||||||
updateState: {
|
updateState: {
|
||||||
hasUpdate: false,
|
hasUpdate: false,
|
||||||
currentVersion: '',
|
currentVersion: '',
|
||||||
@ -790,7 +680,7 @@
|
|||||||
message: ''
|
message: ''
|
||||||
},
|
},
|
||||||
code: '',
|
code: '',
|
||||||
qrcode: new QRCode("qrcode"),
|
qrcode: null,
|
||||||
wsStatus: {
|
wsStatus: {
|
||||||
'disconnected': { title: '未连接', color: 'red' },
|
'disconnected': { title: '未连接', color: 'red' },
|
||||||
'connecting': { title: '连接中', color: '#f59f00' },
|
'connecting': { title: '连接中', color: '#f59f00' },
|
||||||
@ -798,7 +688,6 @@
|
|||||||
'connected': { title: '已连接', color: 'green' },
|
'connected': { title: '已连接', color: 'green' },
|
||||||
'error': { title: '连接错误', color: 'red' },
|
'error': { title: '连接错误', color: 'red' },
|
||||||
},
|
},
|
||||||
isServices: false
|
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
updateProgressPercent() {
|
updateProgressPercent() {
|
||||||
@ -838,7 +727,7 @@
|
|||||||
return `${size.toFixed(idx === 0 ? 0 : 2)} ${units[idx]}`;
|
return `${size.toFixed(idx === 0 ? 0 : 2)} ${units[idx]}`;
|
||||||
},
|
},
|
||||||
loadComponents() {
|
loadComponents() {
|
||||||
wsSendWithCallback('printerComponent.getAll', {}, (data) => {
|
window.printServerAPI.callService('printerComponent.getAll', {}).then((data) => {
|
||||||
console.log('获取组件列表:', data);
|
console.log('获取组件列表:', data);
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
this.components = data.result.components || [];
|
this.components = data.result.components || [];
|
||||||
@ -862,7 +751,7 @@
|
|||||||
return normalized === 'true' || normalized === '1' || normalized === 'yes';
|
return normalized === 'true' || normalized === '1' || normalized === 'yes';
|
||||||
},
|
},
|
||||||
loadPrinters() {
|
loadPrinters() {
|
||||||
wsSendWithCallback('printer.getWindowsPrinters', {}, (data) => {
|
window.printServerAPI.callService('printer.getWindowsPrinters', {}).then((data) => {
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
this.printers = data.result || [];
|
this.printers = data.result || [];
|
||||||
if (this.printers.length === 0) {
|
if (this.printers.length === 0) {
|
||||||
@ -875,121 +764,46 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
register() {
|
|
||||||
wsSendWithCallback('setting.register', {}, (data) => {
|
|
||||||
if (data.success && data.result && data.result.ok) {
|
|
||||||
this.isServices = !!(data.result && (data.result.isService ?? data.result.isServices));
|
|
||||||
} else {
|
|
||||||
alert((data.result && data.result.message) || data.message || '系统服务注册失败!');
|
|
||||||
this.refreshBindStatus();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
unregister() {
|
|
||||||
wsSendWithCallback('setting.unregister', {}, (data) => {
|
|
||||||
if (data.success && data.result && data.result.ok) {
|
|
||||||
this.isServices = !!(data.result && (data.result.isService ?? data.result.isServices));
|
|
||||||
} else {
|
|
||||||
alert((data.result && data.result.message) || data.message || '系统服务注销失败!');
|
|
||||||
this.refreshBindStatus();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
refreshBindStatus() {
|
refreshBindStatus() {
|
||||||
wsSendWithCallback('setting.info', {}, (data) => {
|
window.printServerAPI.callService('setting.info', {}).then((data) => {
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
this.isBind = data.result.isBind || false;
|
this.isBind = data.result.isBind || false;
|
||||||
this.isServices = data.result.isService || false;
|
this.name = data.result.name || '';
|
||||||
this.portForm.wsPort = Number(data.result.wsPort) || this.portForm.wsPort;
|
|
||||||
} else {
|
} else {
|
||||||
alert(data.message || '获取绑定状态失败!');
|
alert(data.message || '获取绑定状态失败!');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
savePorts() {
|
onBackendStatusChange(status) {
|
||||||
if (!this.portForm.wsPort) {
|
|
||||||
alert('端口不能为空');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.portForm.wsPort < 1 || this.portForm.wsPort > 65535) {
|
|
||||||
alert('端口范围应为 1-65535');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.portSaving = true;
|
|
||||||
this.saveMessage = '';
|
|
||||||
|
|
||||||
wsSendWithCallback('setting.updatePorts', {
|
|
||||||
wsPort: Number(this.portForm.wsPort)
|
|
||||||
}, (data) => {
|
|
||||||
this.portSaving = false;
|
|
||||||
if (!data.success || !data.result || !data.result.ok) {
|
|
||||||
alert((data.result && data.result.message) || data.message || '端口保存失败');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.saveMessage = data.result.message || '端口已更新';
|
|
||||||
this.portForm.wsPort = Number(data.result.wsPort) || this.portForm.wsPort;
|
|
||||||
if (data.result.requiresBackendRestart) {
|
|
||||||
this.requestBackendRestart({
|
|
||||||
wsPort: Number(data.result.wsPort) || this.portForm.wsPort,
|
|
||||||
successMessage: '端口已保存,后端重启中...'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
startRestartWatch(timeoutMs, errorMessage) {
|
|
||||||
if (this._restartWatchTimer) {
|
|
||||||
clearTimeout(this._restartWatchTimer);
|
|
||||||
this._restartWatchTimer = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._restartWatchTimer = setTimeout(() => {
|
|
||||||
if (!this.restartingBackend) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.restartingBackend = false;
|
|
||||||
alert(errorMessage || '后端重启失败,请检查端口是否被占用后重试');
|
|
||||||
}, timeoutMs || 15000);
|
|
||||||
},
|
|
||||||
onLocalWsStatusChange(status) {
|
|
||||||
this.wsClientStatus = status;
|
this.wsClientStatus = status;
|
||||||
if (status === 'connected' && this.restartingBackend) {
|
if (status === 'connected' && this.restartingBackend) {
|
||||||
this.restartingBackend = false;
|
this.restartingBackend = false;
|
||||||
if (this._restartWatchTimer) {
|
|
||||||
clearTimeout(this._restartWatchTimer);
|
|
||||||
this._restartWatchTimer = null;
|
|
||||||
}
|
|
||||||
this.saveMessage = '后端已重启并连接成功';
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
requestBackendRestart(options = {}) {
|
requestBackendRestart() {
|
||||||
if (this.restartingBackend) {
|
if (this.restartingBackend) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
||||||
alert('当前本地服务未连接,无法发送重启指令,请稍后重试');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const targetWsPort = Number(options.wsPort) || Number(this.portForm.wsPort) || runtimeWsPort;
|
|
||||||
this.restartingBackend = true;
|
this.restartingBackend = true;
|
||||||
|
|
||||||
wsSendWithCallback('setting.restartBackend', {
|
window.printServerAPI.callService('setting.restartBackend', {}).then((data) => {
|
||||||
wsPort: targetWsPort
|
|
||||||
}, (data) => {
|
|
||||||
if (!data.success || !data.result || !data.result.ok) {
|
if (!data.success || !data.result || !data.result.ok) {
|
||||||
this.restartingBackend = false;
|
this.restartingBackend = false;
|
||||||
alert((data.result && data.result.message) || data.message || '后端重启失败');
|
alert((data.result && data.result.message) || data.message || '后端重启失败');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.saveMessage = options.successMessage || data.result.message || '后端重启中...';
|
this.restartingBackend = false;
|
||||||
reconnectWSWithPort(Number(data.result.wsPort) || targetWsPort);
|
// 重启后刷新数据
|
||||||
this.startRestartWatch(15000, '后端重启失败,15 秒内未恢复连接,请检查端口占用后重试');
|
setTimeout(() => {
|
||||||
|
this.refreshBindStatus();
|
||||||
|
this.loadComponents();
|
||||||
|
this.loadPrinters();
|
||||||
|
}, 500);
|
||||||
|
}).catch(() => {
|
||||||
|
this.restartingBackend = false;
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
confirmRestartBackend() {
|
confirmRestartBackend() {
|
||||||
@ -998,10 +812,7 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.requestBackendRestart({
|
this.requestBackendRestart();
|
||||||
wsPort: Number(this.portForm.wsPort) || runtimeWsPort,
|
|
||||||
successMessage: '后端重启中...'
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
checkUpdate(manual = false) {
|
checkUpdate(manual = false) {
|
||||||
if (this.updateChecking) {
|
if (this.updateChecking) {
|
||||||
@ -1009,7 +820,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.updateChecking = true;
|
this.updateChecking = true;
|
||||||
wsSendWithCallback('update.check', {}, (data) => {
|
window.printServerAPI.callService('update.check', {}).then((data) => {
|
||||||
this.updateChecking = false;
|
this.updateChecking = false;
|
||||||
|
|
||||||
if (!data.success || !data.result || !data.result.ok) {
|
if (!data.success || !data.result || !data.result.ok) {
|
||||||
@ -1050,11 +861,6 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
||||||
alert('当前本地服务未连接,无法开始更新,请稍后重试');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.updateState.hasUpdate) {
|
if (!this.updateState.hasUpdate) {
|
||||||
alert('当前没有可用更新');
|
alert('当前没有可用更新');
|
||||||
return;
|
return;
|
||||||
@ -1075,10 +881,10 @@
|
|||||||
message: '开始下载更新包...'
|
message: '开始下载更新包...'
|
||||||
};
|
};
|
||||||
|
|
||||||
wsSendWithCallback('update.downloadAndInstall', {
|
window.printServerAPI.callService('update.downloadAndInstall', {
|
||||||
downloadUrl: this.updateState.downloadUrl,
|
downloadUrl: this.updateState.downloadUrl,
|
||||||
version: this.updateState.latestVersion
|
version: this.updateState.latestVersion
|
||||||
}, (data) => {
|
}).then((data) => {
|
||||||
if (!data.success || !data.result || !data.result.ok) {
|
if (!data.success || !data.result || !data.result.ok) {
|
||||||
this.updatingInApp = false;
|
this.updatingInApp = false;
|
||||||
alert((data.result && data.result.message) || data.message || '启动更新失败');
|
alert((data.result && data.result.message) || data.message || '启动更新失败');
|
||||||
@ -1097,9 +903,9 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
wsSendWithCallback('update.openDownloadedInstaller', {
|
window.printServerAPI.callService('update.openDownloadedInstaller', {
|
||||||
filePath: this.updateState.filePath
|
filePath: this.updateState.filePath
|
||||||
}, (data) => {
|
}).then((data) => {
|
||||||
if (!data.success || !data.result || !data.result.ok) {
|
if (!data.success || !data.result || !data.result.ok) {
|
||||||
alert((data.result && data.result.message) || data.message || '启动安装向导失败');
|
alert((data.result && data.result.message) || data.message || '启动安装向导失败');
|
||||||
return;
|
return;
|
||||||
@ -1109,7 +915,7 @@
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
unbind() {
|
unbind() {
|
||||||
wsSendWithCallback('setting.unbind', {}, (data) => {
|
window.printServerAPI.callService('setting.unbind', {}).then((data) => {
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
this.isBind = false;
|
this.isBind = false;
|
||||||
} else {
|
} else {
|
||||||
@ -1118,112 +924,161 @@
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
renderQrcode() {
|
renderQrcode() {
|
||||||
this.$nextTick(() => {
|
console.log('[QR] renderQrcode 被调用, code:', this.code);
|
||||||
const el = this.$refs.qrcode;
|
try {
|
||||||
if (!el) return;
|
var el = document.getElementById('qrcode');
|
||||||
// 清空容器,防止多次渲染叠加
|
console.log('[QR] qrcode DOM 元素:', el);
|
||||||
|
if (!el) { console.log('[QR] 容器未找到'); return; }
|
||||||
el.innerHTML = '';
|
el.innerHTML = '';
|
||||||
// 重新生成二维码实例
|
console.log('[QR] typeof QRCode:', typeof QRCode);
|
||||||
|
if (typeof QRCode === 'undefined') { console.log('[QR] QRCode 库未加载'); return; }
|
||||||
this.qrcode = new QRCode(el, { width: 256, height: 256 });
|
this.qrcode = new QRCode(el, { width: 256, height: 256 });
|
||||||
|
console.log('[QR] QRCode 实例已创建');
|
||||||
if (this.code) {
|
if (this.code) {
|
||||||
this.qrcode.makeCode(`https://ye4s.wms.gztbyc.com/mini/?spm=0.5.${this.code}.1.4`);
|
var url = 'https://ye4s.wms.gztbyc.com/mini/?spm=0.5.' + this.code + '.1.4';
|
||||||
|
console.log('[QR] 生成二维码, URL:', url);
|
||||||
|
this.qrcode.makeCode(url);
|
||||||
|
console.log('[QR] makeCode 完成');
|
||||||
}
|
}
|
||||||
});
|
} catch (e) { console.error('[QR] 渲染失败:', e); }
|
||||||
},
|
},
|
||||||
installWsListener() {
|
installWsListener() {
|
||||||
wsOn('printer.getWindowsPrinters', (data) => {
|
this._unsubFns.push(
|
||||||
if (data.success) {
|
window.printServerAPI.onEvent('printer.getWindowsPrinters', (data) => {
|
||||||
this.printers = data.result || [];
|
if (data.success) {
|
||||||
if (this.printers.length === 0) {
|
this.printers = data.result || [];
|
||||||
this.selectedPrinter = '';
|
if (this.printers.length === 0) {
|
||||||
} else if (!this.selectedPrinter) {
|
this.selectedPrinter = '';
|
||||||
this.selectedPrinter = this.printers[0].name;
|
} else if (!this.selectedPrinter) {
|
||||||
|
this.selectedPrinter = this.printers[0].name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('setting.info', (data) => {
|
||||||
|
if (data.success) {
|
||||||
|
this.isBind = data.result.isBind || false;
|
||||||
|
this.name = data.result.name || '';
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('printerComponent.getAll', (data) => {
|
||||||
|
if (data.success) {
|
||||||
|
this.components = data.result.components || [];
|
||||||
|
this.statusList = data.result.status || [];
|
||||||
|
} else {
|
||||||
|
alert(data.message || '获取打印组件列表失败!');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('printerComponent.statusChange', (data) => {
|
||||||
|
if (data.success) {
|
||||||
|
this.statusList = [...this.statusList.filter(s => s.name !== data.result.name), { name: data.result.name, status: data.result.status }];
|
||||||
|
} else {
|
||||||
|
alert(data.message || '获取打印组件列表失败!');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('wsClient.statusChange', (data) => {
|
||||||
|
if (data.success) {
|
||||||
|
this.wsServerStatus = data.result.status;
|
||||||
|
} else {
|
||||||
|
alert(data.message || '获取在线状态失败!');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('bind.generateCode', (data) => {
|
||||||
|
console.log('[QR] 收到 bind.generateCode 事件:', JSON.stringify(data));
|
||||||
|
if (data.success) {
|
||||||
|
this.code = data.result || '';
|
||||||
|
console.log('[QR] code 已设为:', this.code);
|
||||||
|
} else {
|
||||||
|
alert(data.message || '获取绑定码失败!');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onEvent('update.downloadProgress', (data) => {
|
||||||
|
if (!data.success || !data.result) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
|
||||||
wsOn('setting.info', (data) => {
|
|
||||||
if (data.success) {
|
|
||||||
this.isBind = data.result.isBind || false;
|
|
||||||
this.name = data.result.name || '';
|
|
||||||
this.isServices = data.result.isService || false;
|
|
||||||
this.portForm.wsPort = Number(data.result.wsPort) || this.portForm.wsPort;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wsOn('printerComponent.getAll', (data) => {
|
|
||||||
if (data.success) {
|
|
||||||
this.components = data.result.components || [];
|
|
||||||
this.statusList = data.result.status || [];
|
|
||||||
} else {
|
|
||||||
alert(data.message || '获取打印组件列表失败!');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wsOn('printerComponent.statusChange', (data) => {
|
|
||||||
if (data.success) {
|
|
||||||
this.statusList = [...this.statusList.filter(s => s.name !== data.result.name), { name: data.result.name, status: data.result.status }];
|
|
||||||
} else {
|
|
||||||
alert(data.message || '获取打印组件列表失败!');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wsOn('wsClient.statusChange', (data) => {
|
|
||||||
if (data.success) {
|
|
||||||
this.wsServerStatus = data.result.status;
|
|
||||||
} else {
|
|
||||||
alert(data.message || '获取在线状态失败!');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wsOn('bind.generateCode', (data) => {
|
|
||||||
if (data.success) {
|
|
||||||
this.code = data.result || '';
|
|
||||||
} else {
|
|
||||||
alert(data.message || '获取绑定码失败!');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wsOn('update.downloadProgress', (data) => {
|
|
||||||
if (!data.success || !data.result) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.updateState = {
|
this.updateState = {
|
||||||
...this.updateState,
|
...this.updateState,
|
||||||
...data.result,
|
...data.result,
|
||||||
hasUpdate: true,
|
hasUpdate: true,
|
||||||
latestVersion: data.result.latestVersion || this.updateState.latestVersion,
|
latestVersion: data.result.latestVersion || this.updateState.latestVersion,
|
||||||
currentVersion: data.result.currentVersion || this.updateState.currentVersion,
|
currentVersion: data.result.currentVersion || this.updateState.currentVersion,
|
||||||
downloadUrl: data.result.downloadUrl || this.updateState.downloadUrl
|
downloadUrl: data.result.downloadUrl || this.updateState.downloadUrl
|
||||||
};
|
};
|
||||||
|
|
||||||
if (this.updatingInApp || data.result.status === 'downloading' || data.result.status === 'starting') {
|
if (this.updatingInApp || data.result.status === 'downloading' || data.result.status === 'starting') {
|
||||||
this.activeTab = 'extension';
|
this.activeTab = 'extension';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.result.status === 'installing') {
|
if (data.result.status === 'installing') {
|
||||||
this.updatingInApp = false;
|
this.updatingInApp = false;
|
||||||
alert('安装程序已启动,请在安装向导中完成更新。');
|
alert('安装程序已启动,请在安装向导中完成更新。');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.result.status === 'failed') {
|
if (data.result.status === 'failed') {
|
||||||
this.updatingInApp = false;
|
this.updatingInApp = false;
|
||||||
alert(data.result.message || '更新失败');
|
alert(data.result.message || '更新失败');
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
code(val) {
|
code(val) {
|
||||||
|
console.log('[QR] code watcher 触发, 旧值->新值:', val);
|
||||||
if (val) {
|
if (val) {
|
||||||
console.log('新的绑定码:', val);
|
console.log('[QR] 新的绑定码:', val);
|
||||||
this.renderQrcode();
|
this.renderQrcode();
|
||||||
|
} else {
|
||||||
|
console.log('[QR] code 为空, 跳过二维码渲染');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
mounted() {
|
mounted() {
|
||||||
this._restartWatchTimer = null;
|
this._unsubFns = [];
|
||||||
setInterval(() => {
|
|
||||||
this.refreshBindStatus();
|
// 注册 IPC 事件监听
|
||||||
}, 10000);
|
|
||||||
this.installWsListener();
|
this.installWsListener();
|
||||||
|
|
||||||
|
// 注册后端连接状态监听
|
||||||
|
this._unsubFns.push(
|
||||||
|
window.printServerAPI.onBackendStatusChange((status) => {
|
||||||
|
this.onBackendStatusChange(status);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// 初始数据加载
|
||||||
this.refreshBindStatus();
|
this.refreshBindStatus();
|
||||||
wsSendWithCallback('update.getDownloadState', {}, (data) => {
|
this.loadComponents();
|
||||||
|
this.loadPrinters();
|
||||||
|
// 主动拉取远端服务器连接状态(弥补 IPC 事件早于监听注册的时序问题)
|
||||||
|
window.printServerAPI.callService('wsClient.getStatus', {}).then((data) => {
|
||||||
|
if (data.success && data.result) {
|
||||||
|
this.wsServerStatus = data.result.status;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// 弥补 IPC 事件可能早于监听注册的时序问题:主动获取缓存中的绑定码
|
||||||
|
window.printServerAPI.callService('bind.getCurrentCode', {}).then((data) => {
|
||||||
|
console.log('[QR] bind.getCurrentCode 返回:', JSON.stringify(data));
|
||||||
|
if (data.success && data.result) {
|
||||||
|
console.log('[QR] 从缓存获取到 code:', data.result);
|
||||||
|
this.code = data.result;
|
||||||
|
} else {
|
||||||
|
console.log('[QR] 缓存无 code,等待 IPC 事件');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
window.printServerAPI.callService('update.getDownloadState', {}).then((data) => {
|
||||||
if (data.success && data.result && data.result.ok) {
|
if (data.success && data.result && data.result.ok) {
|
||||||
this.updateState = {
|
this.updateState = {
|
||||||
...this.updateState,
|
...this.updateState,
|
||||||
@ -1232,18 +1087,115 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 定期刷新
|
||||||
|
this._refreshInterval = setInterval(() => {
|
||||||
|
this.refreshBindStatus();
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
|
// 延迟检查更新
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.checkUpdate(false);
|
this.checkUpdate(false);
|
||||||
}, 3000);
|
}, 3000);
|
||||||
|
|
||||||
|
// QRCode 重试:首次加载失败时自动重试
|
||||||
|
this._qrTimer = setInterval(function () {
|
||||||
|
var self = document.getElementById('app').__vue__;
|
||||||
|
if (!self) return;
|
||||||
|
var qrEl = document.getElementById('qrcode');
|
||||||
|
if (qrEl && qrEl.children.length > 0) { clearInterval(self._qrTimer); self._qrTimer = null; return; }
|
||||||
|
if (self.code && typeof QRCode !== 'undefined') {
|
||||||
|
self.renderQrcode();
|
||||||
|
clearInterval(self._qrTimer);
|
||||||
|
self._qrTimer = null;
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
// 15 秒后停止重试
|
||||||
|
setTimeout(function () {
|
||||||
|
var self = document.getElementById('app').__vue__;
|
||||||
|
if (self && self._qrTimer) { clearInterval(self._qrTimer); self._qrTimer = null; }
|
||||||
|
}, 30000);
|
||||||
},
|
},
|
||||||
beforeDestroy() {
|
beforeDestroy() {
|
||||||
if (this._restartWatchTimer) {
|
if (this._refreshInterval) {
|
||||||
clearTimeout(this._restartWatchTimer);
|
clearInterval(this._refreshInterval);
|
||||||
this._restartWatchTimer = null;
|
this._refreshInterval = null;
|
||||||
}
|
}
|
||||||
|
if (this._unsubFns) {
|
||||||
|
this._unsubFns.forEach(function (fn) { if (typeof fn === 'function') fn(); });
|
||||||
|
this._unsubFns = [];
|
||||||
|
}
|
||||||
|
if (this._qrTimer) { clearInterval(this._qrTimer); this._qrTimer = null; }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// ─── 状态栏原生 JS 渲染 ───
|
||||||
|
(function renderStatusBar() {
|
||||||
|
var statusEl = document.querySelector('.statusbar');
|
||||||
|
if (!statusEl) return;
|
||||||
|
|
||||||
|
function updateSB() {
|
||||||
|
var mainApp = document.getElementById('app').__vue__;
|
||||||
|
if (!mainApp) return;
|
||||||
|
|
||||||
|
var ws = mainApp.wsStatus;
|
||||||
|
var items = statusEl.querySelectorAll('.status-item');
|
||||||
|
|
||||||
|
if (items[0]) {
|
||||||
|
var c = ws[mainApp.wsClientStatus] || ws.connected;
|
||||||
|
items[0].innerHTML = '<span class="status-dot" style="background:' + c.color + '"></span>' +
|
||||||
|
'<span>本地服务:<strong style="color:' + c.color + '">' + c.title + '</strong></span>';
|
||||||
|
}
|
||||||
|
if (items[1]) {
|
||||||
|
var s = ws[mainApp.wsServerStatus] || ws.disconnected;
|
||||||
|
items[1].innerHTML = '<span class="status-dot" style="background:' + s.color + '"></span>' +
|
||||||
|
'<span>服务器连接:<strong style="color:' + s.color + '">' + s.title + '</strong></span>';
|
||||||
|
}
|
||||||
|
if (items[2]) {
|
||||||
|
var bindC = mainApp.isBind ? '#107c10' : '#c42b1c';
|
||||||
|
var bindT = mainApp.isBind ? '已绑定' : '未绑定';
|
||||||
|
var clickable = mainApp.isBind ? 'cursor:pointer;text-decoration:underline' : '';
|
||||||
|
items[2].innerHTML = '<span class="status-dot" style="background:' + bindC + '"></span>' +
|
||||||
|
'<span>打印服务绑定:<strong style="color:' + bindC + ';' + clickable + '" id="bindStatusText">' + bindT + '</strong></span>';
|
||||||
|
}
|
||||||
|
|
||||||
|
var btns = statusEl.querySelectorAll('button');
|
||||||
|
if (btns[0]) btns[0].textContent = mainApp.updateChecking ? '检查中...' : '检查更新';
|
||||||
|
if (btns[1]) { btns[1].textContent = mainApp.restartingBackend ? '重启中...' : '重启服务'; btns[1].disabled = mainApp.restartingBackend; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 绑定按钮事件
|
||||||
|
var btnCheck = document.getElementById('btnCheckUpdate');
|
||||||
|
if (btnCheck) {
|
||||||
|
btnCheck.addEventListener('click', function () {
|
||||||
|
var mainApp = document.getElementById('app').__vue__;
|
||||||
|
if (mainApp && mainApp.checkUpdate) mainApp.checkUpdate(true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
var btnRestart = document.getElementById('btnRestartBackend');
|
||||||
|
if (btnRestart) {
|
||||||
|
btnRestart.addEventListener('click', function () {
|
||||||
|
var mainApp = document.getElementById('app').__vue__;
|
||||||
|
if (mainApp && mainApp.confirmRestartBackend) mainApp.confirmRestartBackend();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
updateSB();
|
||||||
|
setInterval(updateSB, 500);
|
||||||
|
|
||||||
|
// 点击"打印服务绑定"解绑
|
||||||
|
statusEl.addEventListener('click', function (e) {
|
||||||
|
if (e.target && e.target.id === 'bindStatusText') {
|
||||||
|
var mainApp = document.getElementById('app').__vue__;
|
||||||
|
if (mainApp && mainApp.isBind && mainApp.unbind) {
|
||||||
|
if (window.confirm('确认解除绑定吗?解除后需要重新扫码绑定。')) {
|
||||||
|
mainApp.unbind();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user