chore: init printServer and remove rsa keys

This commit is contained in:
liufumingren 2026-03-29 13:26:23 +08:00
commit 79bae5b51e
46 changed files with 9707 additions and 0 deletions

22
.gitignore vendored Normal file
View File

@ -0,0 +1,22 @@
node_modules/
dist/
coverage/
临时/
涓存椂/
rsa/
.vscode/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
Thumbs.db
.DS_Store
*.tmp
*.temp
*.bak

101
README.md Normal file
View File

@ -0,0 +1,101 @@
# printServer
## 项目概况
printServer 是一个面向 Windows 的本地打印服务应用。
它当前由以下几部分组成:
- Node.js HTTP 服务,监听本地 3000 端口
- 本地 WebSocket 服务,监听 3001 端口
- 前端页面 views/index.html,用于绑定工作台、查看打印机、查看组件状态、执行注册服务等操作
- Windows PowerShell 脚本,用于打印机状态轮询
- 打印组件与远程 WebSocket 通信逻辑,用于接收远端指令并驱动本地打印
- Electron 桌面壳,用于后续安装包、托盘图标和桌面启动能力
## 当前能力
- 查询 Windows 打印机列表
- 监听打印机状态变化
- 通过页面查看本地打印组件状态
- 通过 WebSocket 调用本地服务方法
- 页面点击注册/注销服务状态
- 已开始接入 Electron 桌面入口与托盘常驻能力
## 技术结构
- 入口文件:index.js
- 核心框架:core/
- 服务层:services/
- 控制器:controllers/
- 页面:views/
- Windows 脚本:printer.ps1
- 配置文件:config.json
## 目录说明
- controllers/
- HTTP 控制器
- core/
- 主应用、WebSocket 服务、WebSocket 客户端、打印组件核心逻辑
- services/
- 业务服务,如打印机、设置、绑定
- views/
- 页面模板,目前主要是 index.html
- daemon/
- 守护或服务相关配置文件
- 临时/
- 临时分析文档、测试脚本、临时日志的统一目录,可在任务结束后整体清理
## 本地运行
环境要求:
- Windows
- Node.js
- PowerShell
- 已安装并可调用的打印机驱动
启动方式:
```bash
node index.js
```
开发模式:
```bash
npm run dev
```
打开页面:
- http://127.0.0.1:3000/
## 页面与服务调用关系
页面通过浏览器连接本地 WebSocket 服务:
- 页面地址由本地 HTTP 服务提供
- 页面中的按钮通过 wsSendWithCallback 发送 method
- WebSocket 服务按 method 路由到 services/ 下对应实例方法
示例:
- setting.register -> services/setting.js
- setting.unregister -> services/setting.js
- printer.getWindowsPrinters -> services/printer.js
## 当前打包方向
当前已确定的桌面化与 EXE 打包方向为:
- Electron 作为桌面壳
- electron-builder 作为打包工具
- NSIS 作为 Windows 安装包输出方式
选择这个方向的原因:
- 需要桌面图标启动
- 需要系统托盘图标常驻
- 需要安装包体验
- 需要打开页面并继续复用现有 index.html 和本地服务能力
- 比单纯将 Node 打成 exe 更容易控制窗口、托盘、安装和运行态
## 后续打包目标
- 支持可重复打包
- 输出完整安装包 EXE
- 安装后创建桌面快捷方式
- 启动后保留系统托盘图标
- 能打开页面并完成注册到服务
- 打包时纳入配置文件、页面资源、PowerShell 脚本与相关依赖
## 注意事项
- 当前项目包含明显的 Windows 依赖
- dm 相关能力已从本项目移除,不再属于当前交付范围
- 3000 和 3001 端口需避免被占用
- 临时测试与分析文件统一放在 临时/ 目录

226
build.ps1 Normal file
View File

@ -0,0 +1,226 @@
param(
[ValidateSet('clean', 'prepare', 'app', 'win', 'package')]
[string]$Stage = 'package'
)
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$tempRootName = [string]([char]0x4E34) + [char]0x65F6
$tempPackagingDir = Join-Path (Join-Path $root $tempRootName) 'packaging'
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$logPath = Join-Path $tempPackagingDir ("build-$timestamp.log")
function Ensure-Dir([string]$PathValue) {
if (-not (Test-Path $PathValue)) {
New-Item -ItemType Directory -Path $PathValue -Force | Out-Null
}
}
function Write-Log([string]$Message) {
Ensure-Dir $tempPackagingDir
$line = "[{0}] {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Message
$line | Tee-Object -FilePath $logPath -Append
}
function Invoke-Step([string]$Name, [scriptblock]$Action) {
Write-Log "START $Name"
& $Action
Write-Log "DONE $Name"
}
function Invoke-Npm([string[]]$Args) {
& npm.cmd @Args
if ($LASTEXITCODE -ne 0) {
throw "npm $($Args -join ' ') failed with exit code $LASTEXITCODE"
}
}
function Invoke-Builder([string[]]$Args) {
$builderPath = Join-Path $root 'node_modules\.bin\electron-builder.cmd'
if (-not (Test-Path $builderPath)) {
throw 'electron-builder.cmd not found, run npm install first'
}
& $builderPath @Args
if ($LASTEXITCODE -ne 0) {
throw "electron-builder $($Args -join ' ') failed with exit code $LASTEXITCODE"
}
}
function Ensure-AppExecutable() {
$appOutDir = Join-Path $root 'dist\win-unpacked'
$targetExe = Join-Path $appOutDir 'printServer.exe'
$fallbackSource = Join-Path $root 'node_modules\electron\dist\electron.exe'
$runtimeMarker = Join-Path $appOutDir 'resources.pak'
if (Test-Path $targetExe) {
return $true
}
if ((Test-Path $appOutDir) -and (Test-Path $runtimeMarker) -and (Test-Path $fallbackSource)) {
Copy-Item -Path $fallbackSource -Destination $targetExe -Force
Write-Log 'FALLBACK app executable copied from node_modules/electron/dist/electron.exe'
return $true
}
return $false
}
function Ensure-PackagedResources() {
$appOutDir = Join-Path $root 'dist\win-unpacked'
$resourcesDir = Join-Path $appOutDir 'resources'
Ensure-Dir $resourcesDir
$configTemplateSource = Join-Path $root 'config.packaged.json'
$configTargetPath = Join-Path $resourcesDir 'config.json'
if (Test-Path $configTemplateSource) {
Copy-Item -Path $configTemplateSource -Destination $configTargetPath -Force
}
foreach ($fileName in @('printer.ps1')) {
$sourcePath = Join-Path $root $fileName
$targetPath = Join-Path $resourcesDir $fileName
if (Test-Path $sourcePath) {
Copy-Item -Path $sourcePath -Destination $targetPath -Force
}
}
foreach ($dirName in @('daemon')) {
$sourcePath = Join-Path $root $dirName
$targetPath = Join-Path $resourcesDir $dirName
if (Test-Path $sourcePath) {
if (Test-Path $targetPath) {
Remove-Item -Path $targetPath -Recurse -Force
}
Copy-Item -Path $sourcePath -Destination $targetPath -Recurse -Force
}
}
}
function Clean-Stage {
foreach ($target in @('dist', 'release')) {
$fullPath = Join-Path $root $target
if (Test-Path $fullPath) {
Remove-Item -Path $fullPath -Recurse -Force
}
}
if (Test-Path $tempPackagingDir) {
Remove-Item -Path $tempPackagingDir -Recurse -Force
}
}
function Prepare-Stage {
Ensure-Dir $tempPackagingDir
$requiredItems = @(
'index.js',
'config.packaged.json',
'printer.ps1',
'views\index.html',
'electron\main.cjs'
)
$missing = @()
foreach ($item in $requiredItems) {
$target = Join-Path $root $item
if (-not (Test-Path $target)) {
$missing += $item
}
}
if ($missing.Count -gt 0) {
throw "missing required packaging inputs: $($missing -join ', ')"
}
$manifest = [PSCustomObject]@{
version = (Get-Content (Join-Path $root 'package.json') -Raw | ConvertFrom-Json).version
checkedAt = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
requiredItems = $requiredItems
}
$manifest | ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $tempPackagingDir 'preflight-check.json') -Encoding UTF8
}
function App-Stage {
$builderFailed = $false
try {
Invoke-Builder @('--dir', '--win')
} catch {
$builderFailed = $true
Write-Log ("WARN app stage failed before completion: " + $_.Exception.Message)
}
if ($builderFailed -and (Ensure-AppExecutable)) {
Ensure-PackagedResources
Write-Log 'APP stage fallback completed with unpacked executable workaround'
return
}
if ($builderFailed) {
throw 'app stage failed and no usable unpacked executable was produced'
}
Ensure-PackagedResources
Write-Log 'APP stage resources synchronized'
}
function Invoke-OfflineInstaller {
$offlineBuilderPath = Join-Path $root 'electron\build-offline-installer.ps1'
& powershell.exe -ExecutionPolicy Bypass -File $offlineBuilderPath
if ($LASTEXITCODE -ne 0) {
throw "offline installer build failed with exit code $LASTEXITCODE"
}
}
function Win-Stage {
App-Stage
$nsisBuilt = $false
try {
& node (Join-Path $root 'electron\build-installer.mjs')
if ($LASTEXITCODE -ne 0) {
throw "installer build failed with exit code $LASTEXITCODE"
}
$nsisBuilt = $true
Write-Log 'NSIS installer build completed'
} catch {
Write-Log ("WARN NSIS installer unavailable: " + $_.Exception.Message)
}
if (-not $nsisBuilt) {
Invoke-OfflineInstaller
Write-Log 'OFFLINE installer build completed with IExpress fallback'
}
}
switch ($Stage) {
'clean' {
Invoke-Step 'clean' { Clean-Stage }
}
'prepare' {
Invoke-Step 'prepare' { Prepare-Stage }
}
'app' {
Invoke-Step 'prepare' { Prepare-Stage }
Invoke-Step 'app' { App-Stage }
}
'win' {
Invoke-Step 'prepare' { Prepare-Stage }
Invoke-Step 'win' { Win-Stage }
}
'package' {
Invoke-Step 'clean' { Clean-Stage }
Invoke-Step 'prepare' { Prepare-Stage }
Invoke-Step 'win' { Win-Stage }
}
}

16
config.json Normal file
View File

@ -0,0 +1,16 @@
{
"port": 3000,
"wsPort": 3001,
"logLevel": "info",
"printerDefault": "",
"maxPrintJobs": 10,
"isService": false,
"remoteWs": {
"url": "ws://printer.wms.gztbyc.com/ws",
"reconnectInterval": 3000
},
"refreshTokenExpireTime": 0,
"tokenExpireTime": 1774710196708,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2RlIjoiNzExYzJjIiwicHJpbnRlciI6Iua1i-ivleaJk-WNsOWPsCIsIndhcmVob3VzZSI6IjEwMDAwMjgiLCJjb21wdXRlcklkIjoxLCJpYXQiOjE3NzQ3MDY1OTYsImV4cCI6MTc3NDcxMDE5Nn0.VCkG5bFJGvvvkT_CwuWwfsIE_JsMCF_Zcp2FWOsy1hg",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2RlIjoiNzExYzJjIiwicHJpbnRlciI6Iua1i-ivleaJk-WNsOWPsCIsIndhcmVob3VzZSI6IjEwMDAwMjgiLCJjb21wdXRlcklkIjoxLCJpYXQiOjE3NzI5Nzk2OTIsImV4cCI6NDkyODczOTY5Mn0.1qxGUf1IDco2F2Vfsg-t9mv0s14gtIz56tXvHjIX7ls"
}

17
config.packaged.json Normal file
View File

@ -0,0 +1,17 @@
{
"port": 3000,
"wsPort": 3001,
"logLevel": "info",
"printerDefault": "",
"maxPrintJobs": 10,
"isService": false,
"remoteWs": {
"url": "ws://printer.wms.gztbyc.com/ws",
"reconnectInterval": 3000
},
"refreshTokenExpireTime": 0,
"name": "",
"tokenExpireTime": 0,
"token": "",
"refreshToken": ""
}

27
controllers/index.js Normal file
View File

@ -0,0 +1,27 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import BaseController from '../core/BaseController.js';
class IndexController extends BaseController {
constructor() {
super();
}
index() {
const {ctx} = this;
console.log("访问首页");
const indexPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '../views/index.html');
fs.readFile(indexPath, (err, data) => {
if (err) {
console.log('读取首页文件错误:', err.message);
ctx.response.writeHead(500, { 'Content-Type': 'text/plain' });
ctx.response.end('500 Internal Server Error');
} else {
ctx.response.writeHead(200, { 'Content-Type': 'text/html' });
ctx.response.end(data);
}
});
}
}
export default new IndexController();

27
controllers/printer.js Normal file
View File

@ -0,0 +1,27 @@
import BaseController from '../core/BaseController.js';
class PrinterController extends BaseController {
constructor(ctx) {
super(ctx);
}
async getPrinters() {
try {
const printers = await this.app.services.printer.getWindowsPrinters();
this.ctx.res.writeHead(200, { 'Content-Type': 'application/json' });
this.ctx.res.end(JSON.stringify({ printers }));
} catch (err) {
this.ctx.res.writeHead(500, { 'Content-Type': 'application/json' });
this.ctx.res.end(JSON.stringify({ error: '获取打印机列表失败', detail: err.message }));
}
}
componentList() {
const components = this.app.printerComponents.getAllPorts();
const status = this.app.printerComponents.getAllStatus();
this.ctx.res.writeHead(200, { 'Content-Type': 'application/json' });
this.ctx.res.end(JSON.stringify({ components, status }));
}
}
export default PrinterController;

View File

11
core/BaseController.js Normal file
View File

@ -0,0 +1,11 @@
import app from './main.js';
class BaseController {
constructor() {
this.app = app;
this.ctx = app.ctx;
this.config = app.config;
}
}
export default BaseController;

11
core/BaseService.js Normal file
View File

@ -0,0 +1,11 @@
import app from './main.js';
class BaseService{
constructor() {
this.app = app;
this.ctx = app.ctx;
this.config = app.config;
}
}
export default BaseService;

213
core/main.js Normal file
View File

