docs: 完善README并收敛更新发布流程
This commit is contained in:
parent
f77ab95a90
commit
5bc0e6637e
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,6 +1,8 @@
|
||||
node_modules/
|
||||
dist/
|
||||
versioning/
|
||||
coverage/
|
||||
scripts/deploy.config.local.json
|
||||
|
||||
临时/
|
||||
涓存椂/
|
||||
|
||||
45
README.md
45
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/<version>/` 已存在产物,将直接阻止打包。
|
||||
- 需要手动更新版本号后再执行打包。
|
||||
|
||||
## 更新下发产物
|
||||
- 每次成功打包会自动归档安装包到 `versioning/releases/<version>/`。
|
||||
- 同步生成 `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/<installer>.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 端口当前不再承载页面服务)
|
||||
- 临时测试与分析文件统一放在 临时/ 目录
|
||||
|
||||
290
build.ps1
290
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 }
|
||||
|
||||
@ -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"
|
||||
}
|
||||
@ -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,
|
||||
|
||||
@ -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();
|
||||
@ -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;
|
||||
@ -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;
|
||||
179
core/main.js
179
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();
|
||||
|
||||
@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
BIN
electron/assets/printserver-icon-256.png
Normal file
BIN
electron/assets/printserver-icon-256.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.1 KiB |
BIN
electron/assets/printserver.ico
Normal file
BIN
electron/assets/printserver.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
139
electron/generate-icon.ps1
Normal file
139
electron/generate-icon.ps1
Normal file
@ -0,0 +1,139 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$outDir = Join-Path $root 'assets'
|
||||
if (-not (Test-Path $outDir)) {
|
||||
New-Item -ItemType Directory -Path $outDir -Force | Out-Null
|
||||
}
|
||||
|
||||
$pngPath = Join-Path $outDir 'printserver-icon-256.png'
|
||||
$icoPath = Join-Path $outDir 'printserver.ico'
|
||||
|
||||
function New-IconBitmap([int]$iconSize) {
|
||||
if ($iconSize -is [System.Array]) {
|
||||
$iconSize = [int]$iconSize[0]
|
||||
} else {
|
||||
$iconSize = [int]$iconSize
|
||||
}
|
||||
|
||||
$bmp = New-Object System.Drawing.Bitmap($iconSize, $iconSize)
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$g.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
$bgRect = New-Object System.Drawing.RectangleF -ArgumentList @(
|
||||
[single]($iconSize * 0.07),
|
||||
[single]($iconSize * 0.07),
|
||||
[single]($iconSize * 0.86),
|
||||
[single]($iconSize * 0.86)
|
||||
)
|
||||
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
|
||||
$radius = [single]($iconSize * 0.20)
|
||||
$diameter = $radius * 2
|
||||
$path.AddArc($bgRect.X, $bgRect.Y, $diameter, $diameter, 180, 90)
|
||||
$path.AddArc($bgRect.Right - $diameter, $bgRect.Y, $diameter, $diameter, 270, 90)
|
||||
$path.AddArc($bgRect.Right - $diameter, $bgRect.Bottom - $diameter, $diameter, $diameter, 0, 90)
|
||||
$path.AddArc($bgRect.X, $bgRect.Bottom - $diameter, $diameter, $diameter, 90, 90)
|
||||
$path.CloseFigure()
|
||||
|
||||
$startPoint = New-Object System.Drawing.PointF -ArgumentList @([single]0, [single]0)
|
||||
$endPoint = New-Object System.Drawing.PointF -ArgumentList @([single]$iconSize, [single]$iconSize)
|
||||
$bgBrush = New-Object System.Drawing.Drawing2D.LinearGradientBrush -ArgumentList @(
|
||||
$startPoint,
|
||||
$endPoint,
|
||||
[System.Drawing.Color]::FromArgb(255, 22, 118, 164),
|
||||
[System.Drawing.Color]::FromArgb(255, 19, 78, 74)
|
||||
)
|
||||
$g.FillPath($bgBrush, $path)
|
||||
|
||||
$shadowBrush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(70, 0, 0, 0))
|
||||
$g.FillEllipse($shadowBrush, $iconSize * 0.22, $iconSize * 0.68, $iconSize * 0.56, $iconSize * 0.15)
|
||||
|
||||
$printerBody = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(255, 245, 248, 250))
|
||||
$printerDark = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(255, 212, 220, 224))
|
||||
$accent = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(255, 27, 188, 155))
|
||||
$linePen = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(255, 96, 120, 130), [single]($iconSize * 0.018))
|
||||
|
||||
$g.FillRectangle($printerBody, $iconSize * 0.28, $iconSize * 0.36, $iconSize * 0.44, $iconSize * 0.29)
|
||||
$g.FillRectangle($printerDark, $iconSize * 0.33, $iconSize * 0.26, $iconSize * 0.34, $iconSize * 0.14)
|
||||
$g.FillRectangle($printerBody, $iconSize * 0.34, $iconSize * 0.50, $iconSize * 0.32, $iconSize * 0.23)
|
||||
|
||||
$g.FillRectangle($accent, $iconSize * 0.55, $iconSize * 0.42, $iconSize * 0.09, $iconSize * 0.05)
|
||||
$g.DrawRectangle($linePen, $iconSize * 0.34, $iconSize * 0.50, $iconSize * 0.32, $iconSize * 0.23)
|
||||
$g.DrawLine($linePen, $iconSize * 0.38, $iconSize * 0.57, $iconSize * 0.62, $iconSize * 0.57)
|
||||
$g.DrawLine($linePen, $iconSize * 0.38, $iconSize * 0.63, $iconSize * 0.59, $iconSize * 0.63)
|
||||
|
||||
$g.Dispose()
|
||||
$bgBrush.Dispose()
|
||||
$shadowBrush.Dispose()
|
||||
$printerBody.Dispose()
|
||||
$printerDark.Dispose()
|
||||
$accent.Dispose()
|
||||
$linePen.Dispose()
|
||||
$path.Dispose()
|
||||
|
||||
return $bmp
|
||||
}
|
||||
|
||||
function Convert-BitmapsToIco([System.Drawing.Bitmap[]]$bitmaps, [string]$destination) {
|
||||
$stream = New-Object System.IO.FileStream($destination, [System.IO.FileMode]::Create)
|
||||
$writer = New-Object System.IO.BinaryWriter($stream)
|
||||
|
||||
$writer.Write([UInt16]0)
|
||||
$writer.Write([UInt16]1)
|
||||
$writer.Write([UInt16]$bitmaps.Length)
|
||||
|
||||
$imageData = @()
|
||||
foreach ($bmp in $bitmaps) {
|
||||
$ms = New-Object System.IO.MemoryStream
|
||||
$bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$bytes = $ms.ToArray()
|
||||
$ms.Dispose()
|
||||
$imageData += ,$bytes
|
||||
}
|
||||
|
||||
$offset = 6 + (16 * $bitmaps.Length)
|
||||
for ($i = 0; $i -lt $bitmaps.Length; $i++) {
|
||||
$bmp = $bitmaps[$i]
|
||||
$bytes = $imageData[$i]
|
||||
$w = if ($bmp.Width -ge 256) { 0 } else { [byte]$bmp.Width }
|
||||
$h = if ($bmp.Height -ge 256) { 0 } else { [byte]$bmp.Height }
|
||||
|
||||
$writer.Write([byte]$w)
|
||||
$writer.Write([byte]$h)
|
||||
$writer.Write([byte]0)
|
||||
$writer.Write([byte]0)
|
||||
$writer.Write([UInt16]1)
|
||||
$writer.Write([UInt16]32)
|
||||
$writer.Write([UInt32]$bytes.Length)
|
||||
$writer.Write([UInt32]$offset)
|
||||
|
||||
$offset += $bytes.Length
|
||||
}
|
||||
|
||||
foreach ($bytes in $imageData) {
|
||||
$writer.Write($bytes)
|
||||
}
|
||||
|
||||
$writer.Flush()
|
||||
$writer.Close()
|
||||
$stream.Close()
|
||||
}
|
||||
|
||||
$sizes = @(16, 24, 32, 48, 64, 128, 256)
|
||||
$bitmaps = @()
|
||||
foreach ($s in $sizes) {
|
||||
$bitmaps += ,(New-IconBitmap -iconSize $s)
|
||||
}
|
||||
|
||||
$bitmaps[-1].Save($pngPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
Convert-BitmapsToIco -bitmaps $bitmaps -destination $icoPath
|
||||
|
||||
foreach ($bmp in $bitmaps) {
|
||||
$bmp.Dispose()
|
||||
}
|
||||
|
||||
Write-Host "ICON_OK: $icoPath"
|
||||
Write-Host "PNG_OK: $pngPath"
|
||||
@ -12,14 +12,23 @@ let backendProcess = null;
|
||||
let reconcileTimer = null;
|
||||
let reconcilePromise = null;
|
||||
|
||||
const MAIN_URL = 'http://127.0.0.1:3000/';
|
||||
const MAIN_FILE = path.join(__dirname, '..', 'views', 'index.html');
|
||||
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=';
|
||||
const APP_TITLE = '打印电脑服务';
|
||||
const ICON_ICO_PATH = path.join(__dirname, 'assets', 'printserver.ico');
|
||||
const ICON_PNG_PATH = path.join(__dirname, 'assets', 'printserver-icon-256.png');
|
||||
const TRAY_ICON_FALLBACK_DATA_URL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAV0lEQVR4AWP4TwAw/P//PwMDA8P///8ZGRkYGBgY/v//z8DAwMDA8J8B4v///5kYGRkZGBj+////PwMDw38Ghv9kZGQYGBj+////PwPDfwYGhv8MDAwA0rQYV5vWJ2EAAAAASUVORK5CYII=';
|
||||
const BACKGROUND_SERVICE_OPTIONS = { allowElevation: false };
|
||||
|
||||
function createTrayImage() {
|
||||
return nativeImage.createFromDataURL(TRAY_ICON_DATA_URL).resize({ width: 16, height: 16 });
|
||||
const icon = nativeImage.createFromPath(ICON_PNG_PATH);
|
||||
if (!icon.isEmpty()) {
|
||||
return icon.resize({ width: 16, height: 16 });
|
||||
}
|
||||
|
||||
return nativeImage.createFromDataURL(TRAY_ICON_FALLBACK_DATA_URL).resize({ width: 16, height: 16 });
|
||||
}
|
||||
|
||||
async function startLocalServer() {
|
||||
@ -136,25 +145,37 @@ async function ensureDesiredBackendState() {
|
||||
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();
|
||||
const status = await serviceHelper.ensureServiceInstalled(BACKGROUND_SERVICE_OPTIONS);
|
||||
|
||||
// 仅在系统服务已接管时才停止本地后端,避免服务未运行时出现周期性停启抖动。
|
||||
if (status.running) {
|
||||
if (backendProcess) {
|
||||
await stopManagedBackend();
|
||||
backendReady = await isBackendReady();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!backendReady) {
|
||||
await serviceHelper.startService(BACKGROUND_SERVICE_OPTIONS);
|
||||
const startedStatus = await serviceHelper.getServiceStatus(BACKGROUND_SERVICE_OPTIONS);
|
||||
if (startedStatus.running && backendProcess) {
|
||||
await stopManagedBackend();
|
||||
backendReady = await isBackendReady();
|
||||
}
|
||||
}
|
||||
|
||||
// 服务未运行但本地后端可用时,保持本地后端运行,避免 UI 持续断开重连。
|
||||
return;
|
||||
} catch (error) {
|
||||
console.error('[Runtime] 系统服务启动失败,回退到本地后端:', error);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const status = await serviceHelper.getServiceStatus();
|
||||
const status = await serviceHelper.getServiceStatus(BACKGROUND_SERVICE_OPTIONS);
|
||||
if (status.installed) {
|
||||
await serviceHelper.uninstallService();
|
||||
await serviceHelper.uninstallService(BACKGROUND_SERVICE_OPTIONS);
|
||||
backendReady = await isBackendReady();
|
||||
}
|
||||
} catch (error) {
|
||||
@ -218,20 +239,30 @@ function loadMainPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
mainWindow.loadURL(MAIN_URL).catch(() => {
|
||||
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([
|
||||
{
|
||||
|
||||
9
electron/nsis-shortcuts.nsh
Normal file
9
electron/nsis-shortcuts.nsh
Normal file
@ -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
|
||||
13
index.js
13
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}`);
|
||||
});
|
||||
console.log(`后端已启动(仅 WS 模式),监听端口: ${app.config.wsPort}`);
|
||||
|
||||
export default app;
|
||||
38
package.json
38
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": "打印电脑服务"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
// 路由配置,只需写控制器类和方法名
|
||||
const routes = [
|
||||
{ method: 'GET', path: '/', controller: 'index.index' },
|
||||
];
|
||||
|
||||
export default routes
|
||||
142
scripts/deploy-linux.ps1
Normal file
142
scripts/deploy-linux.ps1
Normal file
@ -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"
|
||||
9
scripts/deploy.config.json
Normal file
9
scripts/deploy.config.json
Normal file
@ -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
|
||||
}
|
||||
9
scripts/deploy.config.local.example.json
Normal file
9
scripts/deploy.config.local.example.json
Normal file
@ -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
|
||||
}
|
||||
@ -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) {
|
||||
|
||||
544
services/update.js
Normal file
544
services/update.js
Normal file
@ -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();
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
}
|
||||
1067
views/index.html
1067
views/index.html
File diff suppressed because it is too large
Load Diff
32
开发日志/2026-03-29_HTTP迁出与静态页面说明.md
Normal file
32
开发日志/2026-03-29_HTTP迁出与静态页面说明.md
Normal file
@ -0,0 +1,32 @@
|
||||
# 2026-03-29 HTTP 迁出与静态页面说明
|
||||
|
||||
## 背景
|
||||
前端页面已迁移为 Electron 直接加载本地静态文件,不再依赖本地 HTTP 页面入口。
|
||||
|
||||
## 本次变更
|
||||
- 移除 Node HTTP 服务入口逻辑,`index.js` 改为仅初始化后端(WS 模式)。
|
||||
- 移除 `routes.js` 与 `controllers/` HTTP 路由/控制器链路。
|
||||
- 移除 `core/BaseController.js`(不再被使用)。
|
||||
- `core/main.js` 仅保留服务加载与 WS 服务能力,删除路由分发与控制器加载代码。
|
||||
- `electron/main.cjs` 删除静态页面加载失败后回退 `http://127.0.0.1:<port>/` 的逻辑,统一使用 `views/index.html`。
|
||||
- `package.json` 打包清单移除 `controllers/**/*` 与 `routes.js`。
|
||||
|
||||
## 运行行为变化
|
||||
- HTTP 端口不再承载页面路由服务(不再提供 `GET /`)。
|
||||
- 页面由 Electron 通过 `loadFile` 直接加载 `views/index.html`。
|
||||
- 前端业务交互仍通过本地 WS 端口与后端通信。
|
||||
|
||||
## 影响与兼容性
|
||||
- 依赖本地 HTTP 页面地址的外部访问方式将失效。
|
||||
- Electron 桌面内功能不受影响(已改为静态页面 + WS 调用)。
|
||||
|
||||
## 端口说明
|
||||
- `wsPort`:当前本地前后端通信主入口。
|
||||
- `port`:保留在配置中用于兼容与后续扩展,不再用于页面服务。
|
||||
|
||||
## 回退方式
|
||||
如需恢复 HTTP 页面访问:
|
||||
1. 恢复 `routes.js`、`controllers/`、`core/BaseController.js`。
|
||||
2. 恢复 `core/main.js` 的 `router` 与 `_loadControllers`。
|
||||
3. 恢复 `index.js` 的 `http.createServer` 监听逻辑。
|
||||
4. 恢复 `package.json` 打包清单中的 `controllers/**/*` 与 `routes.js`。
|
||||
45
评测报告.md
45
评测报告.md
@ -1,45 +0,0 @@
|
||||
# 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
|
||||
34
降低被杀软误报.todo
34
降低被杀软误报.todo
@ -1,30 +1,8 @@
|
||||
降低被杀软误报 TODO
|
||||
降低被杀软误报 TODO(暂缓)
|
||||
|
||||
目标:显著降低安装包与运行态被 Windows Defender/国产安全软件误报或拦截的概率。
|
||||
状态:暂不纳入当前计划(2026-03-29)
|
||||
|
||||
一、P0(优先)
|
||||
- [ ] 启用代码签名:为主程序 EXE、安装包 EXE、服务包装器 EXE 全量签名。
|
||||
- [ ] 打包流程接入签名步骤(npm scripts 固定入口),并在构建日志中输出签名结果。
|
||||
- [ ] 仅保留 NSIS 正式分发链路,关闭 IExpress 离线安装器默认分发。
|
||||
- [ ] 生产构建去除不必要的 ExecutionPolicy Bypass 与隐藏式 PowerShell 拉起。
|
||||
|
||||
二、P1(高优先)
|
||||
- [ ] 远程地址从 ws:// 切换到 wss://,补齐证书与连接失败回退提示。
|
||||
- [ ] 服务安装改为“明确用户确认 + 权限说明”,避免自动反复 install/uninstall。
|
||||
- [ ] 增加版本元数据与公司信息(ProductName/CompanyName/FileDescription)。
|
||||
- [ ] 统一发布包命名与版本留痕,保证每个版本可追溯、可回退。
|
||||
|
||||
三、P2(增强)
|
||||
- [ ] 发布前做多引擎样本扫描(Defender + 国产主流),记录误报结果。
|
||||
- [ ] 补充安装后自检页:端口、服务状态、远程连通性、打印组件连通性。
|
||||
- [ ] 输出“安全行为说明”文档,向用户说明后台常驻、端口监听、服务模式用途。
|
||||
|
||||
四、验收标准
|
||||
- [ ] Defender 首次安装与首次启动无拦截。
|
||||
- [ ] 360/火绒至少两款环境下安装与启动通过。
|
||||
- [ ] 服务注册/注销流程无误报中断。
|
||||
- [ ] 打包日志含签名与哈希信息,能追溯到具体版本。
|
||||
|
||||
五、备注
|
||||
- 固定发布入口:npm scripts。
|
||||
- 涉及本地敏感部署配置文件时,禁止纳入自动读取与日志输出范围。
|
||||
说明:
|
||||
- 本文件已清理为留档说明,不作为当前迭代执行清单。
|
||||
- 已完成的 P0 改造保留在代码中(签名流程、NSIS 分发收敛、Bypass 收敛)。
|
||||
- 后续若恢复计划,建议从“替换正式 CA 代码签名证书”开始。
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user