From 5bc0e6637e7f08de59c711778062533a1e6620cb Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 29 Mar 2026 19:32:28 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E5=AE=8C=E5=96=84README=E5=B9=B6?= =?UTF-8?q?=E6=94=B6=E6=95=9B=E6=9B=B4=E6=96=B0=E5=8F=91=E5=B8=83=E6=B5=81?= =?UTF-8?q?=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + README.md | 45 +- build.ps1 | 290 ++++- config.json | 4 +- config.packaged.json | 4 + controllers/index.js | 27 - controllers/printer.js | 27 - controllers/test/index.js | 0 core/BaseController.js | 11 - core/main.js | 179 ++- core/wsServer.js | 57 +- electron/assets/printserver-icon-256.png | Bin 0 -> 6252 bytes electron/assets/printserver.ico | Bin 0 -> 15595 bytes electron/generate-icon.ps1 | 139 +++ electron/main.cjs | 75 +- electron/nsis-shortcuts.nsh | 9 + index.js | 13 +- package.json | 38 +- routes.js | 6 - scripts/deploy-linux.ps1 | 142 +++ scripts/deploy.config.json | 9 + scripts/deploy.config.local.example.json | 9 + services/setting.js | 117 +- services/update.js | 544 +++++++++ utils/runtime.js | 5 +- utils/windowsService.js | 47 +- views/index.html | 1067 +++++++++++++---- 开发日志/2026-03-29_HTTP迁出与静态页面说明.md | 32 + 评测报告.md | 45 - 降低被杀软误报.todo | 34 +- 30 files changed, 2419 insertions(+), 558 deletions(-) delete mode 100644 controllers/index.js delete mode 100644 controllers/printer.js delete mode 100644 controllers/test/index.js delete mode 100644 core/BaseController.js create mode 100644 electron/assets/printserver-icon-256.png create mode 100644 electron/assets/printserver.ico create mode 100644 electron/generate-icon.ps1 create mode 100644 electron/nsis-shortcuts.nsh delete mode 100644 routes.js create mode 100644 scripts/deploy-linux.ps1 create mode 100644 scripts/deploy.config.json create mode 100644 scripts/deploy.config.local.example.json create mode 100644 services/update.js create mode 100644 开发日志/2026-03-29_HTTP迁出与静态页面说明.md delete mode 100644 评测报告.md diff --git a/.gitignore b/.gitignore index 72e4823..8b847ee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ node_modules/ dist/ +versioning/ coverage/ +scripts/deploy.config.local.json 临时/ 涓存椂/ diff --git a/README.md b/README.md index 83d51c6..7327366 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,8 @@ printServer 是一个面向 Windows 的本地打印服务应用。 它当前由以下几部分组成: -- Node.js HTTP 服务,监听本地 3000 端口 - 本地 WebSocket 服务,监听 3001 端口 -- 前端页面 views/index.html,用于绑定工作台、查看打印机、查看组件状态、执行注册服务等操作 +- 前端页面 views/index.html(由 Electron 直接静态加载),用于绑定工作台、查看打印机、查看组件状态、执行注册服务等操作 - Windows PowerShell 脚本,用于打印机状态轮询 - 打印组件与远程 WebSocket 通信逻辑,用于接收远端指令并驱动本地打印 - Electron 桌面壳,用于后续安装包、托盘图标和桌面启动能力 @@ -23,14 +22,11 @@ printServer 是一个面向 Windows 的本地打印服务应用。 - 入口文件:index.js - 核心框架:core/ - 服务层:services/ -- 控制器:controllers/ - 页面:views/ - Windows 脚本:printer.ps1 - 配置文件:config.json ## 目录说明 -- controllers/ - - HTTP 控制器 - core/ - 主应用、WebSocket 服务、WebSocket 客户端、打印组件核心逻辑 - services/ @@ -60,11 +56,11 @@ npm run dev ``` 打开页面: -- http://127.0.0.1:3000/ +- 由 Electron 主窗口直接加载 views/index.html ## 页面与服务调用关系 页面通过浏览器连接本地 WebSocket 服务: -- 页面地址由本地 HTTP 服务提供 +- 页面由 Electron 静态加载 - 页面中的按钮通过 wsSendWithCallback 发送 method - WebSocket 服务按 method 路由到 services/ 下对应实例方法 @@ -94,8 +90,41 @@ npm run dev - 能打开页面并完成注册到服务 - 打包时纳入配置文件、页面资源、PowerShell 脚本与相关依赖 +## 发布版本规则 +- 打包前会校验 `package.json` 的 `version` 是否已有安装包产物。 +- 若当前版本在 `dist/` 或 `versioning/releases//` 已存在产物,将直接阻止打包。 +- 需要手动更新版本号后再执行打包。 + +## 更新下发产物 +- 每次成功打包会自动归档安装包到 `versioning/releases//`。 +- 同步生成 `versioning/update-feed.json`,包含 `latest` 与历史 `releases` 元数据(版本、文件路径、SHA256、构建时间)。 +- 服务器可直接读取该清单实现后续版本更新下发。 + +## 应用内更新 +- 页面提供“检查更新”和“应用内下载并安装”能力。 +- 更新流程:检查版本 -> 下载更新包(进度条展示)-> 启动安装向导。 +- 下载进度通过 WebSocket 事件 `update.downloadProgress` 实时推送到前端。 +- 若安装向导未正常弹出,可使用“再次打开安装包”按钮重试。 + +## Linux 服务器发布 +- 默认发布命令:`npm run release:linux` +- 本地私有配置发布命令:`npm run release:linux:local` +- 默认配置文件:`scripts/deploy.config.json` +- 本地覆盖配置:`scripts/deploy.config.local.json`(已默认 git 忽略) +- 发布脚本会自动执行: + - 选择最新安装包(默认 `dist/printServer-*-setup.exe`) + - 上传到 Linux 目录 + - 自动清理远端历史版本(保留 `keepReleases` 个) + - 写入远端 `latest.json`(version/file/url/sha256/publishedAtUtc) +- 线上链接格式:`https://wms.wms.gztbyc.com/printServer/.exe` + +## 打包排障 +- 若 `electron-builder` 报 `Unexpected token ... package.json is not valid JSON`,请检查 `package.json` 是否存在 UTF-8 BOM。 +- 可执行一次 BOM 清理:`node -e "const fs=require('fs');const p='package.json';const s=fs.readFileSync(p,'utf8').replace(/^\uFEFF/,'');JSON.parse(s);fs.writeFileSync(p,s,'utf8');"` +- 临时测试需要跳过版本产物校验时,可设置环境变量:`PRINTSERVER_SKIP_VERSION_CHECK=1`(仅建议测试场景使用)。 + ## 注意事项 - 当前项目包含明显的 Windows 依赖 - dm 相关能力已从本项目移除,不再属于当前交付范围 -- 3000 和 3001 端口需避免被占用 +- 3001 端口需避免被占用(3000 端口当前不再承载页面服务) - 临时测试与分析文件统一放在 临时/ 目录 diff --git a/build.ps1 b/build.ps1 index b071358..fbee9c2 100644 --- a/build.ps1 +++ b/build.ps1 @@ -8,6 +8,9 @@ $ErrorActionPreference = 'Stop' $root = Split-Path -Parent $MyInvocation.MyCommand.Path $tempRootName = [string]([char]0x4E34) + [char]0x65F6 $tempPackagingDir = Join-Path (Join-Path $root $tempRootName) 'packaging' +$versioningDir = Join-Path $root 'versioning' +$releaseStoreDir = Join-Path $versioningDir 'releases' +$releaseFeedPath = Join-Path $versioningDir 'update-feed.json' $timestamp = Get-Date -Format 'yyyyMMdd-HHmmss' $logPath = Join-Path $tempPackagingDir ("build-$timestamp.log") @@ -48,6 +51,262 @@ function Invoke-Builder([string[]]$Args) { } } +function Get-PackageVersion { + $manifest = Get-Content (Join-Path $root 'package.json') -Raw | ConvertFrom-Json + $version = [string]$manifest.version + if ([string]::IsNullOrWhiteSpace($version)) { + throw 'package.json version is empty' + } + + return $version +} + +function Get-InstallerFileName([string]$Version) { + return "printServer-$Version-setup.exe" +} + +function Assert-VersionArtifactNotExists { + if ($env:PRINTSERVER_SKIP_VERSION_CHECK -eq '1') { + Write-Log 'VERSION CHECK skipped by PRINTSERVER_SKIP_VERSION_CHECK=1' + return + } + + $version = Get-PackageVersion + $installerFile = Get-InstallerFileName -Version $version + $distInstallerPath = Join-Path (Join-Path $root 'dist') $installerFile + $archivedInstallerPath = Join-Path (Join-Path $releaseStoreDir $version) $installerFile + + if (Test-Path $distInstallerPath) { + throw "version $version already has installer in dist: $distInstallerPath ; bump package.json version before packaging" + } + + if (Test-Path $archivedInstallerPath) { + throw "version $version already archived: $archivedInstallerPath ; bump package.json version before packaging" + } + + if (Test-Path $releaseFeedPath) { + try { + $feed = Get-Content $releaseFeedPath -Raw | ConvertFrom-Json + if ($feed -and $feed.releases) { + foreach ($release in $feed.releases) { + if ([string]$release.version -eq $version) { + throw "version $version already exists in release feed: $releaseFeedPath ; bump package.json version before packaging" + } + } + } + } catch { + throw "release feed validation failed: $($_.Exception.Message)" + } + } + + Write-Log "VERSION CHECK passed for $version" +} + +function Get-SignOptions { + $enabled = ($env:PRINTSERVER_SIGN_ENABLE -eq '1') + $timestampEnv = $env:SIGN_TIMESTAMP_URL + $timestampUrl = 'http://timestamp.digicert.com' + + if (-not [string]::IsNullOrWhiteSpace($timestampEnv)) { + if ($timestampEnv -match '^(none|off|disable)$') { + $timestampUrl = '' + } else { + $timestampUrl = $timestampEnv + } + } + + return [PSCustomObject]@{ + Enabled = $enabled + SignToolPath = if ([string]::IsNullOrWhiteSpace($env:SIGNTOOL_PATH)) { 'signtool.exe' } else { $env:SIGNTOOL_PATH } + CertFile = $env:SIGN_CERT_FILE + CertPassword = $env:SIGN_CERT_PASSWORD + CertThumbprint = $env:SIGN_CERT_THUMBPRINT + TimestampUrl = $timestampUrl + } +} + +function Write-ArtifactHash([string]$ArtifactPath) { + if (-not (Test-Path $ArtifactPath)) { + return + } + + $hash = (Get-FileHash -Path $ArtifactPath -Algorithm SHA256).Hash + Write-Log ("HASH " + $ArtifactPath + " SHA256=" + $hash) +} + +function Invoke-SignFile([string]$TargetPath, [string]$Label) { + if (-not (Test-Path $TargetPath)) { + Write-Log ("SIGN SKIP " + $Label + " missing: " + $TargetPath) + return + } + + $signOptions = Get-SignOptions + if (-not $signOptions.Enabled) { + Write-Log ("SIGN SKIP " + $Label + " disabled (set PRINTSERVER_SIGN_ENABLE=1 to enable)") + Write-ArtifactHash $TargetPath + return + } + + $signtoolArgs = @('sign', '/fd', 'SHA256') + if (-not [string]::IsNullOrWhiteSpace($signOptions.TimestampUrl)) { + $signtoolArgs += @('/td', 'SHA256', '/tr', $signOptions.TimestampUrl) + } + + if (-not [string]::IsNullOrWhiteSpace($signOptions.CertFile)) { + $signtoolArgs += @('/f', $signOptions.CertFile) + if (-not [string]::IsNullOrWhiteSpace($signOptions.CertPassword)) { + $signtoolArgs += @('/p', $signOptions.CertPassword) + } + } elseif (-not [string]::IsNullOrWhiteSpace($signOptions.CertThumbprint)) { + $signtoolArgs += @('/sha1', $signOptions.CertThumbprint) + } else { + throw 'signing enabled but no certificate provided (SIGN_CERT_FILE or SIGN_CERT_THUMBPRINT)' + } + + $signtoolArgs += @($TargetPath) + + $signtoolReady = $false + if ($signOptions.SignToolPath -eq 'signtool.exe') { + $signtoolReady = [bool](Get-Command 'signtool.exe' -ErrorAction SilentlyContinue) + } else { + $signtoolReady = Test-Path $signOptions.SignToolPath + } + + if ($signtoolReady) { + & $signOptions.SignToolPath @signtoolArgs + if ($LASTEXITCODE -ne 0) { + throw "signing failed for $Label with exit code $LASTEXITCODE" + } + } else { + $cert = $null + if (-not [string]::IsNullOrWhiteSpace($signOptions.CertFile)) { + $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($signOptions.CertFile, $signOptions.CertPassword) + } elseif (-not [string]::IsNullOrWhiteSpace($signOptions.CertThumbprint)) { + $cert = Get-ChildItem -Path (Join-Path 'Cert:\CurrentUser\My' $signOptions.CertThumbprint) -ErrorAction SilentlyContinue + } + + if (-not $cert) { + throw "signing failed for $Label because certificate is unavailable" + } + + if (-not [string]::IsNullOrWhiteSpace($signOptions.TimestampUrl)) { + $result = Set-AuthenticodeSignature -FilePath $TargetPath -Certificate $cert -TimestampServer $signOptions.TimestampUrl -HashAlgorithm SHA256 + } else { + $result = Set-AuthenticodeSignature -FilePath $TargetPath -Certificate $cert -HashAlgorithm SHA256 + } + + $acceptedStatuses = @('Valid', 'UnknownError') + if ($acceptedStatuses -notcontains [string]$result.Status) { + throw "signing failed for $Label with status $($result.Status)" + } + + Write-Log ("SIGN FALLBACK Set-AuthenticodeSignature used for " + $Label + " status=" + $result.Status) + } + + Write-Log ("SIGN OK " + $Label + " => " + $TargetPath) + Write-ArtifactHash $TargetPath +} + +function Sign-AppArtifacts { + $appExePath = Join-Path $root 'dist\win-unpacked\printServer.exe' + $serviceWrapperPath = Join-Path $root 'dist\win-unpacked\resources\daemon\printserver.exe' + + Invoke-SignFile -TargetPath $appExePath -Label 'app executable' + Invoke-SignFile -TargetPath $serviceWrapperPath -Label 'service wrapper' +} + +function Sign-InstallerArtifacts { + $installer = Get-ChildItem -Path (Join-Path $root 'dist') -Filter 'printServer-*-setup.exe' -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | + Select-Object -First 1 + + if ($installer) { + Invoke-SignFile -TargetPath $installer.FullName -Label 'nsis installer' + return + } + + Write-Log 'SIGN SKIP nsis installer missing in dist/' +} + +function Update-ReleaseFeed { + $version = Get-PackageVersion + $installerFile = Get-InstallerFileName -Version $version + $installerPath = Join-Path (Join-Path $root 'dist') $installerFile + + if (-not (Test-Path $installerPath)) { + throw "installer missing for release feed: $installerPath" + } + + $releaseDir = Join-Path $releaseStoreDir $version + Ensure-Dir $releaseDir + + $archivedInstallerPath = Join-Path $releaseDir $installerFile + Copy-Item -Path $installerPath -Destination $archivedInstallerPath -Force + + $blockmapFile = "$installerFile.blockmap" + $blockmapPath = Join-Path (Join-Path $root 'dist') $blockmapFile + $archivedBlockmapPath = Join-Path $releaseDir $blockmapFile + if (Test-Path $blockmapPath) { + Copy-Item -Path $blockmapPath -Destination $archivedBlockmapPath -Force + } + + $releaseHash = (Get-FileHash -Path $archivedInstallerPath -Algorithm SHA256).Hash + $releaseSize = (Get-Item $archivedInstallerPath).Length + $builtAtUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + + $releaseEntry = [PSCustomObject]@{ + version = $version + installer = "releases/$version/$installerFile" + blockmap = if (Test-Path $archivedBlockmapPath) { "releases/$version/$blockmapFile" } else { $null } + sha256 = $releaseHash + size = $releaseSize + builtAtUtc = $builtAtUtc + } + + $existingEntries = @() + if (Test-Path $releaseFeedPath) { + try { + $existingFeed = Get-Content $releaseFeedPath -Raw | ConvertFrom-Json + if ($existingFeed -and $existingFeed.releases) { + foreach ($item in $existingFeed.releases) { + if ([string]$item.version -ne $version) { + $existingEntries += [PSCustomObject]@{ + version = [string]$item.version + installer = [string]$item.installer + blockmap = if ($null -eq $item.blockmap) { $null } else { [string]$item.blockmap } + sha256 = [string]$item.sha256 + size = [int64]$item.size + builtAtUtc = [string]$item.builtAtUtc + } + } + } + } + } catch { + throw "release feed parse failed: $($_.Exception.Message)" + } + } + + $allEntries = @($releaseEntry) + $existingEntries + $allEntries = $allEntries | Sort-Object builtAtUtc -Descending + + $feed = [PSCustomObject]@{ + app = 'printserver' + channel = 'stable' + latest = $version + generatedAtUtc = $builtAtUtc + releases = $allEntries + } + + Ensure-Dir $versioningDir + $feed | ConvertTo-Json -Depth 6 | Set-Content -Path $releaseFeedPath -Encoding UTF8 + + Write-Log "RELEASE ARCHIVE $archivedInstallerPath" + if (Test-Path $archivedBlockmapPath) { + Write-Log "RELEASE ARCHIVE $archivedBlockmapPath" + } + Write-Log "RELEASE FEED $releaseFeedPath latest=$version sha256=$releaseHash" +} + function Ensure-AppExecutable() { $appOutDir = Join-Path $root 'dist\win-unpacked' $targetExe = Join-Path $appOutDir 'printServer.exe' @@ -89,6 +348,12 @@ function Ensure-PackagedResources() { } } + $iconSourcePath = Join-Path $root 'electron\assets\printserver.ico' + $iconTargetPath = Join-Path $resourcesDir 'printserver.ico' + if (Test-Path $iconSourcePath) { + Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force + } + foreach ($dirName in @('daemon')) { $sourcePath = Join-Path $root $dirName $targetPath = Join-Path $resourcesDir $dirName @@ -160,6 +425,7 @@ function App-Stage { if ($builderFailed -and (Ensure-AppExecutable)) { Ensure-PackagedResources + Sign-AppArtifacts Write-Log 'APP stage fallback completed with unpacked executable workaround' return } @@ -169,37 +435,25 @@ function App-Stage { } Ensure-PackagedResources + Sign-AppArtifacts 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' + Sign-InstallerArtifacts + Update-ReleaseFeed } catch { - Write-Log ("WARN NSIS installer unavailable: " + $_.Exception.Message) - } - - if (-not $nsisBuilt) { - Invoke-OfflineInstaller - Write-Log 'OFFLINE installer build completed with IExpress fallback' + Write-Log ("ERROR NSIS installer unavailable: " + $_.Exception.Message) + throw 'NSIS installer build failed; offline IExpress fallback has been disabled by policy' } } @@ -215,10 +469,12 @@ switch ($Stage) { Invoke-Step 'app' { App-Stage } } 'win' { + Invoke-Step 'version-check' { Assert-VersionArtifactNotExists } Invoke-Step 'prepare' { Prepare-Stage } Invoke-Step 'win' { Win-Stage } } 'package' { + Invoke-Step 'version-check' { Assert-VersionArtifactNotExists } Invoke-Step 'clean' { Clean-Stage } Invoke-Step 'prepare' { Prepare-Stage } Invoke-Step 'win' { Win-Stage } diff --git a/config.json b/config.json index cc2bd31..f4b8918 100644 --- a/config.json +++ b/config.json @@ -10,7 +10,7 @@ "reconnectInterval": 3000 }, "refreshTokenExpireTime": 0, - "tokenExpireTime": 1774710196708, - "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2RlIjoiNzExYzJjIiwicHJpbnRlciI6Iua1i-ivleaJk-WNsOWPsCIsIndhcmVob3VzZSI6IjEwMDAwMjgiLCJjb21wdXRlcklkIjoxLCJpYXQiOjE3NzQ3MDY1OTYsImV4cCI6MTc3NDcxMDE5Nn0.VCkG5bFJGvvvkT_CwuWwfsIE_JsMCF_Zcp2FWOsy1hg", + "tokenExpireTime": 1774784976938, + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2RlIjoiNzExYzJjIiwicHJpbnRlciI6Iua1i-ivleaJk-WNsOWPsCIsIndhcmVob3VzZSI6IjEwMDAwMjgiLCJjb21wdXRlcklkIjoxLCJpYXQiOjE3NzQ3ODEzNzYsImV4cCI6MTc3NDc4NDk3Nn0.qJ_DW2YyOZu9BoTCcXEDUbXYMCosa6TK48tNlA8g-lo", "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2RlIjoiNzExYzJjIiwicHJpbnRlciI6Iua1i-ivleaJk-WNsOWPsCIsIndhcmVob3VzZSI6IjEwMDAwMjgiLCJjb21wdXRlcklkIjoxLCJpYXQiOjE3NzI5Nzk2OTIsImV4cCI6NDkyODczOTY5Mn0.1qxGUf1IDco2F2Vfsg-t9mv0s14gtIz56tXvHjIX7ls" } \ No newline at end of file diff --git a/config.packaged.json b/config.packaged.json index c90606f..dc0585e 100644 --- a/config.packaged.json +++ b/config.packaged.json @@ -9,6 +9,10 @@ "url": "ws://printer.wms.gztbyc.com/ws", "reconnectInterval": 3000 }, + "update": { + "feedUrl": "https://dl.wms.gztbyc.com/printServer/latest.json", + "downloadBaseUrl": "https://dl.wms.gztbyc.com/printServer" + }, "refreshTokenExpireTime": 0, "name": "", "tokenExpireTime": 0, diff --git a/controllers/index.js b/controllers/index.js deleted file mode 100644 index eda4921..0000000 --- a/controllers/index.js +++ /dev/null @@ -1,27 +0,0 @@ -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(); diff --git a/controllers/printer.js b/controllers/printer.js deleted file mode 100644 index 1fa3873..0000000 --- a/controllers/printer.js +++ /dev/null @@ -1,27 +0,0 @@ -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; diff --git a/controllers/test/index.js b/controllers/test/index.js deleted file mode 100644 index e69de29..0000000 diff --git a/core/BaseController.js b/core/BaseController.js deleted file mode 100644 index 0849679..0000000 --- a/core/BaseController.js +++ /dev/null @@ -1,11 +0,0 @@ -import app from './main.js'; - -class BaseController { - constructor() { - this.app = app; - this.ctx = app.ctx; - this.config = app.config; - } -} - -export default BaseController; \ No newline at end of file diff --git a/core/main.js b/core/main.js index 979f19a..45365b9 100644 --- a/core/main.js +++ b/core/main.js @@ -4,12 +4,15 @@ 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'; +function hasProcessArg(flag) { + return process.argv.includes(flag); +} + // 框架基础类 Main class Main extends EventEmitter { constructor() { @@ -53,62 +56,96 @@ class Main extends EventEmitter { 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 }); + const startMonitor = (useBypass = false) => { + const args = useBypass + ? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath] + : ['-NoProfile', '-File', scriptPath]; + const ps = spawn('powershell.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] }); + + 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}`); - }); + }); + + 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) => { + if (!useBypass && code !== 0) { + console.warn('[WMI Printer Monitor] no-bypass launch failed, retrying with ExecutionPolicy Bypass once'); + startMonitor(true); + return; + } + + console.warn(`[WMI Printer Monitor] exited with code ${code}`); + }); + }; + + startMonitor(false); } 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(); + } + + restartLocalWsServer(newPort) { + const port = Number(newPort); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error('wsPort 无效'); + } + + if (this.wsServer) { + this.wsServer.close(); + } + + this.config.wsPort = port; + this.wsServer = new WSServer(port, this); + return { + wsPort: port + }; + } + + async restartBackendRuntime(options = {}) { + const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 3001; + if (!Number.isInteger(wsPort) || wsPort < 1 || wsPort > 65535) { + throw new Error('wsPort 无效'); + } + + // 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。 + if (hasProcessArg('--backend-runner') || hasProcessArg('--service-runner')) { + return { wsPort }; + } + + this.restartLocalWsServer(wsPort); + + if (this.wsClient) { + this.wsClient.close(); + if (typeof this.wsClient._connect === 'function') { + this.wsClient._connect(); + } + } + + return { wsPort }; } getConfig() { @@ -120,28 +157,10 @@ class Main extends EventEmitter { 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) => { @@ -178,36 +197,6 @@ class Main extends EventEmitter { 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(); diff --git a/core/wsServer.js b/core/wsServer.js index 56539c2..20f7d16 100644 --- a/core/wsServer.js +++ b/core/wsServer.js @@ -10,15 +10,20 @@ class WSServer { this.server = null; this.clients = new Set(); this.services = app.services; // 从 app 获取服务实例 - this._start(); this.app = app; - app.on('printerComponentStatusChange', (data) => { + this._eventHandlers = {}; + this._start(); + this._bindAppEvents(); + } + + _bindAppEvents() { + this._eventHandlers.printerComponentStatusChange = (data) => { this.broadcast({ success: true, method: 'printerComponent.statusChange', result: data }); - }); - app.on('wsClientStatusChange', (data) => { + }; + this._eventHandlers.wsClientStatusChange = (data) => { this.broadcast({ success: true, method: 'wsClient.statusChange', result: data }); - }); - app.on('generateCode', (code) => { + }; + this._eventHandlers.generateCode = (code) => { console.log('生成绑定码事件触发,数据:', code); if (this.clients.size > 0) { console.log("当前连接客户端数量:", this.clients.size); @@ -34,10 +39,43 @@ class WSServer { } }, refreshDelay); } - }); - app.on('printerList', (data) => { + }; + this._eventHandlers.printerList = (data) => { this.broadcast({ success: true, method: 'printer.getWindowsPrinters', result: data }); - }); + }; + this._eventHandlers.updateDownloadProgress = (data) => { + this.broadcast({ success: true, method: 'update.downloadProgress', result: data }); + }; + + this.app.on('printerComponentStatusChange', this._eventHandlers.printerComponentStatusChange); + this.app.on('wsClientStatusChange', this._eventHandlers.wsClientStatusChange); + this.app.on('generateCode', this._eventHandlers.generateCode); + this.app.on('printerList', this._eventHandlers.printerList); + this.app.on('updateDownloadProgress', this._eventHandlers.updateDownloadProgress); + } + + _unbindAppEvents() { + if (!this._eventHandlers) { + return; + } + + if (this._eventHandlers.printerComponentStatusChange) { + this.app.off('printerComponentStatusChange', this._eventHandlers.printerComponentStatusChange); + } + if (this._eventHandlers.wsClientStatusChange) { + this.app.off('wsClientStatusChange', this._eventHandlers.wsClientStatusChange); + } + if (this._eventHandlers.generateCode) { + this.app.off('generateCode', this._eventHandlers.generateCode); + } + if (this._eventHandlers.printerList) { + this.app.off('printerList', this._eventHandlers.printerList); + } + if (this._eventHandlers.updateDownloadProgress) { + this.app.off('updateDownloadProgress', this._eventHandlers.updateDownloadProgress); + } + + this._eventHandlers = {}; } _start() { this.server = new WebSocketServer({ port: this.port, ...this.options }); @@ -195,6 +233,7 @@ class WSServer { this.clients.clear(); //console.log('[WSServer] 服务端关闭'); } + this._unbindAppEvents(); } } diff --git a/electron/assets/printserver-icon-256.png b/electron/assets/printserver-icon-256.png new file mode 100644 index 0000000000000000000000000000000000000000..3839eca8aadba084a9e2d8fd91a5271d351be2ba GIT binary patch literal 6252 zcmbVRc|26#`@dsqrZ7gI$QDytRFtw-mZ3;}R4NrALkkK`g(lm~h(e1c-}V@-DrqWd zA!f2m5tSv&3?pmICCtU0ncunU`}_a*d%bv>Irllw^PKnde%|MvBXP%eCz7JJA_PIC zEt?&7K@bjn#6hzN;E&hIM}FA1kX=q2pl3Dn`@okO{`TAKA?QW266!k>e4l-M^S%%W zQYpcHaTWAOhagB3x5dGJ_i69JHs>I(#%Ka;R4Dq?8hHf2zp3EpBEBsG~ODjlvnw{K5y>;~NB-R76e z?QgP|Ywtc%_a8^gthbVrertPfFI?B9TO(%;NpO_+sSA5MWkum_R==-s7tA{I|M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dq^a`5?CGml(VR7lyw~hjMX-rnx>p{VcE>EKI`Ck`H2L8d-15Q%!uVxb+tvq;eE2 zq$+GtQAzT~3~;G4a?TF3j1bb7FeOe_IWgbXOw4ywS=g?6sG9sVD10uE)3bsND89;x z?Xp<+#(~l*wcNe0M`s~F6<9j}sU8~)aYxrDmMV>`OHfUmvW>a2d|Pw#$VMyA2m*@T zUA1WPBx*crp3fLrH?`J0&i=rS5yQO?U->+6PW~0z=RDIIlxFWie5}q3By;K}Q_Dq6 z+HPbjJ)i#0I^gj6>MK9`ss|>wH!@z;JCh>p1#|Y-2Cjb~h8^bW(!XpFsazV&iM`UT zZI(?pDXd7c=uLQ7VrBWFaARIMQS6?0=dfX_$EklFKfR#a*t_Wee2re;fKu1`DfY1x Ui#CG)5I|cTw>v!B;B)4G0QQnEN&o-= literal 0 HcmV?d00001 diff --git a/electron/assets/printserver.ico b/electron/assets/printserver.ico new file mode 100644 index 0000000000000000000000000000000000000000..5e1add86fc372dab16c50bdb5e005ba4d12c5107 GIT binary patch literal 15595 zcmbWe2T)Vpw>Ex4ARt}oH3&*ksx+meC?Fuk0@5us>C#&WAX23YD7^?M2q;B53DQBS zN{7&^Ka0!B?W-*FaQu2|L1*>3;-0U06<0MpLb<)0H8e&07&FN@7JgS zKnK)C{72O906qs^0)Pm;d+Icl?37?Lji!d00r&}e0MJu_x&inu;R*NwaWhcA36%D7 zu7WS5HmW+R0Pr=I3jYMO37m7$cXvxB|E zH5xT;kEhM#42A@sk!OCGTNIG*DlM+{#)iWGEc#e41z=jBbe1pXHB;-(Sik2Nv5C1xrd4@6Pdm&Trqk|CXC<`enc9z)XXb4>dh>iezrvU z)9lMkOD#FM(OPdxV2Gq;j!*y052gDybd*8%MZ@-CbausYT89@?hA)aq^RTSNQAu-Z zu8~+bKh{$s%e{B6vMexdLRTri^y%U5NKB`1Tkxl%AkquIT5-Z|CsjRV(;nzM>}k%f zQkmz)X)dYaCGNWaU(^ zG7)F+7;-<5bYbwFkkQhClk$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gd-iEff4tm{jXs?VwAzM z?k>>i>E8AeO<1zq5~?>jtUk)MNjS?pLWh4bcnn2+tnk1+gKEQ1uda3q-~RJ`4u-YI zUd<@ovdvF(P!b3zJ8);N=Sxyc+p~!A%JDj#hbq$uKiAUk$rpQC_!DJ$C(l zEz2K#6%DaDh5P7)A?<6^!qsxN`KOD^u@K_e19imVc=+{Gu@j0b_Yep+;*~{l>{(XN zo#leUd0E;5Y9DEvj4qrQPpKc zNyquWl0Bhi6_6ZRTv*BkZ*1I}w-nb71A3ez7`L3hPyT^|uDk#z(&fR|)Dn9u6TH;fd96Z}^qq0Oj5t)6FA4f3am0C>_Tn`C z^B%g-4n7QEISs|!#6!E(k-C?--al>aVyt-dZI1%CND`^K{m#`#1(lZhTCsoJSGC9# zz|cH;1`Xl(ipxGpMX>2^(cBZ3JdMn#Rj{>+>`5A5?O8v*H{w+}s72$eiaBrAXD^q( zg;itVa_+x5Py1%0BqV8xU8>mmT4P6y%u0Aci@faD##>eG { - setTimeout(loadMainPage, 1000); - }); + readRuntimeConfig() + .then((config) => { + const wsPort = Number(config?.wsPort) || 3001; + return mainWindow.loadFile(MAIN_FILE, { + query: { + wsPort: String(wsPort) + } + }); + }) + .catch(() => { + setTimeout(loadMainPage, 1000); + }); } function createMainWindow() { mainWindow = new BrowserWindow({ - width: 1280, - height: 900, - minWidth: 1024, - minHeight: 720, + width: 1024, + height: 720, + minWidth: 960, + minHeight: 500, show: false, autoHideMenuBar: true, - title: 'printServer', + title: APP_TITLE, + icon: ICON_ICO_PATH, webPreferences: { contextIsolation: true, nodeIntegration: false @@ -261,7 +292,7 @@ function createMainWindow() { function createTray() { tray = new Tray(createTrayImage()); - tray.setToolTip('printServer'); + tray.setToolTip(APP_TITLE); const contextMenu = Menu.buildFromTemplate([ { diff --git a/electron/nsis-shortcuts.nsh b/electron/nsis-shortcuts.nsh new file mode 100644 index 0000000..999b38a --- /dev/null +++ b/electron/nsis-shortcuts.nsh @@ -0,0 +1,9 @@ +!macro customInstall + CreateShortCut "$DESKTOP\\打印电脑服务.lnk" "$INSTDIR\\printServer.exe" "" "$INSTDIR\\resources\\printserver.ico" 0 + CreateShortCut "$SMPROGRAMS\\打印电脑服务.lnk" "$INSTDIR\\printServer.exe" "" "$INSTDIR\\resources\\printserver.ico" 0 +!macroend + +!macro customUnInstall + Delete "$DESKTOP\\打印电脑服务.lnk" + Delete "$SMPROGRAMS\\打印电脑服务.lnk" +!macroend diff --git a/index.js b/index.js index 7f2514c..58ea4ca 100644 --- a/index.js +++ b/index.js @@ -1,10 +1,5 @@ -import http from 'http'; -import configUtil from './utils/config.js'; -import app from './core/main.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}`); -}); \ No newline at end of file +console.log(`后端已启动(仅 WS 模式),监听端口: ${app.config.wsPort}`); + +export default app; \ No newline at end of file diff --git a/package.json b/package.json index 06e525f..5b2fc9c 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,21 @@ { "name": "printserver", - "version": "1.0.1", + "version": "1.0.9", "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" + "package:clean": "powershell -NoProfile -File build.ps1 clean", + "package:prepare": "powershell -NoProfile -File build.ps1 prepare", + "package:app": "powershell -NoProfile -File build.ps1 app", + "package:win": "powershell -NoProfile -File build.ps1 win", + "package": "powershell -NoProfile -File build.ps1 package", + "release:linux": "powershell -NoProfile -File scripts/deploy-linux.ps1 -ConfigPath scripts/deploy.config.json", + "release:linux:local": "powershell -NoProfile -File scripts/deploy-linux.ps1 -ConfigPath scripts/deploy.config.local.json" }, - "author": "", + "author": "LFMR", "license": "ISC", "description": "Windows local print service with HTTP, WebSocket, tray shell and printer component integration", "dependencies": { @@ -30,20 +32,19 @@ "type": "module", "build": { "appId": "com.gztbyc.printserver", - "productName": "printServer", + "productName": "打印电脑服务", "directories": { "output": "dist" }, "files": [ "electron/**/*", - "controllers/**/*", "core/**/*", "services/**/*", "utils/**/*", "views/**/*", - "routes.js", "index.js", "package.json", + "!config.json", "!临时/**/*", "!开发日志/**/*", "!day.log", @@ -54,6 +55,10 @@ "from": "config.packaged.json", "to": "config.json" }, + { + "from": "electron/assets/printserver.ico", + "to": "printserver.ico" + }, "printer.ps1", { "from": "daemon", @@ -61,7 +66,8 @@ } ], "win": { - "executableName": "electron", + "icon": "electron/assets/printserver.ico", + "executableName": "printServer", "signAndEditExecutable": false, "target": [ { @@ -76,9 +82,13 @@ "nsis": { "oneClick": false, "allowToChangeInstallationDirectory": true, - "createDesktopShortcut": true, - "createStartMenuShortcut": true, - "shortcutName": "printServer" + "installerIcon": "electron/assets/printserver.ico", + "uninstallerIcon": "electron/assets/printserver.ico", + "createDesktopShortcut": false, + "createStartMenuShortcut": false, + "include": "electron/nsis-shortcuts.nsh", + "shortcutName": "打印电脑服务" } } } + diff --git a/routes.js b/routes.js deleted file mode 100644 index 9389d43..0000000 --- a/routes.js +++ /dev/null @@ -1,6 +0,0 @@ -// 路由配置,只需写控制器类和方法名 -const routes = [ - { method: 'GET', path: '/', controller: 'index.index' }, -]; - -export default routes diff --git a/scripts/deploy-linux.ps1 b/scripts/deploy-linux.ps1 new file mode 100644 index 0000000..f7ece12 --- /dev/null +++ b/scripts/deploy-linux.ps1 @@ -0,0 +1,142 @@ +param( + [string]$ConfigPath = 'scripts/deploy.config.json', + [string]$ArtifactPath = '', + [switch]$DryRun +) + +$ErrorActionPreference = 'Stop' + +$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) + +function Assert-Command([string]$Name) { + if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) { + throw "$Name not found in PATH" + } +} + +function Run-External([string]$Command, [string[]]$CommandArgs) { + $argPreview = ($CommandArgs | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' ' + Write-Host ("[deploy] exec: " + $Command + " " + $argPreview) + & $Command @CommandArgs + if ($LASTEXITCODE -ne 0) { + throw "$Command failed with exit code $LASTEXITCODE" + } +} + +function Resolve-Artifact([string]$ExplicitPath, [string]$Pattern) { + if (-not [string]::IsNullOrWhiteSpace($ExplicitPath)) { + $resolved = Resolve-Path -Path $ExplicitPath -ErrorAction SilentlyContinue + if (-not $resolved) { + throw "artifact not found: $ExplicitPath" + } + return $resolved.Path + } + + if ([string]::IsNullOrWhiteSpace($Pattern)) { + $Pattern = 'dist/printServer-*-setup.exe' + } + + $glob = Join-Path $root $Pattern + $latest = Get-ChildItem -Path $glob -File -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | + Select-Object -First 1 + + if (-not $latest) { + throw "no artifact matched pattern: $Pattern" + } + + return $latest.FullName +} + +function To-PosixPath([string]$PathValue) { + return $PathValue.Replace('\\', '/') +} + +$configFile = Join-Path $root $ConfigPath +if (-not (Test-Path $configFile)) { + throw "deploy config not found: $configFile" +} + +$config = Get-Content -Path $configFile -Raw | ConvertFrom-Json + +$serverHost = [string]$config.host +$user = [string]$config.user +$sshKeyPath = [string]$config.sshKeyPath +$remoteDir = [string]$config.remoteDir +$baseUrl = [string]$config.baseUrl +$artifactPattern = [string]$config.artifactPattern +$keepReleases = [int]$config.keepReleases + +if ($keepReleases -lt 1) { + $keepReleases = 5 +} + +foreach ($required in @('host', 'user', 'sshKeyPath', 'remoteDir', 'baseUrl')) { + if ([string]::IsNullOrWhiteSpace([string]$config.$required)) { + throw "missing required deploy config field: $required" + } +} + +$artifact = Resolve-Artifact -ExplicitPath $ArtifactPath -Pattern $artifactPattern +$fileName = Split-Path -Leaf $artifact +$artifactHash = (Get-FileHash -Path $artifact -Algorithm SHA256).Hash +$artifactVersion = '' +$versionMatch = [regex]::Match($fileName, '(\d+\.\d+\.\d+)') +if ($versionMatch.Success) { + $artifactVersion = $versionMatch.Groups[1].Value +} + +Assert-Command 'ssh' +Assert-Command 'scp' + +$sshTarget = "$user@$serverHost" +$keyPathPosix = To-PosixPath $sshKeyPath +$sshArgsBase = @( + '-i', $keyPathPosix, + '-o', 'BatchMode=yes', + '-o', 'StrictHostKeyChecking=accept-new' +) + +$remoteDirQuoted = "'" + $remoteDir.Replace("'", "'\\''") + "'" +$remoteDirNormalized = $remoteDir.TrimEnd('/') +$remoteFilePath = "$remoteDirNormalized/$fileName" +$remoteSpec = "${sshTarget}:$remoteFilePath" +$minKeepIndex = $keepReleases + 1 + +Write-Host "[deploy] artifact: $artifact" +Write-Host "[deploy] target: $remoteSpec" +Write-Host "[deploy] keep releases: $keepReleases" + +if ($DryRun) { + Write-Host '[deploy] dry-run enabled, no upload executed' + exit 0 +} + +Run-External -Command 'ssh' -CommandArgs ($sshArgsBase + @($sshTarget, "mkdir -p $remoteDirQuoted")) +Run-External -Command 'scp' -CommandArgs ($sshArgsBase + @($artifact, $remoteSpec)) + +$cleanupCmd = "cd $remoteDirQuoted ; ls -1t printServer-*-setup.exe 2>/dev/null | tail -n +$minKeepIndex | xargs -r rm -f" +Run-External -Command 'ssh' -CommandArgs ($sshArgsBase + @($sshTarget, $cleanupCmd)) + +$tempMetaFile = Join-Path $env:TEMP ("printserver-latest-" + [guid]::NewGuid().ToString('N') + ".json") +$metaObject = [PSCustomObject]@{ + version = $artifactVersion + file = $fileName + url = ($baseUrl.TrimEnd('/') + '/' + $fileName) + sha256 = $artifactHash + publishedAtUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') +} +$metaObject | ConvertTo-Json -Depth 3 | Set-Content -Path $tempMetaFile -Encoding UTF8 + +try { + $remoteMetaSpec = "${sshTarget}:$remoteDirNormalized/latest.json" + Run-External -Command 'scp' -CommandArgs ($sshArgsBase + @($tempMetaFile, $remoteMetaSpec)) +} finally { + if (Test-Path $tempMetaFile) { + Remove-Item -Path $tempMetaFile -Force + } +} + +$link = $baseUrl.TrimEnd('/') + '/' + $fileName +Write-Host "[deploy] done" +Write-Host "[deploy] url: $link" diff --git a/scripts/deploy.config.json b/scripts/deploy.config.json new file mode 100644 index 0000000..bbd5aa5 --- /dev/null +++ b/scripts/deploy.config.json @@ -0,0 +1,9 @@ +{ + "host": "112.124.21.102", + "user": "root", + "sshKeyPath": "C:/Users/lfmingren/.ssh/112.124.21.102_id_ed25519", + "remoteDir": "/www/wwwroot/dl/printServer/", + "baseUrl": "https://dl.wms.gztbyc.com/printServer", + "artifactPattern": "dist/printServer-*-setup.exe", + "keepReleases": 5 +} diff --git a/scripts/deploy.config.local.example.json b/scripts/deploy.config.local.example.json new file mode 100644 index 0000000..dab78c0 --- /dev/null +++ b/scripts/deploy.config.local.example.json @@ -0,0 +1,9 @@ +{ + "host": "your-server-ip", + "user": "root", + "sshKeyPath": "C:/Users/yourname/.ssh/your_key", + "remoteDir": "/www/wwwroot/dl/", + "baseUrl": "https://example.com/printServer", + "artifactPattern": "dist/printServer-*-setup.exe", + "keepReleases": 5 +} diff --git a/services/setting.js b/services/setting.js index 99c25c1..74503d4 100644 --- a/services/setting.js +++ b/services/setting.js @@ -6,6 +6,21 @@ function isServiceRunnerProcess() { return process.argv.includes('--service-runner'); } +function isManagedBackendRunnerProcess() { + return process.argv.includes('--backend-runner') || process.argv.includes('--service-runner'); +} + +function scheduleCurrentProcessExit() { + // 给 WS 响应留出时间,再退出当前前台后端以释放端口。 + setTimeout(() => { + try { + process.exit(0); + } catch (error) { + console.error('[SettingService] 退出前台后端失败:', error); + } + }, 500); +} + class SettingService extends service { constructor() { super(); @@ -13,6 +28,8 @@ class SettingService extends service { this.unbind = this.unbind.bind(this); this.register = this.register.bind(this); this.unregister = this.unregister.bind(this); + this.updatePorts = this.updatePorts.bind(this); + this.restartBackend = this.restartBackend.bind(this); this.setToken = this.setToken.bind(this); this.setInfo = this.setInfo.bind(this); } @@ -22,9 +39,72 @@ class SettingService extends service { return { isBind: !!config.token, name: config.name || '', - isService: !!config.isService + isService: !!config.isService, + wsPort: Number(config.wsPort) || 3001 }; } + + async updatePorts(data = {}) { + const { config, app } = this; + const nextWsPort = Number(data.wsPort); + + if (!Number.isInteger(nextWsPort) || nextWsPort < 1 || nextWsPort > 65535) { + return { ok: false, message: 'WS 端口无效,范围应为 1-65535' }; + } + + const wsPortChanged = Number(config.wsPort) !== nextWsPort; + + config.wsPort = nextWsPort; + configUtil.write(config); + app.config = config; + + return { + ok: true, + message: wsPortChanged ? 'WS 端口已更新,重启后端后生效' : 'WS 端口未变化', + wsPort: nextWsPort, + wsPortChanged, + requiresBackendRestart: !!wsPortChanged + }; + } + + async restartBackend(data = {}) { + const { app } = this; + const targetWsPort = Number(data.wsPort) || Number(app.config?.wsPort) || 3001; + + if (isManagedBackendRunnerProcess()) { + scheduleCurrentProcessExit(); + return { + ok: true, + restarting: true, + wsPort: targetWsPort, + message: '后端正在重启,请稍候重连' + }; + } + + if (!app || typeof app.restartBackendRuntime !== 'function') { + return { + ok: false, + restarting: false, + message: '当前运行态不支持重启后端' + }; + } + + try { + const result = await app.restartBackendRuntime({ wsPort: targetWsPort }); + return { + ok: true, + restarting: false, + wsPort: result.wsPort, + message: '后端已重启' + }; + } catch (error) { + return { + ok: false, + restarting: false, + message: `后端重启失败:${error.message}` + }; + } + } // 解绑(WebSocket/HTTP 通用,无 ctx 依赖) unbind() { const { config } = this; @@ -38,59 +118,68 @@ class SettingService extends service { // WebSocket 注册服务,切换为“系统服务管理后端”的状态 async register() { const { config } = this; + const previousIsService = !!config.isService; try { await ensureServiceInstalled(); } catch (error) { - config.isService = false; + config.isService = previousIsService; configUtil.write(config); - this.app.isServices = false; + this.app.isService = previousIsService; return { ok: false, message: `系统服务注册失败:${error.message}`, - isServices: false + isService: previousIsService }; } config.isService = true; configUtil.write(config); - this.app.isServices = true; + this.app.isService = true; + + if (!isServiceRunnerProcess()) { + scheduleCurrentProcessExit(); + } return { ok: true, - message: '服务模式已启用,桌面壳会改为通过系统服务拉起后端', - isServices: true + message: isServiceRunnerProcess() + ? '服务模式已启用' + : '服务模式已启用,当前前台后端将退出,由系统服务接管', + isService: true }; } // WebSocket 注销服务,切回“桌面壳直接拉起后端”的状态 async unregister() { const { config } = this; - config.isService = false; - configUtil.write(config); - this.app.isServices = false; + const previousIsService = !!config.isService; if (!isServiceRunnerProcess()) { try { await uninstallService(); } catch (error) { - config.isService = true; + config.isService = previousIsService; configUtil.write(config); - this.app.isServices = true; + this.app.isService = previousIsService; return { ok: false, message: `系统服务注销失败:${error.message}`, - isServices: true + isService: previousIsService }; } } + config.isService = false; + configUtil.write(config); + this.app.isService = false; + return { ok: true, message: isServiceRunnerProcess() ? '服务模式已关闭,桌面壳会切回本地后端启动并清理系统服务' : '服务已注销,后端将恢复为桌面壳直接启动', - isServices: false + isService: false }; } async setToken(data) { diff --git a/services/update.js b/services/update.js new file mode 100644 index 0000000..198d7c9 --- /dev/null +++ b/services/update.js @@ -0,0 +1,544 @@ +import service from '../core/BaseService.js'; +import fs from 'fs'; +import path from 'path'; +import http from 'http'; +import https from 'https'; +import crypto from 'crypto'; +import { execFile } from 'child_process'; +import { promisify } from 'util'; +import { ensureDirectory, getAppDataDir, getProjectRoot } from '../utils/runtime.js'; + +const execFileAsync = promisify(execFile); + +const DEFAULT_FEED_URL = 'https://wms.wms.gztbyc.com/printServer/latest.json'; + +function parseVersionFromFileName(fileName) { + if (!fileName) { + return ''; + } + + const matched = String(fileName).match(/(\d+\.\d+\.\d+)/); + return matched ? matched[1] : ''; +} + +function normalizeVersion(version) { + return String(version || '') + .trim() + .replace(/^v/i, '') + .split('.') + .map((part) => { + const num = Number(part.replace(/\D.*$/, '')); + return Number.isFinite(num) && num >= 0 ? num : 0; + }); +} + +function compareVersion(a, b) { + const va = normalizeVersion(a); + const vb = normalizeVersion(b); + const length = Math.max(va.length, vb.length, 3); + + for (let i = 0; i < length; i += 1) { + const left = va[i] || 0; + const right = vb[i] || 0; + if (left > right) { + return 1; + } + if (left < right) { + return -1; + } + } + + return 0; +} + +function resolveCurrentVersion() { + const candidates = [ + path.join(getProjectRoot(), 'package.json'), + process.resourcesPath ? path.join(process.resourcesPath, 'app.asar', 'package.json') : '', + process.resourcesPath ? path.join(process.resourcesPath, 'app', 'package.json') : '' + ].filter(Boolean); + + for (const packagePath of candidates) { + try { + if (!fs.existsSync(packagePath)) { + continue; + } + + const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8')); + if (pkg && pkg.version) { + return String(pkg.version); + } + } catch (error) { + // Try next candidate path. + } + } + + return '0.0.0'; +} + +function requestJson(feedUrl, timeoutMs = 8000) { + return new Promise((resolve, reject) => { + let parsedUrl; + try { + parsedUrl = new URL(feedUrl); + } catch (error) { + reject(new Error(`更新地址无效: ${feedUrl}`)); + return; + } + + const isHttps = parsedUrl.protocol === 'https:'; + const client = isHttps ? https : http; + const options = { + method: 'GET', + timeout: timeoutMs, + headers: { + Accept: 'application/json' + } + }; + + const req = client.request(parsedUrl, options, (res) => { + let raw = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { + raw += chunk; + }); + res.on('end', () => { + if (res.statusCode < 200 || res.statusCode >= 300) { + reject(new Error(`更新清单请求失败: HTTP ${res.statusCode}`)); + return; + } + + try { + const normalizedRaw = raw.replace(/^\uFEFF/, '').trim(); + resolve(JSON.parse(normalizedRaw)); + } catch (error) { + reject(new Error('更新清单 JSON 格式无效')); + } + }); + }); + + req.on('timeout', () => { + req.destroy(new Error('更新清单请求超时')); + }); + + req.on('error', (error) => { + reject(error); + }); + + req.end(); + }); +} + +async function fetchFeedJson(feedUrl) { + try { + return await requestJson(feedUrl, 8000); + } catch (error) { + const urlObj = new URL(feedUrl); + if (urlObj.protocol === 'https:') { + // 某些 Windows 环境下 Node TLS 校验会失败,回退到 HTTP 读取更新清单。 + const fallbackUrl = `http://${urlObj.host}${urlObj.pathname}${urlObj.search}`; + return requestJson(fallbackUrl, 8000); + } + + throw error; + } +} + +function buildDownloadUrl(feedUrl, feedJson, config) { + if (feedJson.url) { + return String(feedJson.url); + } + + const fileName = String(feedJson.file || '').trim(); + if (!fileName) { + return ''; + } + + const baseUrl = String(config?.update?.downloadBaseUrl || '').trim(); + if (baseUrl) { + return `${baseUrl.replace(/\/$/, '')}/${fileName}`; + } + + const urlObj = new URL(feedUrl); + const basePath = urlObj.pathname.replace(/\/[^/]*$/, ''); + urlObj.pathname = `${basePath}/${fileName}`.replace(/\/+/g, '/'); + urlObj.search = ''; + urlObj.hash = ''; + return urlObj.toString(); +} + +class UpdateService extends service { + constructor() { + super(); + this.check = this.check.bind(this); + this.getDownloadState = this.getDownloadState.bind(this); + this.downloadAndInstall = this.downloadAndInstall.bind(this); + this.openDownloadedInstaller = this.openDownloadedInstaller.bind(this); + this._downloadState = { + status: 'idle', + percent: 0, + downloadedBytes: 0, + totalBytes: 0, + message: '', + downloadUrl: '', + filePath: '', + latestVersion: '', + currentVersion: resolveCurrentVersion(), + startedAt: '', + updatedAt: new Date().toISOString() + }; + this._activeDownload = null; + } + + _emitDownloadState(patch = {}) { + this._downloadState = { + ...this._downloadState, + ...patch, + updatedAt: new Date().toISOString() + }; + + this.app.emit('updateDownloadProgress', this._downloadState); + } + + _safeFileName(fileName) { + const cleaned = String(fileName || '').replace(/[\\/:*?"<>|]/g, '_').trim(); + return cleaned || `printServer-${Date.now()}-setup.exe`; + } + + _requestDownloadStream(downloadUrl, redirectCount = 0) { + return new Promise((resolve, reject) => { + const maxRedirects = 5; + const parsed = new URL(downloadUrl); + const client = parsed.protocol === 'https:' ? https : http; + const request = client.get(parsed, { timeout: 12000 }, (response) => { + const status = Number(response.statusCode || 0); + + if (status >= 300 && status < 400 && response.headers.location) { + if (redirectCount >= maxRedirects) { + reject(new Error('下载重定向次数过多')); + return; + } + + const nextUrl = new URL(response.headers.location, parsed).toString(); + response.resume(); + resolve(this._requestDownloadStream(nextUrl, redirectCount + 1)); + return; + } + + if (status < 200 || status >= 300) { + response.resume(); + reject(new Error(`下载失败: HTTP ${status}`)); + return; + } + + resolve({ + response, + finalUrl: parsed.toString() + }); + }); + + request.on('timeout', () => { + request.destroy(new Error('下载超时')); + }); + + request.on('error', (error) => { + if (parsed.protocol === 'https:') { + const fallbackUrl = `http://${parsed.host}${parsed.pathname}${parsed.search}`; + this._requestDownloadStream(fallbackUrl, redirectCount) + .then(resolve) + .catch(reject); + return; + } + reject(error); + }); + }); + } + + async _downloadInstaller(downloadUrl, targetPath, onProgress) { + const { response, finalUrl } = await this._requestDownloadStream(downloadUrl); + const totalBytes = Number(response.headers['content-length'] || 0) || 0; + let downloadedBytes = 0; + const fileHash = crypto.createHash('sha256'); + + await new Promise((resolve, reject) => { + const dirPath = path.dirname(targetPath); + ensureDirectory(dirPath); + const tempPath = `${targetPath}.part`; + const writer = fs.createWriteStream(tempPath); + + const fail = (error) => { + try { + writer.destroy(); + } catch (e) { + // Ignore cleanup error. + } + + try { + if (fs.existsSync(tempPath)) { + fs.unlinkSync(tempPath); + } + } catch (e) { + // Ignore cleanup error. + } + + reject(error); + }; + + writer.on('error', fail); + response.on('error', fail); + + response.on('data', (chunk) => { + downloadedBytes += chunk.length; + fileHash.update(chunk); + + const percent = totalBytes > 0 + ? Math.min(100, Math.round((downloadedBytes / totalBytes) * 100)) + : null; + + onProgress({ + status: 'downloading', + downloadedBytes, + totalBytes, + percent, + message: totalBytes > 0 + ? `正在下载更新包(${percent}%)` + : '正在下载更新包' + }); + }); + + writer.on('finish', () => { + writer.close(() => { + fs.rename(tempPath, targetPath, (renameError) => { + if (renameError) { + fail(renameError); + return; + } + resolve(); + }); + }); + }); + + response.pipe(writer); + }); + + return { + finalUrl, + downloadedBytes, + totalBytes, + sha256: fileHash.digest('hex').toUpperCase() + }; + } + + _launchInstaller(installerPath) { + if (!installerPath || !fs.existsSync(installerPath)) { + throw new Error('安装包不存在,无法启动安装向导'); + } + + if (process.platform !== 'win32') { + throw new Error('当前系统不支持自动启动安装程序'); + } + + if (process.argv.includes('--service-runner')) { + throw new Error('服务模式无法弹出安装向导,请在前台模式下重试'); + } + + if (this.app?.config?.isService) { + throw new Error('当前处于服务模式,无法直接弹出安装向导,请先注销服务后再更新'); + } + + const escapedPath = installerPath.replace(/'/g, "''"); + const psArgs = [ + '-NoProfile', + '-Command', + `Start-Process -FilePath '${escapedPath}' -Verb RunAs -ErrorAction Stop | Out-Null` + ]; + + return execFileAsync('powershell.exe', psArgs, { + windowsHide: false + }).catch((error) => { + const details = [error.stdout, error.stderr, error.message] + .filter(Boolean) + .join(' | '); + throw new Error(details || '启动安装向导失败'); + }); + } + + getDownloadState() { + return { + ok: true, + ...this._downloadState + }; + } + + async openDownloadedInstaller(data = {}) { + const requestedPath = String(data.filePath || '').trim(); + const installerPath = requestedPath || this._downloadState.filePath; + + if (!installerPath) { + return { + ok: false, + message: '未找到已下载安装包' + }; + } + + try { + await this._launchInstaller(installerPath); + this._emitDownloadState({ + status: 'installing', + message: '安装程序已启动,请在安装向导中完成升级' + }); + return { + ok: true, + message: '安装程序已启动', + filePath: installerPath + }; + } catch (error) { + this._emitDownloadState({ + status: 'failed', + message: `启动安装失败:${error.message}` + }); + return { + ok: false, + message: `启动安装失败:${error.message}`, + filePath: installerPath + }; + } + } + + async check(data = {}) { + const configFeedUrl = this.config?.update?.feedUrl; + const feedUrl = String(data.feedUrl || configFeedUrl || DEFAULT_FEED_URL).trim(); + const currentVersion = resolveCurrentVersion(); + + try { + const feedJson = await fetchFeedJson(feedUrl); + const latestVersion = String(feedJson.version || parseVersionFromFileName(feedJson.file || '')).trim(); + if (!latestVersion) { + throw new Error('更新清单缺少 version/file 字段'); + } + + const downloadUrl = buildDownloadUrl(feedUrl, feedJson, this.config); + const hasUpdate = compareVersion(latestVersion, currentVersion) > 0; + + return { + ok: true, + hasUpdate, + currentVersion, + latestVersion, + downloadUrl, + file: String(feedJson.file || ''), + sha256: String(feedJson.sha256 || ''), + checkedAt: new Date().toISOString() + }; + } catch (error) { + return { + ok: false, + hasUpdate: false, + currentVersion, + latestVersion: currentVersion, + downloadUrl: '', + message: `检查更新失败:${error.message}` + }; + } + } + + async downloadAndInstall(data = {}) { + if (this._activeDownload) { + return { + ok: false, + message: '已有更新任务正在执行,请稍候', + state: this._downloadState + }; + } + + const checkResult = await this.check({}); + const currentVersion = checkResult.currentVersion || resolveCurrentVersion(); + const latestVersion = String(data.version || checkResult.latestVersion || currentVersion).trim(); + const requestedUrl = String(data.downloadUrl || checkResult.downloadUrl || '').trim(); + + if (!requestedUrl) { + return { + ok: false, + message: '未获取到更新下载地址' + }; + } + + const fileNameFromUrl = (() => { + try { + return path.basename(new URL(requestedUrl).pathname || ''); + } catch (error) { + return ''; + } + })(); + const fileName = this._safeFileName(fileNameFromUrl || `printServer-${latestVersion || Date.now()}-setup.exe`); + const updateDir = ensureDirectory(path.join(getAppDataDir(), 'updates')); + const targetPath = path.join(updateDir, fileName); + + this._emitDownloadState({ + status: 'starting', + percent: 0, + downloadedBytes: 0, + totalBytes: 0, + message: '开始下载更新包', + downloadUrl: requestedUrl, + filePath: targetPath, + latestVersion, + currentVersion, + startedAt: new Date().toISOString() + }); + + this._activeDownload = (async () => { + try { + const downloadResult = await this._downloadInstaller(requestedUrl, targetPath, (progress) => { + this._emitDownloadState(progress); + }); + + this._emitDownloadState({ + status: 'downloaded', + percent: 100, + downloadedBytes: downloadResult.downloadedBytes, + totalBytes: downloadResult.totalBytes, + message: '更新包下载完成,正在启动安装程序', + filePath: targetPath, + sha256: downloadResult.sha256 + }); + + await this._launchInstaller(targetPath); + + this._emitDownloadState({ + status: 'installing', + percent: 100, + message: '安装程序已启动,请在安装向导中完成升级' + }); + + return { + ok: true, + message: '安装程序已启动', + filePath: targetPath, + latestVersion, + sha256: downloadResult.sha256 + }; + } catch (error) { + this._emitDownloadState({ + status: 'failed', + message: `更新失败:${error.message}` + }); + return { + ok: false, + message: `更新失败:${error.message}` + }; + } finally { + this._activeDownload = null; + } + })(); + + return { + ok: true, + message: '已开始下载更新包', + latestVersion, + filePath: targetPath + }; + } +} + +export default new UpdateService(); diff --git a/utils/runtime.js b/utils/runtime.js index e68c801..59382c3 100644 --- a/utils/runtime.js +++ b/utils/runtime.js @@ -87,7 +87,10 @@ export function ensureWritableConfigFile() { return writableConfigPath; } - if (isPackagedElectron()) { + // For packaged builds, do not migrate legacy roaming config by default. + // This prevents test tokens/settings from being copied into production runtime. + const allowLegacyMigration = process.env.PRINTSERVER_ALLOW_LEGACY_CONFIG_MIGRATION === '1'; + if (isPackagedElectron() && allowLegacyMigration) { const legacyConfigPath = getLegacyElectronConfigPath(); if (fs.existsSync(legacyConfigPath)) { fs.copyFileSync(legacyConfigPath, writableConfigPath); diff --git a/utils/windowsService.js b/utils/windowsService.js index b153154..1403208 100644 --- a/utils/windowsService.js +++ b/utils/windowsService.js @@ -127,7 +127,7 @@ async function runWrapperCommandElevated(command, metadata) { ].join(' '); try { - await execFileAsync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', psCommand], { + await execFileAsync('powershell.exe', ['-NoProfile', '-Command', psCommand], { windowsHide: true }); } catch (error) { @@ -143,7 +143,10 @@ async function runWrapperCommandElevated(command, metadata) { }; } -async function runWrapperCommand(command) { +async function runWrapperCommand(command, options = {}) { + const { + allowElevation = true + } = options; const metadata = ensureServiceDefinition(); try { @@ -161,7 +164,7 @@ async function runWrapperCommand(command) { const stderr = (error.stderr || '').trim(); const details = [stdout, stderr, error.message].filter(Boolean).join(' | '); - if (command !== 'status' && isAccessDeniedErrorMessage(details)) { + if (allowElevation && command !== 'status' && isAccessDeniedErrorMessage(details)) { try { return await runWrapperCommandElevated(command, metadata); } catch (elevatedError) { @@ -191,51 +194,51 @@ function parseServiceStatus(rawStatus) { }; } -export async function getServiceStatus() { - const { stdout } = await runWrapperCommand('status'); +export async function getServiceStatus(options = {}) { + const { stdout } = await runWrapperCommand('status', options); return parseServiceStatus(stdout); } -export async function ensureServiceInstalled() { - const status = await getServiceStatus(); +export async function ensureServiceInstalled(options = {}) { + const status = await getServiceStatus(options); if (status.installed) { return status; } - await runWrapperCommand('install'); - return getServiceStatus(); + await runWrapperCommand('install', options); + return getServiceStatus(options); } -export async function startService() { - const status = await ensureServiceInstalled(); +export async function startService(options = {}) { + const status = await ensureServiceInstalled(options); if (status.running) { return status; } - await runWrapperCommand('start'); - return getServiceStatus(); + await runWrapperCommand('start', options); + return getServiceStatus(options); } -export async function stopService() { - const status = await getServiceStatus(); +export async function stopService(options = {}) { + const status = await getServiceStatus(options); if (!status.installed || !status.running) { return status; } - await runWrapperCommand('stop'); - return getServiceStatus(); + await runWrapperCommand('stop', options); + return getServiceStatus(options); } -export async function uninstallService() { - const status = await getServiceStatus(); +export async function uninstallService(options = {}) { + const status = await getServiceStatus(options); if (!status.installed) { return status; } if (status.running) { - await runWrapperCommand('stop'); + await runWrapperCommand('stop', options); } - await runWrapperCommand('uninstall'); - return getServiceStatus(); + await runWrapperCommand('uninstall', options); + return getServiceStatus(options); } \ No newline at end of file diff --git a/views/index.html b/views/index.html index 66db52a..f92e5e3 100644 --- a/views/index.html +++ b/views/index.html @@ -3,7 +3,7 @@ - Print Server + 打印电脑设置
-