@ -0,0 +1,213 @@
import WSServer from './wsServer.js';
import configUtil from '../utils/config.js';
import PrinterComponentCore from './printerComponentCore.js';
import PrinterComponentMessageHandler from './printerComponentMessageHandler.js';
import WSClient from './wsClient.js';
import fs from 'fs';
import routes from '../routes.js';
import { pathToFileURL } from 'url';
import path from 'path';
import EventEmitter from 'events';
import { getResourcePath } from '../utils/runtime.js';
// 框架基础类 Main
class Main extends EventEmitter {
constructor() {
super();
if (Main.instance) {
return Main.instance;
}
this.config = configUtil.read();
this.app = this;
this.info = null;
this.isBind = false; // 绑定状态
this.ctx = {};
this.services = {};
this.printerComponents = new PrinterComponentCore(this);
this.printerComponents.initAll();
// 初始化打印组件消息处理对象
this.printerComponentMessageHandler = new PrinterComponentMessageHandler(this, this.printerComponents);
this.printerComponentMessageHandler.init();
// 监听 WMI 打印机状态变化
console.log(`ws服务器已启动,监听端口: ${this.config.wsPort}`);
this.init().then(() => {
console.log('框架初始化完成');
console.log('初始化services完成,当前服务列表:', Object.keys(this.services));
this.wsClient = new WSClient(this.config.remoteWs.url, {
reconnectInterval: this.config.remoteWs.reconnectInterval || 3000
}, this);
this.wsServer = new WSServer(this.config.wsPort, this);
this._initWmiPrinterMonitor();
this.app.on('printerWmiStatusChange', (data) => {
console.log('打印机状态变化事件触发,数据:', data);
this.services.printer.getWindowsPrinters();
});
});
Main.instance = this;
return this;
}
async _initWmiPrinterMonitor() {
// Use child_process to start PowerShell polling script, listen for printer status changes
const { spawn } = await import('child_process');
const scriptPath = getResourcePath('printer.ps1');
try {
const ps = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath], { stdio: ['ignore', 'pipe', 'pipe'] });
let lastStatus = {};
ps.stdout.on('data', (data) => {
const lines = data.toString().split(/\r?\n/).filter(Boolean);
for (const line of lines) {
// Parse format: 15:15:46 PrinterName: Status (Online/Offline)
const match = line.match(/^(\d{2}:\d{2}:\d{2}) (.+?): (.+?) \((Online|Offline)\)$/);
if (match) {
const [, time, name, status, online] = match;
const key = name;
if (lastStatus[key] !== status + online) {
lastStatus[key] = status + online;
this.app.emit('printerWmiStatusChange', { name, status, online, time });
}
}
}
});
ps.stderr.on('data', (data) => {
console.error('[WMI Printer Monitor][stderr]', data.toString());
});
ps.on('error', (err) => {
console.error('[WMI Printer Monitor][error]', err);
});
ps.on('exit', (code) => {
console.warn(`[WMI Printer Monitor] exited with code ${code}`);
});
} catch (e) {
console.error('[WMI Printer Monitor] failed to start:', e);
}
}
router(req, res) {
this.ctx.request = req;
this.ctx.response = res;
const match = routes.find(r => r.method === req.method && r.path === req.url);
if (match) {
const parts = match.controller.split('.');
const action = parts.pop(); // 最后一个部分是方法名
const controllerPath = parts.join('.'); // 其余部分合并为控制器路径
console.log('匹配到路由:', match.method, match.path, '=>', controllerPath, action);
const ctrl = this.getController(controllerPath); // 加载控制器
if (ctrl && typeof ctrl[action] === 'function') {
ctrl[action](req, res);
} else {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('控制器或方法不存在');
}
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
}
async init() {
await this._loadServices();
await this._loadControllers();
}
getConfig() {
return this.config;
}
setConfig(newConfig) {
this.config = newConfig;
return this.configUtil.write(newConfig);
}
getController(name) {
console.log('获取控制器:', name);
console.log('当前控制器列表:', Object.keys(this.ctx.controllers));
return this.ctx.controllers[name];
}
getService(name) {
return this.ctx.services[name];
}
createContext(req, res) {
// 构建 ctx 上下文对象
return {
app: this.app,
config: this.config,
req,
res,
controllers: this.ctx.controllers
// 可扩展更多上下文属性
};
}
// 可扩展更多框架基础能力
async _loadServices() {
const walk = async (dir) => {
const result = {};
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.resolve(path.join(dir, file));
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
result[file] = await walk(fullPath);
} else if (file.endsWith('.js')) {
const name = path.basename(file, '.js');
const fileUrl = pathToFileURL(fullPath).href;
console.log('[WSServer] 动态 import 路径:', fullPath, fileUrl);
try {
const mod = await import(fileUrl);
// 自动实例化导出的类
if (mod.default && typeof mod.default === 'function') {
result[name] = new mod.default();
} else {
result[name] = mod.default;
}
} catch (e) {
console.error('[WSServer] import try/catch 错误:', fileUrl, e);
}
}
}
return result;
};
// 使用 pathToFileURL 修复路径解析
console.log("import.meta.url", import.meta.url);
const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, '')));
this.services = await walk(path.join(__dirname, '../services'));
console.log('[WSServer] 已加载服务:', Object.keys(this.services));
}
async _loadControllers() {
// 递归加载 controllers 目录下所有 js 文件,按目录结构组装对象
const walk = async (dir) => {
const result = {};
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.resolve(path.join(dir, file));
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
result[file] = await walk(fullPath);
} else if (file.endsWith('.js')) {
const name = path.basename(file, '.js');
const fileUrl = pathToFileURL(fullPath).href;
console.log('[WSServer] 动态 import 路径:', fullPath, fileUrl);
try {
const mod = await import(fileUrl);
result[name] = mod.default;
} catch (e) {
console.error('[WSServer] import try/catch 错误:', fileUrl, e);
}
}
}
return result;
};
// 使用 pathToFileURL 修复路径解析
console.log("import.meta.url", import.meta.url);
const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, '')));
this.ctx.controllers = await walk(path.join(__dirname, '../controllers'));
console.log('[WSServer] 已加载控制器:', Object.keys(this.ctx.controllers));
}
}
export default new Main();

View File

@ -0,0 +1,174 @@
import WebSocket from 'ws';
import EventEmitter from 'events';
// 打印组件核心管理类
const defaultComponents = [
{ name: '抖音', port: '13888' },
{ name: '拼多多', port: '5000' },
{ name: '快手', port: '16888/ks/printer' },
{ name: '京东', port: '9113' },
{ name: '菜鸟', port: '13528' },
{ name: '视频号', port: '12705' },
{ name: '小红书', port: '10818' },
{ name: 'LODOP', port: '8000/c_webskt' }
];
class PrinterComponentCore extends EventEmitter {
constructor(app) {
super();
this.app = app;
this.components = new Map(); // {name: ws实例}
this.ports = new Map(); // {name: port}
this.status = new Map(); // {name: status}
this.reconnectTimers = new Map(); // {name: timer}
this.reconnectInterval = 3000;
defaultComponents.forEach(c => {
this.ports.set(c.name, c.port);
this.status.set(c.name, 'disconnected');
});
}
// 统一初始化所有组件
initAll() {
defaultComponents.forEach(c => {
this.initComponent(c.name);
});
}
// 初始化单个组件,带自动重连
initComponent(name) {
const port = this.ports.get(name);
if (!port) return;
let url = port.includes('/') ? `ws://127.0.0.1:${port}` : `ws://127.0.0.1:${port}`;
const connect = () => {
if (this.components.has(name)) {
try {
this.components.get(name).terminate();
} catch {}
this.components.delete(name);
}
if (this.reconnectTimers.has(name)) {
clearTimeout(this.reconnectTimers.get(name));
this.reconnectTimers.delete(name);
}
const ws = new WebSocket(url);
ws.on('open', () => {
this._updateStatus(name, 'connected');
//console.log(`[${name}] 连接成功: ${url}`);
});
ws.on('close', () => {
this._updateStatus(name, 'disconnected');
//console.log(`[${name}] 连接关闭,准备重连`);
if (!ws._manualClose) {
this._reconnect(name, connect);
}
});
ws.on('message', msg => {
if (Buffer.isBuffer(msg)) {
msg = msg.toString('utf8');
}
switch (name) {
case 'LODOP':
this.app.emit('lodopMessage', msg);
break;
case '抖音':
this.app.emit('douyinMessage', msg);
break;
case '拼多多':
this.app.emit('pinduoduoMessage', msg);
break;
case '快手':
this.app.emit('kuaishouMessage', msg);
break;
case '京东':
this.app.emit('jingdongMessage', msg);
break;
case '菜鸟':
this.app.emit('cainiaoMessage', msg);
break;
case '视频号':
this.app.emit('shipinhaoMessage', msg);
break;
case '小红书':
this.app.emit('xiaohongshuMessage', msg);
break;
default:
this.app.emit('printerComponentMessage', { name, message: msg });
}
});
ws.on('error', err => {
this._updateStatus(name, 'disconnected');
//console.log(`[${name}] 连接错误:`, err.message);
if (!ws._manualClose) {
this._reconnect(name, connect);
}
});
this.components.set(name, ws);
};
connect();
}
_reconnect(name, connectFn) {
if (this.reconnectTimers.has(name)) return;
this.reconnectTimers.set(name, setTimeout(() => {
connectFn();
this.reconnectTimers.delete(name);
}, this.reconnectInterval));
//console.log(`[${name}] ${this.reconnectInterval}ms 后重试连接...`);
}
addComponent(name, wsInstance) {
this.components.set(name, wsInstance);
}
getComponent(name) {
return this.components.get(name);
}
removeComponent(name) {
if (this.components.has(name)) {
const ws = this.components.get(name);
if (ws) {
ws._manualClose = true;
if (typeof ws.close === 'function') ws.close();
}
this.components.delete(name);
this.status.set(name, 'disconnected');
if (this.reconnectTimers.has(name)) {
clearTimeout(this.reconnectTimers.get(name));
this.reconnectTimers.delete(name);
}
}
}
getAllComponents() {
return Array.from(this.components.entries()).map(([name, ws]) => ({ name, ws }));
}
getPort(name) {
return this.ports.get(name);
}
getAllPorts() {
return Array.from(this.ports.entries()).map(([name, port]) => ({ name, port }));
}
getStatus(name) {
return this.status.get(name);
}
getAllStatus() {
return Array.from(this.status.entries()).map(([name, status]) => ({ name, status }));
}
// 更新状态并触发事件
_updateStatus(name, newStatus) {
//检测原来的状态,如果发生变化才触发事件
if (this.status.get(name) !== newStatus) {
this.status.set(name, newStatus);
this.app.emit('printerComponentStatusChange', { name, status: newStatus });
}
}
}
export default PrinterComponentCore;

View File

@ -0,0 +1,69 @@
/*
* 打印组件消息处理对象,负责监听各个打印组件的消息事件,并进行统一处理
* 主要功能:
* 1. 监听各个打印组件的消息事件,如LODOP、抖音、拼多多、快手、京东、菜鸟、视频号、小红书等组件的消息事件
* 2. 解析消息内容,根据不同组件的消息格式进行解析,提取打印结果状态和相关信息
* this.app.emit('printResult'); // 打印结果事件,携带打印ID和状态是增量添加的事件,
* 专门用于处理打印结果回调,携带打印ID和状态,方便服务端处理状态和保存日志
* 参数示例:{ printId: '123456', status: 'success' | 'error', message: '原始消息内容' }
* 其他组件消息事件(如douyinMessage、pinduoduoMessage等)是根据组件名称动态生成的事件,
* 针对性解析后返回状态和消息内容,方便服务端处理和保存日志
*/
class PrinterComponentMessageHandler {
constructor(app, printerComponentCore) {
this.app = app;
this.core = printerComponentCore;
}
// 初始化所有监听
init() {
this.app.on('lodopMessage', this.handleLodopMessage.bind(this));
this.app.on('douyinMessage', this.handleDouyinMessage.bind(this));
this.app.on('pinduoduoMessage', this.handlePinduoduoMessage.bind(this));
this.app.on('kuaishouMessage', this.handleKuaishouMessage.bind(this));
this.app.on('jingdongMessage', this.handleJingdongMessage.bind(this));
this.app.on('cainiaoMessage', this.handleCainiaoMessage.bind(this));
this.app.on('shipinhaoMessage', this.handleShipinhaoMessage.bind(this));
this.app.on('xiaohongshuMessage', this.handleXiaohongshuMessage.bind(this));
this.app.on('printerComponentMessage', this.handleOtherComponentMessage.bind(this));
}
handleLodopMessage(msg) {
// 处理LODOP消息
console.log('[LODOP]', msg);
//检测消息是否携带tid头,如果携带了tid头,说明是打印结果回调
//消息格式示例:tid:230=true;等于号后面是打印结果,true表示成功,false表示失败;tid:230=false;则表示打印失败
//printResult
if(msg.indexOf('tid:') === 0) {
const tid = msg.split('tid:')[1].split(';')[0];
const status = msg.split('=')[1] === 'true' ? 'success' : 'error';
this.app.emit('printResult', { printId: tid, status, message: msg }); // 触发打印结果事件,携带打印ID和状态
}
}
handleDouyinMessage(msg) {
console.log('[抖音]', msg);
}
handlePinduoduoMessage(msg) {
console.log('[拼多多]', msg);
}
handleKuaishouMessage(msg) {
console.log('[快手]', msg);
}
handleJingdongMessage(msg) {
console.log('[京东]', msg);
}
handleCainiaoMessage(msg) {
console.log('[菜鸟]', msg);
}
handleShipinhaoMessage(msg) {
console.log('[视频号]', msg);
}
handleXiaohongshuMessage(msg) {
console.log('[小红书]', msg);
}
handleOtherComponentMessage({ name, message }) {
console.log(`[${name}]`, message);
}
}
export default PrinterComponentMessageHandler;

190
core/wsClient.js Normal file
View File

@ -0,0 +1,190 @@
import WebSocket from 'ws';
import path from 'path';
import fs from 'fs';
class WSClient {
constructor(url, options = {}, app) {
this.url = url;
this.options = options;
this.ws = null;
this.status = 'disconnected';
//console.log('[WSClient] app', app);
this.services = app.services || {};
this.heartbeatTimerInterval = 10000; // 心跳间隔,默认10秒
this.app = app;
this.reconnectInterval = options.reconnectInterval || 3000; // 重连间隔,默认3秒
this._reconnectTimer = null;
//console.log('[WSClient] 初始化,目标地址:', this.url);
this._connect();
app.on('printerComponentStatusChange', (data) => {
if (this.app.info) {
console.log("组件状态变化,通知远程服务器", data);
this.send({ method: 'printerComponent.statusChange', data });
}
});
app.on("printResult", (data) => {
if (this.app.info) {
console.log("打印结果,通知远程服务器", data);
this.send({ method: 'base.printResult', data });
}
});
//获取打印机列表事件通知远程服务器
app.on("printerList", (data) => {
if (this.app.info) {
//console.log("打印机列表,通知远程服务器", data);
this.send({ method: 'base.printerList', data });
}
});
}
_connect() {
if (this.ws) {
try {
this.ws.terminate();
} catch (e) {
//console.log('[WSClient] 关闭旧连接异常:', e.message);
}
this.ws = null;
}
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
}
//console.log('[WSClient] 尝试连接:', this.url);
this.ws = new WebSocket(this.url, this.options);
this.ws.on('open', () => {
this.status = 'connected';
this._handleOpen();
this.app.emit('wsClientStatusChange', { status: 'connected', url: this.url });
});
this.ws.on('message', (msg) => {
if (Buffer.isBuffer(msg)) {
msg = msg.toString('utf8');
}
console.log('[WSClient] 收到消息:', msg);
this._handleMessage(msg);
});
this.ws.on('close', () => {
this.status = 'disconnected';
//console.log('[WSClient] 连接关闭,准备重连');
this.app.emit('wsClientStatusChange', { status: 'disconnected', url: this.url });
if (this.onClose) this.onClose();
this._reconnect();
});
this.ws.on('error', (err) => {
this.status = 'error';
//console.log('[WSClient] 连接错误:', err.message);
this.app.emit('wsClientStatusChange', { status: 'error', url: this.url, error: err.message });
this._reconnect();
});
}
_reconnect() {
//清理现有连接和定时器
this.app.randomCode = null; // 清除随机码
this.app.info = null; // 清除用户信息
if (this.status === 'connected' || this._reconnectTimer) return;
//console.log(`[WSClient] ${this.reconnectInterval}ms 后重试连接...`);
this._reconnectTimer = setTimeout(() => {
this._connect();
}, this.reconnectInterval);
}
async _handleOpen() {
/*console.log('[WSClient] _handleOpen 调试:', {
status: this.status,
url: this.url,
config: this.app.config
});*/
//设置心跳
const { token } = this.app.config;
this.send({ method: 'auth.getInfo', data: token });
this.startHeartbeat();
}
async startHeartbeat() {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
}
this.heartbeatTimer = setInterval(() => {
if (this.status === 'connected') {
this.send('ping');
const { token, refreshToken, tokenExpireTime } = this.app.config;
console.log(this.app.info,"this.app.info的值")
if (!this.app.info && token && refreshToken && tokenExpireTime) {
if (tokenExpireTime < Date.now()) {
//console.log('[WSClient] 心跳检测: token 已过期,尝试刷新');
this.send({ method: 'auth.refreshToken', data: { token: refreshToken } });
} else {
//拉取信息
this.send({ method: 'auth.getInfo', data: token });
}
}
}
}, this.heartbeatTimerInterval);
}
async _handleMessage(msg) {
if(msg === 'pong') {
//console.log('[WSClient] 收到心跳响应');
return;
}
//console.log("[WSClient]原始消息", msg)
let parsed;
try {
parsed = typeof msg === 'string' ? JSON.parse(msg) : msg;
} catch {
//console.log('[WSClient] 消息解析失败:', msg);
this.send({ success: false, message: '消息解析失败' });
return;
}
const { method, data } = parsed;
//console.log('[WSClient] 可用服务列表:', method, this.services, '方法:', method);
if (!method) {
//this.send({ success: false, message: '消息缺少 method 字段' });
return;
}
const methodPath = method.split('.');
let serviceFn = this.services;
for (let i = 0; i < methodPath.length; i++) {
serviceFn = serviceFn[methodPath[i]];
//console.log("serviceFn", serviceFn,methodPath[i]);
if (!serviceFn) break;
}
if (typeof serviceFn === 'function') {
try {
const result = await serviceFn(data);
if (result !== undefined) {
const responseMethod = result && typeof result === 'object' && result.method
? result.method
: method;
this.ws.send(JSON.stringify({ success: true, method: responseMethod, result }));
}
} catch (err) {
//console.log(`[WSClient] 服务方法执行失败: ${method}`, err);
//this.ws.send(JSON.stringify({ success: false, message: '服务方法执行失败: ' + err.message }));
}
} else {
//console.log(`[WSClient] 未找到对应服务方法: ${method}`);
//this.ws.send(JSON.stringify({ success: false, message: '未找到对应服务方法' }));
}
}
send(data) {
if (this.status === 'connected') {
//console.log('[WSClient] 发送消息:', data);
this.ws.send(typeof data === 'string' ? data : JSON.stringify(data));
}
}
close() {
if (this.ws) {
//console.log('[WSClient] 主动关闭连接');
this.ws.terminate();
this.ws = null;
}
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
}
}
}
export default WSClient;

201
core/wsServer.js Normal file
View File

@ -0,0 +1,201 @@
import { WebSocketServer } from 'ws';
import path from 'path';
import fs from 'fs';
import { pathToFileURL } from 'url';
class WSServer {
constructor(port, app, options = {}) {
this.port = port || 8081;
this.options = options;
this.server = null;
this.clients = new Set();
this.services = app.services; // 从 app 获取服务实例
this._start();
this.app = app;
app.on('printerComponentStatusChange', (data) => {
this.broadcast({ success: true, method: 'printerComponent.statusChange', result: data });
});
app.on('wsClientStatusChange', (data) => {
this.broadcast({ success: true, method: 'wsClient.statusChange', result: data });
});
app.on('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);
}
});
app.on('printerList', (data) => {
this.broadcast({ success: true, method: 'printer.getWindowsPrinters', result: data });
});
}
_start() {
this.server = new WebSocketServer({ port: this.port, ...this.options });
this.server.on('connection', (ws, req) => {
this.clients.add(ws);
//console.log('[WSServer] 新客户端连接,当前连接数:', this.clients.size);
if (typeof this.onConnection === 'function') {
this.onConnection(ws, req);
}
ws.on('message', (msg) => {
//console.log('[WSServer] 收到消息:', 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);
});
});
}
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 (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 (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 } }));
}
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 } = parsed;
if (!method) {
ws.send(JSON.stringify({ success: false, message: 'method不能为空' }));
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 }));
} catch (err) {
//console.log(err);
ws.send(JSON.stringify({ success: false, message: '服务方法执行失败: ' + err.message }));
}
} else {
ws.send(JSON.stringify({
success: false,
message: '未找到对应服务方法',
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] 服务端关闭');
}
}
}
export default WSServer;

BIN
daemon/printserver.exe Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
<supportedRuntime version="v4.0" />
</startup>
</configuration>

11
daemon/printserver.xml Normal file
View File

@ -0,0 +1,11 @@
<service>
<id>printserver.exe</id>
<name>PrintServer</name>
<description>printServer backend service</description>
<executable>C:\Program Files\nodejs\node.exe</executable>
<argument>D:\printServer\index.js</argument>
<logmode>rotate</logmode>
<startmode>Automatic</startmode>
<stoptimeout>30sec</stoptimeout>
<workingdirectory>D:\printServer</workingdirectory>
</service>

View File

@ -0,0 +1,12 @@
import path from 'path';
import { build } from 'electron-builder';
const projectDir = process.cwd();
const prepackaged = path.resolve(projectDir, 'dist', 'win-unpacked');
await build({
projectDir,
prepackaged,
win: ['nsis'],
publish: 'never'
});

View File

@ -0,0 +1,128 @@
param(
[string]$ProjectRoot = (Split-Path -Parent $PSScriptRoot)
)
$ErrorActionPreference = 'Stop'
function Ensure-Dir([string]$PathValue) {
if (-not (Test-Path $PathValue)) {
New-Item -ItemType Directory -Path $PathValue -Force | Out-Null
}
}
function Get-ShortPath([string]$PathValue) {
$item = Get-Item -Path $PathValue -ErrorAction Stop
$shortPath = cmd.exe /d /c ('for %I in ("{0}") do @echo %~sI' -f $item.FullName)
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($shortPath)) {
return $item.FullName
}
return $shortPath.Trim()
}
$packageJsonPath = Join-Path $ProjectRoot 'package.json'
$packageJson = Get-Content -Path $packageJsonPath -Raw | ConvertFrom-Json
$version = $packageJson.version
$distDir = Join-Path $ProjectRoot 'dist'
$appOutDir = Join-Path $distDir 'win-unpacked'
$primaryExePath = Join-Path $appOutDir 'printServer.exe'
$fallbackExePath = Join-Path $appOutDir 'electron.exe'
$targetName = "printServer-$version-setup.exe"
$targetPath = Join-Path $distDir $targetName
$tempRootName = [string]([char]0x4E34) + [char]0x65F6
$stagingRoot = Join-Path (Join-Path $ProjectRoot $tempRootName) 'packaging\iexpress'
$payloadZipPath = Join-Path $stagingRoot 'printServer-app.zip'
$sedPath = Join-Path $stagingRoot 'offline-installer.sed'
$installScriptSource = Join-Path $ProjectRoot 'electron\offline-install.ps1'
$installCmdSource = Join-Path $ProjectRoot 'electron\offline-install.cmd'
$installScriptTarget = Join-Path $stagingRoot 'install.ps1'
$installCmdTarget = Join-Path $stagingRoot 'install.cmd'
if (-not (Test-Path $appOutDir)) {
throw 'win-unpacked directory not found, run the app stage first'
}
if (-not (Test-Path $primaryExePath)) {
if (-not (Test-Path $fallbackExePath)) {
throw 'win-unpacked executable not found'
}
Copy-Item -Path $fallbackExePath -Destination $primaryExePath -Force
}
if (Test-Path $stagingRoot) {
Remove-Item -Path $stagingRoot -Recurse -Force
}
Ensure-Dir $stagingRoot
Copy-Item -Path $installScriptSource -Destination $installScriptTarget -Force
Copy-Item -Path $installCmdSource -Destination $installCmdTarget -Force
Compress-Archive -Path (Join-Path $appOutDir '*') -DestinationPath $payloadZipPath -Force
$sourceFilesPath = Get-ShortPath $stagingRoot
$sedContent = @"
[Version]
Class=IEXPRESS
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=1
HideExtractAnimation=1
UseLongFileName=1
InsideCompressed=1
CAB_FixedSize=0
CAB_ResvCodeSigning=0
RebootMode=N
InstallPrompt=%InstallPrompt%
DisplayLicense=%DisplayLicense%
FinishMessage=%FinishMessage%
TargetName=%TargetName%
FriendlyName=%FriendlyName%
AppLaunched=%AppLaunched%
PostInstallCmd=%PostInstallCmd%
AdminQuietInstCmd=%AdminQuietInstCmd%
UserQuietInstCmd=%UserQuietInstCmd%
SourceFiles=SourceFiles
[Strings]
InstallPrompt=
DisplayLicense=
FinishMessage=printServer installation completed.
TargetName=$targetPath
FriendlyName=printServer Installer
AppLaunched=install.cmd
PostInstallCmd=<None>
AdminQuietInstCmd=install.cmd /quiet
UserQuietInstCmd=install.cmd /quiet
FILE0=install.cmd
FILE1=install.ps1
FILE2=printServer-app.zip
[SourceFiles]
SourceFiles0=$sourceFilesPath
[SourceFiles0]
%FILE0%=
%FILE1%=
%FILE2%=
"@
Set-Content -Path $sedPath -Value $sedContent -Encoding ASCII
& iexpress.exe /N /Q $sedPath
if ($LASTEXITCODE -ne 0) {
throw "IExpress failed with exit code $LASTEXITCODE"
}
if (-not (Test-Path $targetPath)) {
throw 'IExpress completed without producing the setup executable'
}
Write-Host "Offline installer created: $targetPath"

334
electron/main.cjs Normal file
View File

@ -0,0 +1,334 @@
const { app, BrowserWindow, Menu, Tray, nativeImage } = require('electron');
const path = require('path');
const net = require('net');
const { spawn } = require('child_process');
const { pathToFileURL } = require('url');
let mainWindow = null;
let tray = null;
let isQuitting = false;
let serverStarted = false;
let backendProcess = null;
let reconcileTimer = null;
let reconcilePromise = null;
const MAIN_URL = 'http://127.0.0.1:3000/';
const BACKEND_RUNNER_ARG = '--backend-runner';
const SERVICE_RUNNER_ARG = '--service-runner';
const RECONCILE_INTERVAL_MS = 5000;
const TRAY_ICON_DATA_URL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAV0lEQVR4AWP4TwAw/P//PwMDA8P///8ZGRkYGBgY/v//z8DAwMDA8J8B4v///5kYGRkZGBj+////PwMDw38Ghv9kZGQYGBj+////PwPDfwYGhv8MDAwA0rQYV5vWJ2EAAAAASUVORK5CYII=';
function createTrayImage() {
return nativeImage.createFromDataURL(TRAY_ICON_DATA_URL).resize({ width: 16, height: 16 });
}
async function startLocalServer() {
if (serverStarted) {
return;
}
serverStarted = true;
const entryFile = path.join(__dirname, '..', 'index.js');
await import(pathToFileURL(entryFile).href);
}
function hasArg(flag) {
return process.argv.includes(flag);
}
function isHeadlessRunner() {
return hasArg(BACKEND_RUNNER_ARG) || hasArg(SERVICE_RUNNER_ARG);
}
async function loadWorkspaceModule(relativePath) {
const filePath = path.join(__dirname, '..', relativePath);
return import(pathToFileURL(filePath).href);
}
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function isPortReachable(port) {
return new Promise((resolve) => {
const socket = net.createConnection({ host: '127.0.0.1', port });
let settled = false;
const finish = (result) => {
if (settled) {
return;
}
settled = true;
socket.destroy();
resolve(result);
};
socket.setTimeout(1000);
socket.once('connect', () => finish(true));
socket.once('timeout', () => finish(false));
socket.once('error', () => finish(false));
});
}
async function isBackendReady() {
const [httpReady, wsReady] = await Promise.all([
isPortReachable(3000),
isPortReachable(3001)
]);
return httpReady && wsReady;
}
async function readRuntimeConfig() {
const configUtil = (await loadWorkspaceModule('utils/config.js')).default;
return configUtil.read();
}
async function getWindowsServiceHelper() {
return loadWorkspaceModule('utils/windowsService.js');
}
function getManagedBackendArgs() {
if (app.isPackaged) {
return [BACKEND_RUNNER_ARG];
}
return [app.getAppPath(), BACKEND_RUNNER_ARG];
}
function startManagedBackend() {
if (backendProcess || !app.isPackaged) {
return;
}
backendProcess = spawn(process.execPath, getManagedBackendArgs(), {
stdio: 'ignore',
windowsHide: true
});
backendProcess.once('exit', () => {
backendProcess = null;
});
}
async function stopManagedBackend() {
if (!backendProcess) {
return;
}
const child = backendProcess;
backendProcess = null;
child.kill();
await delay(800);
}
async function ensureDesiredBackendState() {
if (!app.isPackaged) {
await startLocalServer();
return;
}
const config = await readRuntimeConfig();
let backendReady = await isBackendReady();
const serviceHelper = await getWindowsServiceHelper();
if (config.isService) {
if (backendProcess) {
await stopManagedBackend();
backendReady = await isBackendReady();
}
try {
const status = await serviceHelper.ensureServiceInstalled();
if (!backendReady && !status.running) {
await serviceHelper.startService();
}
return;
} catch (error) {
console.error('[Runtime] 系统服务启动失败,回退到本地后端:', error);
}
} else {
try {
const status = await serviceHelper.getServiceStatus();
if (status.installed) {
await serviceHelper.uninstallService();
backendReady = await isBackendReady();
}
} catch (error) {
console.error('[Runtime] 清理系统服务失败:', error);
}
}
if (!backendReady && !backendProcess) {
startManagedBackend();
}
}
async function reconcileBackendState() {
if (reconcilePromise) {
return reconcilePromise;
}
reconcilePromise = ensureDesiredBackendState().finally(() => {
reconcilePromise = null;
});
return reconcilePromise;
}
function startReconcileLoop() {
if (reconcileTimer || !app.isPackaged) {
return;
}
reconcileTimer = setInterval(() => {
reconcileBackendState().catch((error) => {
console.error('[Runtime] 状态同步失败:', error);
});
}, RECONCILE_INTERVAL_MS);
}
function stopReconcileLoop() {
if (!reconcileTimer) {
return;
}
clearInterval(reconcileTimer);
reconcileTimer = null;
}
function showMainWindow() {
if (!mainWindow) {
return;
}
if (mainWindow.isMinimized()) {
mainWindow.restore();
}
mainWindow.show();
mainWindow.focus();
}
function loadMainPage() {
if (!mainWindow || mainWindow.isDestroyed()) {
return;
}
mainWindow.loadURL(MAIN_URL).catch(() => {
setTimeout(loadMainPage, 1000);
});
}
function createMainWindow() {
mainWindow = new BrowserWindow({
width: 1280,
height: 900,
minWidth: 1024,
minHeight: 720,
show: false,
autoHideMenuBar: true,
title: 'printServer',
webPreferences: {
contextIsolation: true,
nodeIntegration: false
}
});
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
mainWindow.on('close', (event) => {
if (isQuitting) {
return;
}
event.preventDefault();
mainWindow.hide();
});
mainWindow.on('minimize', (event) => {
event.preventDefault();
mainWindow.hide();
});
loadMainPage();
}
function createTray() {
tray = new Tray(createTrayImage());
tray.setToolTip('printServer');
const contextMenu = Menu.buildFromTemplate([
{
label: '打开主界面',
click: () => showMainWindow()
},
{
label: '退出',
click: () => {
isQuitting = true;
app.quit();
}
}
]);
tray.setContextMenu(contextMenu);
tray.on('double-click', () => showMainWindow());
tray.on('click', () => showMainWindow());
}
async function bootstrap() {
if (isHeadlessRunner()) {
await startLocalServer();
return;
}
await reconcileBackendState();
startReconcileLoop();
createMainWindow();
createTray();
}
const singleInstanceLock = isHeadlessRunner() ? true : app.requestSingleInstanceLock();
if (!singleInstanceLock) {
app.quit();
} else {
if (!isHeadlessRunner()) {
app.on('second-instance', () => {
showMainWindow();
});
}
app.whenReady().then(bootstrap);
if (!isHeadlessRunner()) {
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
} else {
showMainWindow();
}
});
}
app.on('before-quit', () => {
isQuitting = true;
stopReconcileLoop();
if (backendProcess) {
backendProcess.kill();
backendProcess = null;
}
});
if (!isHeadlessRunner()) {
app.on('window-all-closed', (event) => {
event.preventDefault();
});
}
}