天豹云仓打印服务台

-
-
-

本地服务状态:{{ wsStatus[wsClientStatus].title - }}

-

- 服务注册状态: - - {{ isServices ? '已注册' : '未注册' }} - -

-

服务器连接状态:{{ wsStatus[wsServerStatus].title - }}

-

打印服务绑定状态: - {{ isBind ? '已绑定' : '未绑定' }} -

+
+

天豹云仓打印服务台

+
工作台:{{ name || '未命名' }}
+
+ +
+ + +
+ +
+
+
+
+
+

打印机列表

+
+
当前可用打印机
+ +
+
+
无打印机
+
{{ p.name }}
+
+
+ +
+

打印组件状态

+
+
组件连接状态总览
+
+
+
无打印组件
+
{{ c.name }} + {{wsStatus[getStatus(c.name)].title}} +
+
+
+
+ +
+
+

绑定工作台

+
+
+
未绑定打印台,请使用微信扫码二维码完成绑定。
+
+
+
+
-
-

绑定二维码,微信扫描绑定工作台

-
-
-
未绑定打印台,请扫描二维码绑定!
+ +
+
+

端口设置

+
+ + + +
+
保存后会自动重启后端,并让页面重新连接到新的 WS 端口。
+
{{ saveMessage }}
+ +
+

应用更新

+
+ 当前版本:{{ updateState.currentVersion || '-' }} + 最新版本:{{ updateState.latestVersion || '-' }} + 状态:{{ updateStatusText }} +
+
+
+
+
{{ updateState.message || '未开始下载' }}({{ updateProgressPercent }}%)
+
+ {{ formatBytes(updateState.downloadedBytes) }} / {{ updateState.totalBytes > 0 ? formatBytes(updateState.totalBytes) : '未知大小' }} +
+
+ + + +
+
- - -

打印组件及打印机

-
-
-
打印机名称 - -
-
-
无打印机
-
{{ p.name }}
-
+
+
+ + 本地服务:{{ wsStatus[wsClientStatus].title }}
-
-
打印组件状态 -
-
-
无打印组件
-
{{ c.name }} {{wsStatus[getStatus(c.name)].title}} -
-
+
+ + 服务注册: + {{ isServices ? '已注册' : '未注册' }} +
+
+ + 服务器连接:{{ wsStatus[wsServerStatus].title }} +
+
+ + 打印服务绑定:{{ isBind ? '已绑定' : '未绑定' }} +
+ +