View File

@ -0,0 +1,4 @@
@echo off
setlocal
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0install.ps1" %*
exit /b %errorlevel%

View File

@ -0,0 +1,73 @@
param(
[switch]$Quiet
)
$ErrorActionPreference = 'Stop'
function Ensure-Dir([string]$PathValue) {
if (-not (Test-Path $PathValue)) {
New-Item -ItemType Directory -Path $PathValue -Force | Out-Null
}
}
function New-Shortcut([string]$ShortcutPath, [string]$TargetPath, [string]$WorkingDirectory, [string]$Description) {
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($ShortcutPath)
$shortcut.TargetPath = $TargetPath
$shortcut.WorkingDirectory = $WorkingDirectory
$shortcut.Description = $Description
$shortcut.IconLocation = $TargetPath
$shortcut.Save()
}
$zipPath = Join-Path $PSScriptRoot 'printServer-app.zip'
$installRoot = Join-Path $env:LOCALAPPDATA 'Programs'
$installDir = Join-Path $installRoot 'printServer'
$tempExtractDir = Join-Path $env:TEMP ("printServer-install-" + [guid]::NewGuid().ToString('N'))
$exePath = Join-Path $installDir 'printServer.exe'
if (-not (Test-Path $zipPath)) {
throw 'Installer payload archive was not found.'
}
Ensure-Dir $installRoot
Ensure-Dir $tempExtractDir
try {
$running = Get-Process -Name 'printServer' -ErrorAction SilentlyContinue
if ($running) {
$running | Stop-Process -Force
Start-Sleep -Milliseconds 500
}
if (Test-Path $installDir) {
Remove-Item -Path $installDir -Recurse -Force
}
Ensure-Dir $installDir
Expand-Archive -Path $zipPath -DestinationPath $tempExtractDir -Force
Copy-Item -Path (Join-Path $tempExtractDir '*') -Destination $installDir -Recurse -Force
if (-not (Test-Path $exePath)) {
throw 'Installed executable was not found after extraction.'
}
$desktopShortcut = Join-Path ([Environment]::GetFolderPath('Desktop')) 'printServer.lnk'
$startMenuDir = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs'
$startMenuShortcut = Join-Path $startMenuDir 'printServer.lnk'
Ensure-Dir $startMenuDir
New-Shortcut -ShortcutPath $desktopShortcut -TargetPath $exePath -WorkingDirectory $installDir -Description 'printServer'
New-Shortcut -ShortcutPath $startMenuShortcut -TargetPath $exePath -WorkingDirectory $installDir -Description 'printServer'
Start-Process -FilePath $exePath -WorkingDirectory $installDir
if (-not $Quiet) {
Write-Host "printServer installed to $installDir"
}
}
finally {
if (Test-Path $tempExtractDir) {
Remove-Item -Path $tempExtractDir -Recurse -Force
}
}

10
index.js Normal file
View File

@ -0,0 +1,10 @@
import http from 'http';
import configUtil from './utils/config.js';
import app from './core/main.js'
const server = http.createServer((req, res) => {
app.router(req, res);
});
server.listen(app.config.port, () => {
console.log(`服务器已启动,监听端口: ${app.config.port}`);
});

13
nodemon.json Normal file
View File

@ -0,0 +1,13 @@
{
"watch": [
"index.js",
"core/*",
"views/*",
"services/*"
],
"ext": "js,json,html",
"ignore": [
"node_modules/*"
],
"exec": "node index.js"
}

5210
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

84
package.json Normal file
View File

@ -0,0 +1,84 @@
{
"name": "printserver",
"version": "1.0.1",
"main": "electron/main.cjs",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon index.js",
"desktop:dev": "electron .",
"package:clean": "powershell -ExecutionPolicy Bypass -File build.ps1 clean",
"package:prepare": "powershell -ExecutionPolicy Bypass -File build.ps1 prepare",
"package:app": "powershell -ExecutionPolicy Bypass -File build.ps1 app",
"package:win": "powershell -ExecutionPolicy Bypass -File build.ps1 win",
"package": "powershell -ExecutionPolicy Bypass -File build.ps1 package"
},
"author": "",
"license": "ISC",
"description": "Windows local print service with HTTP, WebSocket, tray shell and printer component integration",
"dependencies": {
"iconv-lite": "^0.7.2",
"node-windows": "^1.0.0-beta.8",
"ws": "^8.19.0"
},
"devDependencies": {
"electron": "^37.2.0",
"electron-builder": "^26.0.12",
"nodemon": "^3.0.0",
"rimraf": "^6.0.1"
},
"type": "module",
"build": {
"appId": "com.gztbyc.printserver",
"productName": "printServer",
"directories": {
"output": "dist"
},
"files": [
"electron/**/*",
"controllers/**/*",
"core/**/*",
"services/**/*",
"utils/**/*",
"views/**/*",
"routes.js",
"index.js",
"package.json",
"!临时/**/*",
"!开发日志/**/*",
"!day.log",
"!.vscode/**/*"
],
"extraResources": [
{
"from": "config.packaged.json",
"to": "config.json"
},
"printer.ps1",
{
"from": "daemon",
"to": "daemon"
}
],
"win": {
"executableName": "electron",
"signAndEditExecutable": false,
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
],
"artifactName": "printServer-${version}-setup.${ext}"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"createStartMenuShortcut": true,
"shortcutName": "printServer"
}
}
}

View File

@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}

71
printer.ps1 Normal file
View File

@ -0,0 +1,71 @@
param(
[string[]]$PrinterNames, # Printers to monitor, empty array means all
[int]$IntervalSeconds = 2 # Polling interval (seconds)
)
$OutputEncoding = [System.Text.Encoding]::UTF8
if (-not $PrinterNames) { $PrinterNames = @() }
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Printer Status Monitor" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Start time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
if ($PrinterNames.Count -gt 0) {
Write-Host "Monitoring printers: $($PrinterNames -join ', ')"
} else {
Write-Host "Monitoring all printers"
}
Write-Host "Press Ctrl+C to stop monitoring"
Write-Host ""
# Cache last status to avoid duplicate output
$lastStatus = @{}
function Get-PrinterStatusText($status) {
switch ($status) {
3 { "Idle" }
4 { "Printing" }
5 { "Warming Up" }
6 { "Paused" }
7 { "Offline" }
8 { "Disconnected" }
default { "Unknown($status)" }
}
}
function Get-ErrorText($errorState) {
switch ($errorState) {
2 { "Paper Jam" }
3 { "Out of Paper" }
4 { "Out of Ink/Toner" }
5 { "Mechanical Failure" }
default { "Error code: $errorState" }
}
}
try {
while ($true) {
$printers = Get-WmiObject -Class Win32_Printer
foreach ($printer in $printers) {
if ($PrinterNames.Count -gt 0 -and ($PrinterNames -notcontains $printer.Name)) { continue }
$name = $printer.Name
$status = $printer.PrinterStatus
$offline = $printer.WorkOffline
$errorState = $printer.DetectedErrorState
$statusText = Get-PrinterStatusText $status
$onlineText = if ($offline) { "Offline" } else { "Online" }
$statusKey = "$status|$offline"
if ($lastStatus.ContainsKey($name) -and $lastStatus[$name] -eq $statusKey) { continue }
$lastStatus[$name] = $statusKey
$color = if ($offline) { "Red" } elseif ($status -eq 4) { "Yellow" } else { "Green" }
$time = Get-Date -Format "HH:mm:ss"
Write-Host "$time ${name}: $statusText ($onlineText)" -ForegroundColor $color
if ($errorState -and $errorState -ne 0) {
$errorText = Get-ErrorText $errorState
Write-Host " └─ Error: $errorText" -ForegroundColor Red
}
}
Start-Sleep -Seconds $IntervalSeconds
}
} finally {
Write-Host "`nMonitoring stopped" -ForegroundColor Yellow
}

6
routes.js Normal file
View File

@ -0,0 +1,6 @@
// 路由配置,只需写控制器类和方法名
const routes = [
{ method: 'GET', path: '/', controller: 'index.index' },
];
export default routes

29
services/bind.js Normal file
View File

@ -0,0 +1,29 @@
import fs from 'fs';
import path from 'path';
import configUtil from '../utils/config.js';
import service from '../core/BaseService.js';
const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, '')));
const configPath = path.join(__dirname, '../config.json');
class BindService extends service {
constructor() {
super();
this.generateCode = this.generateCode.bind(this); // 确保上下文绑定
this.tokenInfo = this.tokenInfo.bind(this); // 确保上下文绑定
}
generateCode(data) {
const {app} = this;
this.app.randomCode = data;
this.app.emit('generateCode', data);
}
tokenInfo(data) {
const {app} = this;
app.config.token = data.jwtToken;
app.config.refreshToken = data.refreshToken;
app.config.tokenExpireTime = data.tokenExpireTime;
configUtil.write(app.config);
app.isBind = true;
}
};
export default BindService;

28
services/config.js Normal file
View File

@ -0,0 +1,28 @@
import fs from 'fs';
import path from 'path';
import service from '../core/BaseService.js';
const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, '')));
const configPath = path.join(__dirname, '../config.json');
class ConfigService extends service {
constructor() {
super();
}
read() {
try {
return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
} catch {
return {};
}
}
write(newConfig) {
try {
fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2), 'utf-8');
return true;
} catch {
return false;
}
}
};

102
services/printer.js Normal file
View File

@ -0,0 +1,102 @@
import service from '../core/BaseService.js';
import { exec } from 'child_process';
import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
import lodopUtil from '../utils/lodop.js';
// 打印机服务类
class PrinterService extends service {
constructor() {
super();
this.getWindowsPrinters = this.getWindowsPrinters.bind(this); // 确保上下文绑定
this.print = this.print.bind(this); // 确保上下文绑定
}
// 读取 Windows 打印服务的打印机列表,返回 Promise<json>
async getWindowsPrinters() {
const res = new Promise((resolve, reject) => {
const command = `powershell -NoProfile -Command "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-CimInstance Win32_Printer | Select-Object Name,WorkOffline | ConvertTo-Json -Compress"`;
exec(command, { encoding: 'buffer', maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
if (err) {
const stderrText = stderr ? stderr.toString('utf8').trim() : '';
return reject(new Error(stderrText || err.message));
}
const output = stdout.toString('utf8').trim();
if (!output) {
return resolve([]);
}
const parsed = JSON.parse(output);
const list = Array.isArray(parsed) ? parsed : [parsed];
const printers = list
.filter(item => item && item.Name)
.map(item => ({
name: item.Name,
workOffline: item.WorkOffline ? 'TRUE' : 'FALSE'
}));
resolve(printers);
});
});
res.then(printers => {
console.log('获取到打印机列表:', printers);
this.app.emit("printerList", printers); // 触发打印机列表事件,携带打印机列表数据
}).catch(err => {
console.error('获取打印机列表失败:', err);
});
}
print(data) {
console.log("打印服务收到打印请求,数据:", data);
const { printerComponents } = this.app;
console.log("所有打印组件", printerComponents.components);
console.log("准备打印,数据:", data);
// 根据data.type选择不同的打印组件和打印方式
// 每个打印只接收一个组件,在服务端做拆分
//data的结构示例:
// {
// printId: '123456', // 打印任务ID,唯一标识一次打印请求
// type: 'customize' | 'express', // 打印类型,customize表示自定义打印,express表示快递单打印
// component: 'douyin' | 'pinduoduo' | 'kuaishou' | 'jingdong' | 'cainiao' | 'shipinhao' | 'xiaohongshu', // 打印组件,仅express类型需要
// printer: '打印机名称', // 目标打印机名称
// data: { // 打印数据,结构根据type不同而不同
// // customize类型示例
// pageWidth: 80, // 页面宽度,单位mm
// pageHeight: 50, // 页面高度,单位mm
// htm: '<div style="font-size:14px;">自定义打印内容</div>', // HTML格式的打印内容
// // express类型示例
//
// }
// }
let component = null;
let printData = null;
switch (data.type) {
case "customize":
component = printerComponents.components.get('LODOP');
printData = this.renderCustomPrintContent(data);
break;
case "express":
component = printerComponents.components.get(data.component);
printData = data.data; // 直接使用后端传来的数据
default:
}
this.app.printTasks = this.app.printTasks || new Map();
this.app.printTasks.set(data.printId, 'pending');
if (component && component.readyState === 1) {
//console.log("使用组件打印,组件:", component, "打印数据:", printData);
component.send(printData);
} else {
this.app.emit('printError', { message: '打印组件未连接', printId: data.printId });
return;
}
}
//渲染自定义打印内容,返回HTML字符串
renderCustomPrintContent(data) {
const lodop = new lodopUtil();
lodop.PRINT_INIT(`tid:${data.printId}`);
lodop.SET_LICENSES(data.data.lodopkey[0],data.data.lodopkey[1],data.data.lodopkey[2],data.data.lodopkey[3]);
lodop.SET_PRINTER_INDEXA(data.printer);
lodop.SET_PRINT_PAGESIZE(0, data.data.pageWidth*10, data.data.pageHeight*10, "");
lodop.ADD_PRINT_HTM(0, 0, "100%", "100%", data.data.htm);
return lodop.EXPORT_INSTRUCTIONS();
}
}
export default new PrinterService();

View File

@ -0,0 +1,35 @@
import service from '../core/BaseService.js';
class PrinterComponentService extends service {
constructor() {
super();
this.getAll = this.getAll.bind(this); // 确保上下文绑定
this.getStatus = this.getStatus.bind(this);
}
// 获取所有打印组件
getAll() {
const { app } = this;
if (app && app.printerComponents) {
const components = app.printerComponents.getAllPorts();
const status = app.printerComponents.getAllStatus();
return { components, status };
}
// 默认返回静态数据
return { components: this.components, status: this.components.map(c => ({ name: c.name, status: c.status })) };
}
// 获取指定组件状态
getStatus(name) {
const { app } = this;
if (app && app.printerComponents) {
return app.printerComponents.getStatus(name);
}
const comp = this.components.find(c => c.name === name);
return comp ? comp.status : '未知';
}
// 可扩展:添加、删除、更新组件等
}
export default new PrinterComponentService();

124
services/setting.js Normal file
View File

@ -0,0 +1,124 @@
import service from '../core/BaseService.js';
import configUtil from '../utils/config.js';
import { ensureServiceInstalled, uninstallService } from '../utils/windowsService.js';
function isServiceRunnerProcess() {
return process.argv.includes('--service-runner');
}
class SettingService extends service {
constructor() {
super();
this.info = this.info.bind(this);
this.unbind = this.unbind.bind(this);
this.register = this.register.bind(this);
this.unregister = this.unregister.bind(this);
this.setToken = this.setToken.bind(this);
this.setInfo = this.setInfo.bind(this);
}
// 判断是否已绑定
info() {
const {config} = this;
return {
isBind: !!config.token,
name: config.name || '',
isService: !!config.isService
};
}
// 解绑(WebSocket/HTTP 通用,无 ctx 依赖)
unbind() {
const { config } = this;
config.token = '';
configUtil.write(config);
this.app.isBind = false;
return { ok: true, message: '解绑成功' };
}
// WebSocket 注册服务,切换为“系统服务管理后端”的状态
async register() {
const { config } = this;
try {
await ensureServiceInstalled();
} catch (error) {
config.isService = false;
configUtil.write(config);
this.app.isServices = false;
return {
ok: false,
message: `系统服务注册失败:${error.message}`,
isServices: false
};
}
config.isService = true;
configUtil.write(config);
this.app.isServices = true;
return {
ok: true,
message: '服务模式已启用,桌面壳会改为通过系统服务拉起后端',
isServices: true
};
}
// WebSocket 注销服务,切回“桌面壳直接拉起后端”的状态
async unregister() {
const { config } = this;
config.isService = false;
configUtil.write(config);
this.app.isServices = false;
if (!isServiceRunnerProcess()) {
try {
await uninstallService();
} catch (error) {
config.isService = true;
configUtil.write(config);
this.app.isServices = true;
return {
ok: false,
message: `系统服务注销失败:${error.message}`,
isServices: true
};
}
}
return {
ok: true,
message: isServiceRunnerProcess()
? '服务模式已关闭,桌面壳会切回本地后端启动并清理系统服务'
: '服务已注销,后端将恢复为桌面壳直接启动',
isServices: false
};
}
async setToken(data) {
const { config } = this;
config.token = data.token;
config.tokenExpireTime = data.tokenExpireTime;
configUtil.write(config);
this.app.isBind = !!data.token;
//重载设置
await this.app.wsClient._checkAuth();
}
async setInfo(data) {
const { config, app } = this;
config.name = data.name;
console.log("设置打印台信息", data);
app.info = data;
configUtil.write(config);
// 登录成功后主动全量同步一次组件状态,避免服务端只收到后续增量变化
if (app.wsClient && app.printerComponents) {
const allStatus = app.printerComponents.getAllStatus();
for (const item of allStatus) {
app.wsClient.send({ method: 'printerComponent.statusChange', data: item });
}
}
return { ok: true };
}
}
export default new SettingService();

53
utils/config.js Normal file
View File

@ -0,0 +1,53 @@
import fs from 'fs';
import { ensureWritableConfigFile, getBundledConfigPath, getWritableConfigPath } from './runtime.js';
function readJson(filePath) {
try {
if (!filePath || !fs.existsSync(filePath)) {
return {};
}
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
} catch {
return {};
}
}
function mergeConfig(defaultConfig, currentConfig) {
return {
...defaultConfig,
...currentConfig,
remoteWs: {
...(defaultConfig.remoteWs || {}),
...(currentConfig.remoteWs || {})
}
};
}
export default {
read() {
try {
const configPath = ensureWritableConfigFile();
const bundledConfig = readJson(getBundledConfigPath());
const writableConfig = readJson(configPath);
const mergedConfig = mergeConfig(bundledConfig, writableConfig);
if (JSON.stringify(writableConfig) !== JSON.stringify(mergedConfig)) {
fs.writeFileSync(configPath, JSON.stringify(mergedConfig, null, 2), 'utf-8');
}
return mergedConfig;
} catch {
return {};
}
},
write(newConfig) {
try {
const configPath = getWritableConfigPath();
fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2), 'utf-8');
return true;
} catch {
return false;
}
}
};

521
utils/lodop.js Normal file
View File

@ -0,0 +1,521 @@
// CLodop.js - 后端使用的 CLodop 对象
class CLodop {
constructor() {
// 核心数据结构
this.PageData = {}; // 页面级参数
this.PageDataEx = {}; // 扩展参数(如注册信息)
this.ItemDatas = { count: 0 }; // 打印项集合
this.defStyleJson = { // 默认样式
beginpage: 0,
beginpagea: 0
};
this.ItemCNameStyles = {}; // 样式类名
// 分隔符(与 C-Lodop 协议一致)
this.DelimChar = '\f\f';
// 任务标识
this.strWebPageID = "";
this.strTaskID = "";
this.iBaseTask = 0;
// 状态标志
this.blWorking = false;
this.NoClearAfterPrint = false;
this.blNormalItemAdded = false;
}
/**
* 生成任务ID
*/
GetTaskID() {
if (!this.strTaskID || this.strTaskID === "") {
const dt = new Date();
this.iBaseTask++;
this.strTaskID = `${dt.getHours()}${dt.getMinutes()}${dt.getSeconds()}_${this.iBaseTask}`;
}
return this.strWebPageID + this.strTaskID;
}
/**
* 初始化/重置任务
*/
DoInit() {
this.strTaskID = "";
if (this.NoClearAfterPrint) return;
this.ItemDatas = { count: 0 };
this.PageData = {};
this.ItemCNameStyles = {};
this.defStyleJson = {
beginpage: 0,
beginpagea: 0
};
this.blNormalItemAdded = false;
}
// ==================== 初始化方法 ====================
PRINT_INIT(strPrintTask) {
return this.PRINT_INITA(null, null, null, null, strPrintTask);
}
PRINT_INITA(Top, Left, Width, Height, strPrintTask) {
if (Top === undefined || Top === null) Top = "";
if (Left === undefined || Left === null) Left = "";
if (Width === undefined || Width === null) Width = "";
if (Height === undefined || Height === null) Height = "";
if (strPrintTask === undefined || strPrintTask === null) strPrintTask = "";
this.NoClearAfterPrint = false;
this.DoInit();
this.PageData["top"] = Top;
this.PageData["left"] = Left;
this.PageData["width"] = Width;
this.PageData["height"] = Height;
this.PageData["printtask"] = strPrintTask;
this.strTaskID = strPrintTask;
// console.log("PRINT_INITA 修改后 PageData:", this.PageData);
return true;
}
// ==================== 打印项添加方法 ====================
ADD_PRINT_TEXT(top, left, width, height, strText) {
return this._addItem(2, top, left, width, height, strText);
}
ADD_PRINT_TEXTA(itemName, top, left, width, height, strText) {
return this._addItem(2, top, left, width, height, strText, itemName);
}
ADD_PRINT_HTM(top, left, width, height, strHTML) {
return this._addItem(4, top, left, width, height, strHTML);
}
ADD_PRINT_HTML(top, left, width, height, strHTML) {
return this._addItem(1, top, left, width, height, strHTML);
}
ADD_PRINT_HTMLA(itemName, top, left, width, height, strHTML) {
return this._addItem(1, top, left, width, height, strHTML, itemName);
}
ADD_PRINT_TABLE(top, left, width, height, strHTML) {
return this._addItem(6, top, left, width, height, strHTML);
}
ADD_PRINT_URL(top, left, width, height, strURL) {
return this._addItem(5, top, left, width, height, strURL);
}
ADD_PRINT_IMAGE(top, left, width, height, strHTML) {
return this._addItem(8, top, left, width, height, strHTML);
}
ADD_PRINT_PDF(top, left, width, height, strContent) {
return this._addItem(11, top, left, width, height, strContent);
}
ADD_PRINT_BARCODE(top, left, width, height, BarType, BarValue) {
return this._addItem(9, top, left, width, height, BarValue, null, null, null, null, null, null, BarType);
}
ADD_PRINT_BARCODEA(ItemName, top, left, width, height, BarType, BarValue) {
return this._addItem(9, top, left, width, height, BarValue, ItemName, null, null, null, null, null, BarType);
}
ADD_PRINT_RECT(top, left, width, height, intPenStyle, intPenWidth) {
return this._addItem(3, top, left, width, height, null, null, 2, intPenStyle, intPenWidth);
}
ADD_PRINT_RECTA(top, left, width, height, intPenStyle, intPenWidth, intColor) {
return this._addItem(3, top, left, width, height, null, null, 2, intPenStyle, intPenWidth, intColor);
}
ADD_PRINT_ELLIPSE(top, left, width, height, intPenStyle, intPenWidth) {
return this._addItem(3, top, left, width, height, null, null, 3, intPenStyle, intPenWidth);
}
ADD_PRINT_ELLIPSEA(top, left, width, height, intPenStyle, intPenWidth, intColor) {
return this._addItem(3, top, left, width, height, null, null, 3, intPenStyle, intPenWidth, intColor);
}
ADD_PRINT_LINE(top1, left1, top2, left2, intPenStyle, intPenWidth) {
return this._addItem(3, top1, left1, top2, left2, null, null, 0, intPenStyle, intPenWidth, null, "1");
}
ADD_PRINT_UPLINE(Top, Left, Width, Height, intPenStyle, intPenWidth) {
return this._addItem(3, Top, Left, Width, Height, null, null, 0, intPenStyle, intPenWidth);
}
ADD_PRINT_UPLINEA(Top, Left, Width, Height, intPenStyle, intPenWidth, intColor) {
return this._addItem(3, Top, Left, Width, Height, null, null, 0, intPenStyle, intPenWidth, intColor);
}
ADD_PRINT_DNLINE(Top, Left, Width, Height, intPenStyle, intPenWidth) {
return this._addItem(3, Top, Left, Width, Height, null, null, 1, intPenStyle, intPenWidth);
}
ADD_PRINT_DNLINEA(Top, Left, Width, Height, intPenStyle, intPenWidth, intColor) {
return this._addItem(3, Top, Left, Width, Height, null, null, 1, intPenStyle, intPenWidth, intColor);
}
/**
* 内部添加项方法
*/
_addItem(type, top, left, width, height, strContent, itemname, ShapeType, intPenStyle, intPenWidth, intColor, isLinePosition, BarType, strChartTypess) {
if (top === undefined || left === undefined || width === undefined || height === undefined) {
return false;
}
const sCount = this.ItemDatas.count + 1;
// 创建新项,继承默认样式
const oneItem = { ...this.defStyleJson };
oneItem["type"] = type;
oneItem["top"] = top;
oneItem["left"] = left;
oneItem["width"] = width;
oneItem["height"] = height;
if (strContent != null) {
oneItem["content"] = strContent;
}
if (itemname !== undefined && itemname != null) oneItem["itemname"] = String(itemname);
if (ShapeType !== undefined && ShapeType != null) oneItem["shapetype"] = ShapeType;
if (intPenStyle !== undefined && intPenStyle != null) oneItem["penstyle"] = intPenStyle;
if (intPenWidth !== undefined && intPenWidth != null) oneItem["penwidth"] = intPenWidth;
if (intColor !== undefined && intColor != null) oneItem["fontcolor"] = intColor;
if (isLinePosition !== undefined && isLinePosition != null) oneItem["lineposition"] = "1";
if (BarType !== undefined && BarType != null) oneItem["fontname"] = BarType;
if (strChartTypess !== undefined && strChartTypess != null) oneItem["charttypess"] = strChartTypess;
oneItem["beginpage"] = this.defStyleJson["beginpage"];
oneItem["beginpagea"] = this.defStyleJson["beginpagea"];
this.ItemDatas.count = sCount;
this.ItemDatas[sCount] = oneItem;
this.blNormalItemAdded = true;
return true;
}
// ==================== 样式设置方法 ====================
SET_PRINT_STYLE(strStyleName, StyleValue) {
if (strStyleName === undefined || strStyleName === null || strStyleName === "") return false;
strStyleName = strStyleName.toLowerCase();
this.defStyleJson[strStyleName] = StyleValue;
return true;
}
SET_PRINT_STYLEA(ItemNo, strKey, Value) {
if (ItemNo === undefined || ItemNo === null || ItemNo === "" ||
strKey === undefined || strKey === null || strKey === "") return false;
if (this.ItemDatas.count <= 0) {
if (this.PageData["add_print_program_data"] !== undefined) {
this.ItemCNameStyles[strKey.toLowerCase() + "-" + ItemNo] = Value;
return true;
}
return false;
}
strKey = strKey.toLowerCase();
if (strKey === "type") return false;
let blResult = false;
// 处理 ItemNo 为 0 的情况(表示最后一个项)
if (ItemNo === 0) {
ItemNo = this.ItemDatas.count;
}
// 遍历查找匹配的项
for (let vItemNO in this.ItemDatas) {
if (vItemNO === "count") continue;
const ItemName = this.ItemDatas[vItemNO]["itemname"];
if ((ItemNo == vItemNO) || (ItemNo == ItemName) ||
(typeof ItemNo === "string" && typeof ItemName === "string" &&
ItemNo.toUpperCase() === ItemName.toUpperCase())) {
this.ItemDatas[vItemNO][strKey] = Value;
blResult = true;
}
}
return blResult;
}
SET_PRINT_TEXT_STYLE(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment) {
this.SET_PRINT_STYLEA(ItemNO, "fontname", strFontName);
this.SET_PRINT_STYLEA(ItemNO, "fontsize", intSize);
this.SET_PRINT_STYLEA(ItemNO, "bold", intBold);
this.SET_PRINT_STYLEA(ItemNO, "italic", intItalic);
this.SET_PRINT_STYLEA(ItemNO, "underline", intUnderline);
this.SET_PRINT_STYLEA(ItemNO, "alignment", intAlignment);
return true;
}
SET_PRINT_TEXT_STYLEA(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment, Color) {
this.SET_PRINT_TEXT_STYLE(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment);
this.SET_PRINT_STYLEA(ItemNO, "fontcolor", Color);
return true;
}
// ==================== 页面控制 ====================
SET_PRINT_PAGESIZE(intOrient, PageWidth, PageHeight, strPageName) {
if (intOrient !== undefined && intOrient !== null) this.PageData["orient"] = intOrient;
if (PageWidth !== undefined && PageWidth !== null) this.PageData["pagewidth"] = PageWidth;
if (PageHeight !== undefined && PageHeight !== null) this.PageData["pageheight"] = PageHeight;
if (strPageName !== undefined && strPageName !== null) this.PageData["pagename"] = strPageName;
// console.log("SET_PRINT_PAGESIZE 修改后 PageData:", this.PageData);
return true;
}
SET_PRINT_COPIES(intCopies) {
if (intCopies !== undefined && intCopies !== null) {
this.PageData["printcopies"] = intCopies;
// console.log("SET_PRINT_COPIES 修改后 PageData:", this.PageData);
return true;
}
return false;
}
SET_PRINT_MODE(strModeType, ModeValue) {
if (strModeType === undefined || strModeType === null || strModeType === "") return false;
strModeType = strModeType.toLowerCase();
this.PageData[strModeType] = ModeValue;
// console.log("SET_PRINT_MODE 修改后 PageData:", this.PageData);
if (strModeType === "noclear_after_print") {
this.NoClearAfterPrint = ModeValue;
}
return true;
}
SET_SHOW_MODE(strModeType, ModeValue) {
if (strModeType === undefined || strModeType === null || strModeType === "") return false;
strModeType = strModeType.toLowerCase();
this.PageData['shwmod_' + strModeType] = ModeValue;
// console.log("SET_SHOW_MODE 修改后 PageData:", this.PageData);
return true;
}
SET_SAVE_MODE(strModeType, ModeValue) {
if (strModeType === undefined || strModeType === null || strModeType === "") return false;
strModeType = strModeType.toLowerCase();
this.PageData['stfmod_' + strModeType] = ModeValue;
// console.log("SET_SAVE_MODE 修改后 PageData:", this.PageData);
return true;
}
// ==================== 打印机设置 ====================
SET_PRINTER_INDEX(strName) {
if (!strName) return false;
strName = String(strName).replace(/^\s+|\s+$/g, "");
const iPos = strName.indexOf(",");
const strNameOrNO = iPos > -1 ? strName.slice(0, iPos) : strName;
this.PageData["printerindex"] = strNameOrNO;
if (iPos > -1) {
this.PageData["printersubid"] = strName.slice(iPos + 1);
}
// console.log("SET_PRINTER_INDEX 修改后 PageData:", this.PageData);
return true;
}
SET_PRINTER_INDEXA(strName) {
if (!strName) return false;
strName = String(strName).replace(/^\s+|\s+$/g, "");
const iPos = strName.indexOf(",");
const strNameOrNO = iPos > -1 ? strName.slice(0, iPos) : strName;
this.PageData["printerindexa"] = strNameOrNO;
if (iPos > -1) {
this.PageData["printersubid"] = strName.slice(iPos + 1);
}
// console.log("SET_PRINTER_INDEXA 修改后 PageData:", this.PageData);
return true;
}
// ==================== 注册信息 ====================
SET_LICENSES(strCompanyName, strLicense, strLicenseA, strLicenseB) {
if ((strCompanyName === 'THIRD LICENSE') && strLicense === "") {
if (strLicenseA && strLicenseA !== "") this.PageDataEx["licensec"] = strLicenseA;
if (strLicenseB && strLicenseB !== "") this.PageDataEx["licensed"] = strLicenseB;
} else if ((strCompanyName === 'LICENSE TETCODE') && strLicense === "" && strLicenseB === "") {
if (strLicenseA && strLicenseA !== "") this.PageDataEx["Licensetetcode"] = strLicenseA;
} else if ((strLicense && strLicense !== "") || (strLicenseA && strLicenseA !== "") || (strLicenseB && strLicenseB !== "")) {
this.PageDataEx["companyname"] = strCompanyName;
this.PageDataEx["license"] = strLicense;
this.PageDataEx["licensea"] = strLicenseA;
this.PageDataEx["licenseb"] = strLicenseB;
}
// console.log("SET_LICENSES 修改后 PageDataEx:", this.PageDataEx);
return true;
}
// ==================== 新页控制 ====================
NEWPAGE() {
this.NewPage();
}
NewPage() {
if (this.blNormalItemAdded) {
this.defStyleJson["beginpage"] = this.defStyleJson["beginpage"] + 1;
}
}
NEWPAGEA() {
this.NewPageA();
}
NewPageA() {
if (this.blNormalItemAdded) {
this.defStyleJson["beginpagea"] = this.defStyleJson["beginpagea"] + 1;
}
}
// ==================== 指令导出方法(核心!) ====================
/**
* 导出打印指令文本(供外部发送)
* @param {string} act 操作类型(print/preview/print_design等)
* @returns {string} 完整的指令报文
*/
EXPORT_INSTRUCTIONS(act = 'print') {
const parts = [];
// 基础部分
parts.push(`post:charset=丂`);
parts.push(`tid=${this.GetTaskID()}`);
parts.push(`act=${act}`);
parts.push(`browseurl=http://www.c-lodop.com/demolist/PrintSample5.html`);
// 扩展参数(注册信息等)
for (const [key, value] of Object.entries(this.PageDataEx)) {
if (value !== undefined && value !== '') {
parts.push(`${key}=${value}`);
}
}
// 收集打印模式名称
const printModeNames = [];
// console.log("this.PageData", this.PageData);
for (const [key, value] of Object.entries(this.PageData)) {
if (value !== undefined && value !== '') {
parts.push(`${key}=${value}`);
// 记录非标准参数名(用于 printmodenames)
if (!['top', 'left', 'width', 'height', 'printtask',
'printerindex', 'printerindexa', 'printersubid',
'orient', 'pagewidth', 'pageheight', 'pagename',
'printcopies', 'setup_bkimg'].includes(key)) {
printModeNames.push(key);
}
}
}
if (printModeNames.length > 0) {
parts.push(`printmodenames=;${printModeNames.join(';')}`);
}
// 样式类名
const styleClassNames = [];
for (const [key, value] of Object.entries(this.ItemCNameStyles)) {
parts.push(`${key}=${value}`);
styleClassNames.push(key);
}
if (styleClassNames.length > 0) {
parts.push(`printstyleclassnames=;${styleClassNames.join(';')}`);
}
// 打印项数量
parts.push(`itemcount=${this.ItemDatas.count}`);
// 处理每个打印项
for (let i = 1; i <= this.ItemDatas.count; i++) {
const item = this.ItemDatas[i];
if (!item) continue;
// 收集此项的样式名称
const itemStyleNames = [];
for (const key of Object.keys(item)) {
if (!['beginpage', 'beginpagea', 'type', 'top', 'left', 'width', 'height'].includes(key)) {
itemStyleNames.push(key);
}
}
parts.push(`${i}_itemstylenames=;${itemStyleNames.join(';')}`);
// 添加此项的所有属性
for (const [key, value] of Object.entries(item)) {
parts.push(`${i}_${key}=${value}`);
}
}
// 结束标记
parts.push(`count_itemstylenames=`);
// console.log("生成的指令文本数组:", parts);
// console.log("this.DelimChar",this.DelimChar)
// 用分隔符连接
return parts.join(this.DelimChar)+this.DelimChar;
}
/**
* 导出预览指令
*/
EXPORT_PREVIEW() {
return this.EXPORT_INSTRUCTIONS('preview');
}
/**
* 导出打印设计指令
*/
EXPORT_PRINT_DESIGN() {
return this.EXPORT_INSTRUCTIONS('print_design');
}
/**
* 导出打印设置指令
*/
EXPORT_PRINT_SETUP() {
return this.EXPORT_INSTRUCTIONS('print_setup');
}
/**
* 导出保存到文件指令
*/
EXPORT_SAVE_TO_FILE(strFileName) {
if (strFileName) {
this.PageData["stf_file_name"] = strFileName;
}
return this.EXPORT_INSTRUCTIONS('savetofile');
}
/**
* 清空任务数据
*/
CLEAR() {
this.DoInit();
this.blWorking = false;
}
}
export default CLodop;

106
utils/runtime.js Normal file
View File

@ -0,0 +1,106 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
const currentFilePath = fileURLToPath(import.meta.url);
const projectRoot = path.resolve(path.dirname(currentFilePath), '..');
export function isElectronRuntime() {
return Boolean(process.versions?.electron);
}
export function isPackagedElectron() {
return isElectronRuntime() && !process.defaultApp;
}
export function getProjectRoot() {
return projectRoot;
}
export function getResourcePath(...segments) {
const candidatePaths = [];
if (isPackagedElectron()) {
candidatePaths.push(path.join(process.resourcesPath, ...segments));
candidatePaths.push(path.join(path.dirname(process.execPath), 'resources', ...segments));
candidatePaths.push(path.join(path.dirname(process.execPath), ...segments));
candidatePaths.push(path.join(projectRoot, ...segments));
} else {
candidatePaths.push(path.join(projectRoot, ...segments));
candidatePaths.push(path.join(process.cwd(), ...segments));
}
for (const candidate of candidatePaths) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return candidatePaths[0];
}
export function ensureDirectory(dirPath) {
fs.mkdirSync(dirPath, { recursive: true });
return dirPath;
}
function getUserRoamingDir() {
return process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
}
function getSharedDataRoot() {
return process.env.ProgramData || path.join(process.env.SystemDrive || 'C:', 'ProgramData');
}
function getLegacyElectronConfigPath() {
return path.join(getUserRoamingDir(), 'printServer', 'config.json');
}
export function getAppDataDir() {
if (!isElectronRuntime()) {
return projectRoot;
}
if (isPackagedElectron()) {
return ensureDirectory(path.join(getSharedDataRoot(), 'printServer'));
}
return ensureDirectory(path.join(getUserRoamingDir(), 'printServer'));
}
export function getBundledConfigPath() {
return getResourcePath('config.json');
}
export function getWritableConfigPath() {
if (!isElectronRuntime()) {
return path.join(projectRoot, 'config.json');
}
return path.join(getAppDataDir(), 'config.json');
}
export function ensureWritableConfigFile() {
const writableConfigPath = getWritableConfigPath();
if (fs.existsSync(writableConfigPath)) {
return writableConfigPath;
}
if (isPackagedElectron()) {
const legacyConfigPath = getLegacyElectronConfigPath();
if (fs.existsSync(legacyConfigPath)) {
fs.copyFileSync(legacyConfigPath, writableConfigPath);
return writableConfigPath;
}
}
const bundledConfigPath = getBundledConfigPath();
if (fs.existsSync(bundledConfigPath)) {
fs.copyFileSync(bundledConfigPath, writableConfigPath);
} else {
fs.writeFileSync(writableConfigPath, '{}\n', 'utf8');
}
return writableConfigPath;
}

241
utils/windowsService.js Normal file
View File

@ -0,0 +1,241 @@
import fs from 'fs';
import path from 'path';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { getProjectRoot, getResourcePath, isElectronRuntime, isPackagedElectron } from './runtime.js';
const execFileAsync = promisify(execFile);
const SERVICE_NAME = 'PrintServer';
const SERVICE_ID = 'printserver.exe';
function assertWindows() {
if (process.platform !== 'win32') {
throw new Error('Windows 服务能力仅支持 Windows 环境');
}
}
function escapeXml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
function getServiceWrapperPath() {
return getResourcePath('daemon', SERVICE_ID);
}
function getServiceXmlPath() {
return getResourcePath('daemon', 'printserver.xml');
}
function getServiceWorkingDirectory() {
if (isPackagedElectron()) {
return path.dirname(process.execPath);
}
return getProjectRoot();
}
function getServiceCommandDefinition() {
if (isElectronRuntime()) {
return {
executable: process.execPath,
arguments: isPackagedElectron() ? ['--service-runner'] : [getProjectRoot(), '--service-runner'],
workingDirectory: getServiceWorkingDirectory()
};
}
return {
executable: process.execPath,
arguments: [path.join(getProjectRoot(), 'index.js')],
workingDirectory: getProjectRoot()
};
}
function buildServiceXml() {
const command = getServiceCommandDefinition();
const argumentLines = command.arguments
.map((argument) => ` <argument>${escapeXml(argument)}</argument>`)
.join('\n');
return [
'<service>',
` <id>${SERVICE_ID}</id>`,
` <name>${SERVICE_NAME}</name>`,
' <description>printServer backend service</description>',
` <executable>${escapeXml(command.executable)}</executable>`,
argumentLines,
' <logmode>rotate</logmode>',
' <startmode>Automatic</startmode>',
' <stoptimeout>30sec</stoptimeout>',
` <workingdirectory>${escapeXml(command.workingDirectory)}</workingdirectory>`,
'</service>',
''
].join('\n');
}
export function ensureServiceDefinition() {
assertWindows();
const wrapperPath = getServiceWrapperPath();
const xmlPath = getServiceXmlPath();
if (!fs.existsSync(wrapperPath)) {
throw new Error(`服务包装器不存在: ${wrapperPath}`);
}
const expectedXml = buildServiceXml();
const currentXml = fs.existsSync(xmlPath) ? fs.readFileSync(xmlPath, 'utf8') : '';
if (currentXml !== expectedXml) {
fs.writeFileSync(xmlPath, expectedXml, 'utf8');
}
return {
name: SERVICE_NAME,
id: SERVICE_ID,
wrapperPath,
xmlPath,
workingDirectory: getServiceWorkingDirectory()
};
}
function isAccessDeniedErrorMessage(message) {
if (!message) {
return false;
}
return /AccessDenied|拒绝访问|\b0x5\b|\berror\s*5\b/i.test(String(message));
}
async function runWrapperCommandElevated(command, metadata) {
const escapedWrapperPath = metadata.wrapperPath.replace(/'/g, "''");
const escapedCommand = String(command).replace(/'/g, "''");
const escapedWorkingDirectory = path.dirname(metadata.wrapperPath).replace(/'/g, "''");
const psCommand = [
"$proc = Start-Process",
`-FilePath '${escapedWrapperPath}'`,
`-ArgumentList '${escapedCommand}'`,
`-WorkingDirectory '${escapedWorkingDirectory}'`,
'-Verb RunAs',
'-WindowStyle Hidden',
'-PassThru',
'-Wait;',
'exit $proc.ExitCode'
].join(' ');
try {
await execFileAsync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', psCommand], {
windowsHide: true
});
} catch (error) {
const stdout = (error.stdout || '').trim();
const stderr = (error.stderr || '').trim();
const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
throw new Error(`提权执行服务命令 ${command} 失败: ${details}`);
}
return {
stdout: '',
stderr: ''
};
}
async function runWrapperCommand(command) {
const metadata = ensureServiceDefinition();
try {
const result = await execFileAsync(metadata.wrapperPath, [command], {
cwd: path.dirname(metadata.wrapperPath),
windowsHide: true
});
return {
stdout: (result.stdout || '').trim(),
stderr: (result.stderr || '').trim()
};
} catch (error) {
const stdout = (error.stdout || '').trim();
const stderr = (error.stderr || '').trim();
const details = [stdout, stderr, error.message].filter(Boolean).join(' | ');
if (command !== 'status' && isAccessDeniedErrorMessage(details)) {
try {
return await runWrapperCommandElevated(command, metadata);
} catch (elevatedError) {
throw new Error(`执行服务命令 ${command} 失败: ${details} | ${elevatedError.message}`);
}
}
throw new Error(`执行服务命令 ${command} 失败: ${details}`);
}
}
function parseServiceStatus(rawStatus) {
const normalized = (rawStatus || '').trim();
if (!normalized || normalized === 'NonExistent') {
return {
installed: false,
running: false,
rawStatus: normalized || 'NonExistent'
};
}
return {
installed: true,
running: /started|running|active/i.test(normalized),
rawStatus: normalized
};
}
export async function getServiceStatus() {
const { stdout } = await runWrapperCommand('status');
return parseServiceStatus(stdout);
}
export async function ensureServiceInstalled() {
const status = await getServiceStatus();
if (status.installed) {
return status;
}
await runWrapperCommand('install');
return getServiceStatus();
}
export async function startService() {
const status = await ensureServiceInstalled();
if (status.running) {
return status;
}
await runWrapperCommand('start');
return getServiceStatus();
}
export async function stopService() {
const status = await getServiceStatus();
if (!status.installed || !status.running) {
return status;
}
await runWrapperCommand('stop');
return getServiceStatus();
}
export async function uninstallService() {
const status = await getServiceStatus();
if (!status.installed) {
return status;
}
if (status.running) {
await runWrapperCommand('stop');
}
await runWrapperCommand('uninstall');
return getServiceStatus();
}

539
views/index.html Normal file
View File

@ -0,0 +1,539 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Print Server</title>
<script>
(function loadExternalDeps() {
function loadScript(candidates) {
return new Promise(function (resolve, reject) {
var idx = 0;
function tryNext() {
if (idx >= candidates.length) {
reject(new Error('All CDN sources failed: ' + candidates.join(', ')));
return;
}
var src = candidates[idx++];
var script = document.createElement('script');
script.src = src;
script.async = false;
script.onload = function () { resolve(src); };
script.onerror = tryNext;
document.head.appendChild(script);
}
tryNext();
});
}
Promise.resolve()
.then(function () {
return loadScript([
'https://cdn.jsdelivr.net/npm/vue@2/dist/vue.min.js',
'https://unpkg.com/vue@2/dist/vue.min.js',
'https://cdn.bootcdn.net/ajax/libs/vue/2.7.16/vue.min.js'
]);
})
.then(function () {
return loadScript([
'https://cdn.jsdelivr.net/npm/qrcodejs2@0.0.2/qrcode.min.js',
'https://unpkg.com/qrcodejs2@0.0.2/qrcode.min.js',
'https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js'
]);
})
.then(function () {
window.__depsReady = true;
window.dispatchEvent(new Event('deps-ready'));
})
.catch(function (err) {
console.error('依赖脚本加载失败:', err);
window.__depsReady = false;
window.dispatchEvent(new Event('deps-failed'));
});
})();
</script>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
background-color: #f4f4f9;
color: #333;
overflow: hidden;
height: 100vh;
}
#app {
display: flex;
flex-direction: column;
max-width: 800px;
margin: 0px auto;
padding: 20px;
background: #fff;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
height: 100%;
box-sizing: border-box;
}
h3,
h2 {
color: #4CAF50;
font-weight: bold;
}
h3 {
font-size: 20px;
}
h2 {
border-bottom: 2px solid #4CAF50;
padding-bottom: 8px;
margin-bottom: 16px;
font-size: 18px;
margin: 0;
}
#qrcode {
width: 256px;
height: 256px;
margin: 0 auto;
flex: 1;
height: 100px;
text-align: center;
}
table {
width: 100%;
margin-top: 16px;
border-collapse: collapse;
text-align: center;
background-color: #f9f9f9;
}
th,
td {
padding: 12px;
border: 1px solid #ddd;
}
th {
background-color: #4CAF50;
color: white;
}
button {
padding: 10px 20px;
margin: 10px 0;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
.error {
color: red;
font-weight: bold;
}
.qrcode-box {
margin-top: 12px;
text-align: center;
display: flex;
flex-direction: column;
height: 100px;
flex: 1;
}
.qrcode-box .error {
margin-top: 10px;
}
img {
width: auto;
height: 100%;
display: inline-block !important;
}
.printers {
display: flex;
gap: 16px;
justify-content: space-between;
}
.header {
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
gap: 20px;
height: 300px;
}
.left,
.right {
width: 50%;
height: 300px;
border: 1px solid;
padding: 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
.printers {
height: 100px;
flex: 1;
}
.list-box {
width: 50%;
border: 1px solid;
padding: 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
.title {
font-size: 16px;
font-weight: bold;
height: 40px;
line-height: 40px;
}
.list {
flex: 1;
margin-top: 12px;
padding: 12px;
background-color: #f9f9f9;
border-radius: 5px;
overflow-y: auto;
}
</style>
</head>
<body>
<div id="app">
<h1 class="title" style="text-align: center;font-size: 30px;font-weight: bold;">天豹云仓打印服务台<template>({{ name
}})</template></h1>
<div class="header">
<div class="left">
<h3>本地服务状态:<span :style="{color: wsStatus[wsClientStatus].color}">{{ wsStatus[wsClientStatus].title
}}</span></h3>
<h3>
服务注册状态:
<span :style="{color: isServices ? 'green' : 'red'}" @click="isServices ? unregister() : register()"
style="cursor: pointer;">
{{ isServices ? '已注册' : '未注册' }}
</span>
</h3>
<h3>服务器连接状态:<span :style="{color: wsStatus[wsServerStatus].color}">{{ wsStatus[wsServerStatus].title
}}</span></h3>
<h3>打印服务绑定状态:<span>
<span :style="{color: isBind ? 'green' : 'red'}">{{ isBind ? '已绑定' : '未绑定' }}</span>
</span></h3>
</div>
<div class="right" v-if="!isBind">
<h2>绑定二维码,微信扫描绑定工作台</h2>
<div class="qrcode-box">
<div id="qrcode" ref="qrcode" style="cursor:pointer;" @click="jumpToAuth"></div>
<div class="error">未绑定打印台,请扫描二维码绑定!</div>
</div>
</div>
</div>
<h2 style="margin-bottom: 20px;margin-top: 10px;">打印组件及打印机</h2>
<div class="printers">
<div class="list-box">
<div class="title">打印机名称
<button @click="loadPrinters"
style="margin-top: 16px; padding: 8px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">刷新打印机状态</button>
</div>
<div class="list">
<div class="item" v-if="printers.length === 0">无打印机</div>
<div class="item" v-for="p in printers" :key="p.name">{{ p.name }}</div>
</div>
</div>
<div class="list-box">
<div class="title">打印组件状态
</div>
<div class="list">
<div class="item" v-if="components.length === 0">无打印组件</div>
<div class="item" v-for="c in components" :key="c.name">{{ c.name }} <i
:style="{color: wsStatus[getStatus(c.name)].color}">{{wsStatus[getStatus(c.name)].title}}</i>
</div>
</div>
</div>
</div>
</div>
<script>
(function initApp() {
if (!window.__depsReady) {
window.addEventListener('deps-ready', initApp, { once: true });
window.addEventListener('deps-failed', function () {
var root = document.getElementById('app');
if (root) {
root.innerHTML = '<h2 style="color:#c62828;">页面依赖加载失败,请检查网络或更换可用 CDN。</h2>';
}
}, { once: true });
return;
}
let ws;
let wsUrl = 'ws://127.0.0.1:3001';
let reconnectTimer = null;
// 全局事件监听器注册表
let wsMethodListeners = {};
// 只定义一次 wsOn
function wsOn(method, callback) {
if (!wsMethodListeners[method]) wsMethodListeners[method] = [];
wsMethodListeners[method].push(callback);
}
function connectWS() {
ws = new WebSocket(wsUrl);
ws.onopen = function () {
console.log('WebSocket 已连接');
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
// Update Vue data for WebSocket status
const app = document.getElementById('app').__vue__;
if (app) app.wsClientStatus = '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秒后重连');
reconnectTimer = setTimeout(connectWS, 3000);
// Update Vue data for WebSocket status
const app = document.getElementById('app').__vue__;
if (app) app.wsClientStatus = 'disconnected';
};
ws.onerror = function (err) {
console.log('WebSocket 错误:', err);
ws.close();
// Update Vue data for WebSocket status
const app = document.getElementById('app').__vue__;
if (app) app.wsClientStatus = 'error';
};
}
connectWS();
// 封装 ws 发送并监听回调
function wsSendWithCallback(method, data, callback) {
if (!ws || ws.readyState !== WebSocket.OPEN) {
// Directly update the status instead of showing an alert
const app = document.getElementById('app').__vue__;
if (app) app.wsClientStatus = 'disconnected';
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({
el: '#app',
data: {
printers: [],
components: [],
statusList: [],
isBind: false,
wsClientStatus: 'disconnected',
wsServerStatus: 'disconnected',
code: '',
qrcode: new QRCode("qrcode"),
wsStatus: {
'disconnected': { title: '未连接', color: 'red' },
'connected': { title: '已连接', color: 'green' },
'error': { title: '连接错误', color: 'red' },
},
isServices: false
},
methods: {
loadComponents() {
wsSendWithCallback('printerComponent.getAll', {}, (data) => {
console.log('获取组件列表:', data);
if (data.success) {
this.components = data.result.components || [];
this.statusList = data.result.status || [];
} else {
alert(data.message || '获取打印组件列表失败!');
}
});
},
getStatus(name) {
const s = this.statusList.find(x => x.name === name);
return s ? s.status : '未知';
},
loadPrinters() {
wsSendWithCallback('printer.getWindowsPrinters', {}, (data) => {
if (data.success) {
this.printers = data.result || [];
if (this.printers.length === 0) {
this.selectedPrinter = '';
} else if (!this.selectedPrinter) {
this.selectedPrinter = this.printers[0].name;
}
} else {
alert(data.message || '获取打印机列表失败!');
}
});
},
register() {
wsSendWithCallback('setting.register', {}, (data) => {
if (data.success) {
this.isServices = !!(data.result && data.result.isServices);
} else {
alert(data.message || '获取绑定状态失败!');
}
});
},
unregister() {
wsSendWithCallback('setting.unregister', {}, (data) => {
if (data.success) {
this.isServices = !!(data.result && data.result.isServices);
} else {
alert(data.message || '获取绑定状态失败!');
}
});
},
refreshBindStatus() {
wsSendWithCallback('setting.info', {}, (data) => {
if (data.success) {
this.isBind = data.result.isBind || false;
this.isServices = data.result.isService || false;
} else {
alert(data.message || '获取绑定状态失败!');
}
});
},
unbind() {
wsSendWithCallback('setting.unbind', {}, (data) => {
if (data.success) {
this.isBind = false;
} else {
alert(data.message || '解绑失败!');
}
});
},
renderQrcode() {
this.$nextTick(() => {
const el = this.$refs.qrcode;
if (!el) return;
// 清空容器,防止多次渲染叠加
el.innerHTML = '';
// 重新生成二维码实例
this.qrcode = new QRCode(el, { width: 256, height: 256 });
if (this.code) {
this.qrcode.makeCode(`http://127.0.0.1:6060/auth/printSetting/${this.code}`);
}
});
},
jumpToAuth() {
if (this.code) {
window.open(`http://127.0.0.1:6060/auth/printSetting/${this.code}`, '_blank');
}
},
installWsListener() {
wsOn('printer.getWindowsPrinters', (data) => {
if (data.success) {
this.printers = data.result || [];
if (this.printers.length === 0) {
this.selectedPrinter = '';
} else if (!this.selectedPrinter) {
this.selectedPrinter = this.printers[0].name;
}
}
});
wsOn('setting.info', (data) => {
if (data.success) {
this.isBind = data.result.isBind || false;
this.name = data.result.name || '';
this.isServices = data.result.isService || false;
}
});
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 || '获取绑定码失败!');
}
});
}
},
watch: {
code(val) {
if (val) {
console.log('新的绑定码:', val);
this.renderQrcode();
}
}
},
mounted() {
setInterval(() => {
this.refreshBindStatus();
}, 10000);
this.installWsListener();
this.refreshBindStatus();
}
});
})();
</script>
</body>
</html>

451
views/index_new.html Normal file
View File

@ -0,0 +1,451 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Print Server</title>
<script>
(function loadExternalDeps() {
function loadScript(candidates) {
return new Promise(function (resolve, reject) {
var idx = 0;
function tryNext() {
if (idx >= candidates.length) {
reject(new Error('All CDN sources failed: ' + candidates.join(', ')));
return;
}
var src = candidates[idx++];
var script = document.createElement('script');
script.src = src;
script.async = false;
script.onload = function () { resolve(src); };
script.onerror = tryNext;
document.head.appendChild(script);
}
tryNext();
});
}
Promise.resolve()
.then(function () {
return loadScript([
'https://cdn.jsdelivr.net/npm/vue@2/dist/vue.min.js',
'https://unpkg.com/vue@2/dist/vue.min.js',
'https://cdn.bootcdn.net/ajax/libs/vue/2.7.16/vue.min.js'
]);
})
.then(function () {
return loadScript([
'https://cdn.jsdelivr.net/npm/qrcodejs2@0.0.2/qrcode.min.js',
'https://unpkg.com/qrcodejs2@0.0.2/qrcode.min.js',
'https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js'
]);
})
.then(function () {
window.__depsReady = true;
window.dispatchEvent(new Event('deps-ready'));
})
.catch(function (err) {
console.error('依赖脚本加载失败:', err);
window.__depsReady = false;
window.dispatchEvent(new Event('deps-failed'));
});
})();
</script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 0;
padding: 0;
min-height: 100vh;
}
#app {
max-width: 1000px;
margin: 40px auto;
background: #fff;
border-radius: 12px;
box-shadow: 0 6px 24px rgba(0,0,0,0.08);
padding: 32px 40px 40px 40px;
display: flex;
flex-direction: column;
gap: 32px;
}
.main-title {
text-align: center;
font-size: 32px;
font-weight: bold;
color: #4CAF50;
margin-bottom: 0;
}
.status-section {
display: flex;
flex-wrap: wrap;
gap: 32px;
justify-content: space-between;
}
.status-box {
flex: 1 1 320px;
min-width: 320px;
background: #f9f9f9;
border-radius: 8px;
padding: 24px 20px 20px 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 18px;
}
.status-box h3 {
margin: 0 0 8px 0;
color: #4CAF50;
font-size: 20px;
font-weight: bold;
}
.status-item {
font-size: 16px;
display: flex;
align-items: center;
gap: 8px;
}
.status-label {
min-width: 120px;
color: #666;
}
.status-value {
font-weight: bold;
}
.qrcode-section {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
min-height: 220px;
}
#qrcode {
width: 180px;
height: 180px;
}
.qrcode-tip {
color: #e53935;
font-size: 15px;
font-weight: bold;
}
.printer-section {
display: flex;
gap: 32px;
flex-wrap: wrap;
}
.list-box {
flex: 1 1 340px;
min-width: 340px;
background: #f9f9f9;
border-radius: 8px;
padding: 20px 18px 18px 18px;
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 10px;
}
.list-title {
font-size: 18px;
font-weight: bold;
color: #4CAF50;
margin-bottom: 8px;
display: flex;
align-items: center;
justify-content: space-between;
}
.list {
background: #fff;
border-radius: 5px;
padding: 10px;
min-height: 60px;
max-height: 180px;
overflow-y: auto;
font-size: 15px;
}
.item {
margin-bottom: 6px;
}
button {
padding: 7px 18px;
background: #4CAF50;
color: #fff;
border: none;
border-radius: 4px;
font-size: 15px;
cursor: pointer;
transition: background 0.2s;
}
button:hover {
background: #388e3c;
}
@media (max-width: 900px) {
#app { padding: 16px; }
.status-section, .printer-section { flex-direction: column; gap: 18px; }
.list-box, .status-box { min-width: unset; }
}
</style>
</head>
<body>
<div id="app">
<div class="main-title">天豹云仓打印服务台<template>({{ name }})</template></div>
<div class="status-section">
<div class="status-box">
<h3>服务状态</h3>
<div class="status-item">
<span class="status-label">本地服务:</span>
<span class="status-value" :style="{color: wsStatus[wsClientStatus].color}">{{ wsStatus[wsClientStatus].title }}</span>
</div>
<div class="status-item">
<span class="status-label">服务注册:</span>
<span class="status-value" :style="{color: isServices ? 'green' : 'red'}" @click="isServices ? unregister() : register()" style="cursor:pointer;">{{ isServices ? '已注册' : '未注册' }}</span>
</div>
<div class="status-item">
<span class="status-label">服务器连接:</span>
<span class="status-value" :style="{color: wsStatus[wsServerStatus].color}">{{ wsStatus[wsServerStatus].title }}</span>
</div>
<div class="status-item">
<span class="status-label">打印服务绑定:</span>
<span class="status-value" :style="{color: isBind ? 'green' : 'red'}">{{ isBind ? '已绑定' : '未绑定' }}</span>
</div>
</div>
<div class="status-box qrcode-section" v-if="!isBind">
<h3>绑定二维码</h3>
<div id="qrcode" ref="qrcode" style="cursor:pointer;" @click="jumpToAuth"></div>
<div class="qrcode-tip">未绑定打印台,请扫描二维码绑定!</div>
</div>
</div>
<div class="printer-section">
<div class="list-box">
<div class="list-title">
打印机名称
<button @click="loadPrinters">刷新打印机状态</button>
</div>
<div class="list">
<div class="item" v-if="printers.length === 0">无打印机</div>
<div class="item" v-for="p in printers" :key="p.name">{{ p.name }}</div>
</div>
</div>
<div class="list-box">
<div class="list-title">打印组件状态</div>
<div class="list">
<div class="item" v-if="components.length === 0">无打印组件</div>
<div class="item" v-for="c in components" :key="c.name">{{ c.name }} <i :style="{color: wsStatus[getStatus(c.name)].color}">{{wsStatus[getStatus(c.name)].title}}</i></div>
</div>
</div>
</div>
</div>
<script>
function initApp() {
if (!window.__depsReady) {
window.addEventListener('deps-ready', initApp, { once: true });
window.addEventListener('deps-failed', function () {
var root = document.getElementById('app');
if (root) {
root.innerHTML = '<h2 style="color:#c62828;">页面依赖加载失败,请检查网络或更换可用 CDN。</h2>';
}
}, { once: true });
return;
}
// ...existing JS 逻辑,直接复制 index.html 的 <script> 内容 ...
let ws;
let wsUrl = 'ws://127.0.0.1:3001';
let reconnectTimer = null;
let wsMethodListeners = {};
function wsOn(method, callback) {
if (!wsMethodListeners[method]) wsMethodListeners[method] = [];
wsMethodListeners[method].push(callback);
}
function connectWS() {
ws = new WebSocket(wsUrl);
ws.onopen = function () {
const app = document.getElementById('app').__vue__;
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
if (app) app.wsClientStatus = '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 () {
reconnectTimer = setTimeout(connectWS, 3000);
const app = document.getElementById('app').__vue__;
if (app) app.wsClientStatus = 'disconnected';
};
ws.onerror = function (err) {
ws.close();
const app = document.getElementById('app').__vue__;
if (app) app.wsClientStatus = 'error';
};
}
connectWS();
function wsSendWithCallback(method, data, callback) {
if (!ws || ws.readyState !== WebSocket.OPEN) {
const app = document.getElementById('app').__vue__;
if (app) app.wsClientStatus = 'disconnected';
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 }));
}
new Vue({
el: '#app',
data: {
printers: [],
components: [],
statusList: [],
isBind: false,
wsClientStatus: 'disconnected',
wsServerStatus: 'disconnected',
code:'',
qrcode:new QRCode("qrcode"),
wsStatus: {
'disconnected': { title: '未连接', color: 'red' },
'connected': { title: '已连接', color: 'green' },
'error': { title: '连接错误', color: 'red' },
},
isServices: false
},
methods: {
loadComponents() {
wsSendWithCallback('printerComponent.getAll', {}, (data) => {
if (data.success) {
this.components = data.result.components || [];
this.statusList = data.result.status || [];
}
});
},
getStatus(name) {
const s = this.statusList.find(x => x.name === name);
return s ? s.status : '未知';
},
loadPrinters() {
wsSendWithCallback('printer.getWindowsPrinters', {}, (data) => {
if (data.success) {
this.printers = data.result || [];
if (this.printers.length === 0) {
this.selectedPrinter = '';
} else if (!this.selectedPrinter) {
this.selectedPrinter = this.printers[0].name;
}
}
});
},
register() {
wsSendWithCallback('setting.register', {}, (data) => {
if (data.success) {
this.isServices = data.result || '';
}
});
},
unregister() {
wsSendWithCallback('setting.unregister', {}, (data) => {
if (data.success) {
this.isServices = data.result || '';
}
});
},
isBind() {
wsSendWithCallback('setting.info', {}, (data) => {
if (data.success) {
this.isBind = data.result.isBind || false;
}
});
},
unbind() {
wsSendWithCallback('setting.unbind', {}, (data) => {
if (data.success) {
this.isBind = false;
}
});
},
renderQrcode() {
this.$nextTick(() => {
const el = this.$refs.qrcode;
if (!el) return;
el.innerHTML = '';
this.qrcode = new QRCode(el, { width: 180, height: 180 });
if (this.code) {
this.qrcode.makeCode(`http://127.0.0.1:6060/auth/printSetting/${this.code}`);
}
});
},
jumpToAuth() {
if (this.code) {
window.open(`http://127.0.0.1:6060/auth/printSetting/${this.code}`, '_blank');
}
},
installWsListener() {
wsOn('printer.getWindowsPrinters', (data) => {
if (data.success) {
this.printers = data.result || [];
if (this.printers.length === 0) {
this.selectedPrinter = '';
} else if (!this.selectedPrinter) {
this.selectedPrinter = this.printers[0].name;
}
}
});
wsOn('setting.info', (data) => {
if (data.success) {
this.isBind = data.result.isBind || false;
this.name = data.result.name || '';
}
});
wsOn('printerComponent.getAll', (data) => {
if (data.success) {
this.components = data.result.components || [];
this.statusList = data.result.status || [];
}
});
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 }];
}
});
wsOn('wsClient.statusChange', (data) => {
if (data.success) {
this.wsServerStatus = data.result.status;
}
});
wsOn('bind.generateCode', (data) => {
if (data.success) {
this.code = data.result || '';
}
});
}
},
watch: {
code(val) {
if (val) {
this.renderQrcode();
}
}
},
mounted() {
setInterval(() => {
this.isBind();
}, 10000);
this.installWsListener();
}
});
}
initApp();
</script>
</body>
</html>

View File

@ -0,0 +1,21 @@
开发时间:2026-03-24
任务描述:实现前端网页通过 WebSocket 调用 setting.register 与 setting.unregister,并完成回归测试。
修改内容:
- 调整 services/setting.js,仅保留可供 WebSocket 直接调用的 info、unbind、register、unregister 方法,并补齐上下文绑定。
- register 改为通过 WebSocket 调用后写入 isService 状态,并尝试以 detached 方式拉起外部 node 进程,提升进程存活能力。
- 增强 core/wsServer.js 的错误回传信息,便于定位服务装载与 method 路由问题。
回归结果:
- 通过任务方式启动当前实例后,setting 服务成功装载。
- WebSocket 测试结果:
- setting.register 返回 success=true,result.ok=true。
- setting.unregister 返回 success=true,result.ok=true。
- 前端页面依赖的 method 路由方式已验证可用,调用链为 ws message -> method split -> services.setting.register/unregister。
涉及文件:
- services/setting.js
- core/wsServer.js
备注:
- 调试过程中发现共享终端存在历史输出串扰,最终采用 VS Code task 方式启动服务并完成回归。

View File

@ -0,0 +1,62 @@
# 2026-03-25 安装后服务验证
## 验证目标
- 验证安装后的应用点击“注册服务/注销服务”是否会创建或移除真正的 Windows Service。
- 验证关闭窗口后应用是否以系统服务形式继续运行。
## 验证步骤
- 使用 dist/printServer-1.0.0-setup.exe 静默安装到 临时/installed-app。
- 启动安装后的 printServer.exe。
- 通过本地 WebSocket 依次调用 setting.info、setting.register、setting.info、setting.unregister、setting.info。
- 使用 Get-Service 和 sc.exe query PrintServer 查询系统服务状态。
- 通过 CloseMainWindow 模拟点击主窗口关闭按钮。
- 再次检查进程、端口和系统服务状态。
## 验证结果
- 安装后的程序可以正常启动并监听 3000、3001。
- setting.register 返回成功,随后 setting.info 返回 isService=true。
- setting.unregister 返回成功,最终 setting.info 返回 isService=false。
- Get-Service 未发现 PrintServer 服务。
- sc.exe query PrintServer 返回:指定的服务未安装。
- 主窗口关闭后,printServer 进程仍继续存活,3000/3001 继续监听。
- 主窗口关闭后系统服务列表仍不存在 PrintServer。
## 结论
- 当前“注册服务/注销服务”只是在应用配置层切换 isService 标记,没有接入真正的 Windows Service 安装和卸载。
- 当前“关闭窗口后继续运行”属于 Electron 托盘常驻行为,不属于系统服务运行。
## 后续建议
- 如果需求是进入 Windows 服务列表并可被服务管理器控制,需要新增真正的服务安装/卸载实现,并明确管理员权限、服务脚本入口和安装时机。
## 2026-03-26 共享配置路径修复后复测
### 修复内容
- 打包态配置写入路径由用户 APPDATA 调整为 ProgramData/printServer/config.json,桌面壳与 Windows Service 共用同一份配置。
- 保留旧用户 APPDATA 配置迁移逻辑,避免升级后直接丢失既有业务配置。
### 复测前处理
- 清理残留 PrintServer 服务与历史打包态进程。
- 显式初始化 ProgramData/printServer/config.json,并将 isService 置为 false,确保从非服务模式开始验证。
### 复测步骤
- 重新执行 npm run package:app 生成最新 win-unpacked。
- 以管理员权限启动 dist/win-unpacked/printServer.exe。
- 通过本地 WebSocket 调用 setting.register。
- 使用 Get-Service 与 daemon/printserver.exe status 验证服务注入结果。
- 再次通过本地 WebSocket 调用 setting.unregister。
- 再次检查共享配置、系统服务状态与端口监听状态。
### 复测结果
- ProgramData/printServer/config.json 在启动后被正确读取并维护,初始 isService=false。
- setting.register 返回成功,随后共享配置中的 isService=true。
- Get-Service 显示 PrintServer 已进入 Running。
- daemon/printserver.exe status 返回 Started。
- setting.unregister 返回成功,随后共享配置中的 isService=false。
- 等待桌面壳状态同步后,Get-Service 不再返回 PrintServer。
- daemon/printserver.exe status 返回 NonExistent。
- 注销完成后 3000/3001 仍可继续监听,说明运行态已切回桌面壳托管的本地后端。
### 更新结论
- 共享配置路径不一致是此前“注销服务只改状态、不卸载真实系统服务”的根因。
- 修复为 ProgramData 共享配置后,注册服务与注销服务两条链路均已闭环。
- 注册与注销系统服务仍依赖管理员权限;若未提升权限,服务注入会失败并返回 AccessDenied。

View File

@ -0,0 +1,29 @@
# 2026-03-25 打包安装包与运行态回归
## 任务目标
- 完成 Windows 安装包产出。
- 验证打包后的 Electron 应用是否能真实启动本地 HTTP/WS 服务。
- 验证页面注册服务链路在打包态是否可用。
## 本次完成内容
- 确认 dist/win-unpacked/resources 已包含 config.json、printer.ps1、daemon/。
- 确认 dist/printServer-1.0.0-setup.exe 已生成。
- 使用打包后的 printServer.exe 启动运行态,确认可拉起本地 3000 和 3001。
- 验证 APPDATA/printServer/config.json 在初始为空对象时可自动补齐默认配置。
- 验证 http://127.0.0.1:3000/ 可正常返回首页内容。
- 验证本地 WebSocket 接口 setting.info、setting.register、setting.unregister 在打包态可正常响应。
## 验证结果
- 安装包产物存在:dist/printServer-1.0.0-setup.exe。
- 解包版产物存在:dist/win-unpacked/printServer.exe。
- 打包态首页请求返回 200。
- 打包态页面包含 Vue 初始化代码、本地 WS 地址和 setting.register 调用链路。
- WebSocket 回归结果:
- setting.info 返回 isBind=true、isService=false。
- setting.register 返回成功,isServices=true。
- 再次查询 setting.info,isService=true。
- setting.unregister 返回成功,最终 setting.info 返回 isService=false。
## 备注
- 本轮验证结束后已关闭验证过程中启动的 printServer 后台实例,3000/3001 已释放。
- 托盘图标、桌面快捷方式和窗口显示属于 GUI 视觉项,当前已从代码和进程层确认 Electron 主进程正常拉起,安装后可再做一次人工点检。

View File

@ -0,0 +1,46 @@
运行双态与系统服务归档
状态:已完成(2026-03-28 归档)
目标:明确区分“桌面壳自管后端”和“系统服务托管后端”两种运行状态,保证打包安装后启动路径可预期、无重复实例、无端口争抢。
一、目标状态
- 状态 A:未注册系统服务
- 桌面应用启动后,如果本地后端和系统服务都未运行,则由桌面壳拉起本地后端。
- 桌面应用关闭为托盘常驻时,本地后端继续由桌面壳维持。
- 桌面应用完全退出时,本地后端一并退出。
- 状态 B:已注册系统服务
- 后端由 Windows 系统服务启动与托管。
- 桌面应用启动时不再直接拉起本地后端,而是检查并拉起系统服务。
- 桌面应用只负责界面、托盘和状态编排,不再持有后端生命周期。
二、实现要求
- Electron 主进程只保留一个编排入口,避免进程内直接 import 后端导致无法切换运行态。
- 后端需要支持 headless 启动参数,供本地子进程模式和系统服务模式共用。
- 系统服务统一复用 daemon/ 下的 WinSW 包装器,不再保留“只改 isService 配置但不落地系统服务”的伪状态。
- 服务配置文件必须在运行时按实际安装路径重写,不能写死开发机路径。
- 状态切换时避免 3000 和 3001 被两个后端实例同时占用。
三、完成状态
- 已完成:2026-03-28 已完成“关窗托盘 -> 托盘退出 -> 再次启动”整条链路人工复测,确认没有重复监听或端口争抢。
四、风险点
- 系统服务安装和卸载通常需要管理员权限,需要明确失败提示。
- 服务从本地子进程模式切到系统服务模式时,存在短暂重连窗口,需要前端可接受本地 WS 断开重连。
- 如果用户直接修改配置文件而未完成服务安装,桌面壳需要有回退策略,避免界面不可用。
五、当前核对结论
- 已完成:Electron 主进程单编排入口、headless 启动参数、WinSW 统一服务包装、运行时重写 daemon XML 路径。
- 已完成:未注册服务时,打包态启动 printServer.exe 可以拉起本地 3000/3001。
- 已完成:注册服务后可真实安装 Windows Service,注销后可真实移除,并能切回桌面壳托管本地后端。
- 已完成:ProgramData 配置目录与 daemon XML 路径已统一到打包态可用路径。
- 已完成:单实例锁、托盘常驻与退出时回收本地后端的代码路径已经落地。
六、对应记录
- 开发日志/2026-03-25_安装后服务验证.md
- 开发日志/2026-03-25_打包安装包与运行态回归.md
七、关闭说明
- 本 TODO 对应目标已全部达成,可视为完成并归档。
创建时间:2026-03-25

45
评测报告.md Normal file
View File

@ -0,0 +1,45 @@
# printServer 稳定性与迁移评测报告
## 一、评测环境
- 操作系统:Windows
- Node.js 版本:22.12.0
- 依赖环境:PowerShell、无 wmic 依赖
## 二、稳定性评测
### 1. 打印机查询与状态监控
- 已完全采用 PowerShell + Get-CimInstance Win32_Printer 查询打印机,兼容新旧 Windows 环境。
- printer.ps1 实现打印机状态轮询,支持多打印机并发监控,状态变更事件实时推送。
- 日志与异常处理健全,能捕获并输出错误信息。
### 2. WebSocket 服务
- wsServer 支持本地与远程 WebSocket 通信。
- 日志显示端口 3001 多次被占用(EADDRINUSE),需确保端口唯一性,避免多实例冲突。
### 3. 错误与异常
- 日志中有详细的错误捕获与输出,便于定位问题。
- 远程 WebSocket 存在 502 返回,但不影响本地功能。
## 三、迁移到纯 Windows 客户端评测
### 1. 依赖分析
- 已无 wmic、winax 等跨平台依赖,全部核心功能基于 PowerShell 与 Node.js。
- 仅需保证 PowerShell 可用。
- 适合打包为 Windows 独立客户端,无需额外环境配置。
### 2. 兼容性与适配
- 适配 Windows 10/11,理论支持所有带 PowerShell 的 Windows。
- 打印机、COM 组件、WebSocket 均为本地实现,无平台兼容障碍。
### 3. 潜在风险
- 端口占用(3001)需在客户端唯一分配。
- PowerShell 执行策略需允许脚本运行(Bypass)。
## 四、结论与建议
- 项目已高度适配 Windows 客户端,稳定性良好。
- 建议:
1. 客户端启动时检测端口占用,自动切换空闲端口。
2. 增加 PowerShell 执行策略检测与提示。
3. 日志与错误输出建议写入本地文件,便于用户反馈。
---
评测日期:2026-03-24
评测人:GitHub Copilot