Release LanUps 0.1.2 with native installers and monitoring updates

This commit is contained in:
tongtong committed 2026-11-28 21:18:14 +08:00
1 parent 90c57f020f
commit 5bdc79d8e4
30 files changed
+751 -270

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
[Setup]
AppId=LanUps.Desktop
AppName=LanUps
AppVersion={#AppVersion}
VersionInfoVersion={#AppVersion}
AppPublisher=LanUps Project
DefaultDirName={code:DefaultInstallDirectory}
DefaultGroupName=LanUps
DisableWelcomePage=no
DisableDirPage=no
DisableProgramGroupPage=yes
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
PrivilegesRequired=admin
WizardStyle=modern
SetupIconFile=..\..\src\LanUps.Desktop\Assets\ups.ico
Compression=lzma2
SolidCompression=yes
UninstallDisplayIcon={app}\Desktop\LanUps.Desktop.exe
SetupLogging=yes
[Languages]
Name: "en"; MessagesFile: "compiler:Default.isl"
#ifdef ChineseMessages
Name: "zhcn"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
#endif
[Files]
Source: "deployment.ps1"; Flags: dontcopy
Source: "{#PayloadDir}\Agent\*"; DestDir: "{app}\Agent"; Excludes: "*.pdb,*.dbg"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#PayloadDir}\Desktop\*"; DestDir: "{app}\Desktop"; Excludes: "*.pdb,*.dbg"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "deployment.ps1"; DestDir: "{app}"; Flags: ignoreversion
Source: "install.ps1"; DestDir: "{app}"; Flags: ignoreversion
[Icons]
Name: "{autoprograms}\LanUps"; Filename: "{app}\Desktop\LanUps.Desktop.exe"; WorkingDir: "{app}\Desktop"
Name: "{autodesktop}\局域网 UPS"; Filename: "{app}\Desktop\LanUps.Desktop.exe"; WorkingDir: "{app}\Desktop"
[CustomMessages]
en.DeploymentFailed=LanUps service deployment failed. See %%ProgramData%%\LanUps\setup.log for details.
#ifdef ChineseMessages
zhcn.DeploymentFailed=LanUps 后台服务部署失败。详细信息见 %%ProgramData%%\LanUps\setup.log。
#endif
[Code]
function DefaultInstallDirectory(Param: String): String;
var
Command, Suffix: String;
Ending: Integer;
begin
Result := ExpandConstant('{autopf}\LanUps');
Suffix := '\Agent\LanUps.Agent.exe"';
if RegQueryStringValue(HKLM, 'SYSTEM\CurrentControlSet\Services\LanUps.Agent', 'ImagePath', Command) then
begin
Ending := Pos(Lowercase(Suffix), Lowercase(Command));
if (Ending > 4) and (Copy(Command, 1, 1) = '"') then
Result := Copy(Command, 2, Ending - 2);
end;
end;
function RunDeployment(const Script, Mode: String): Boolean;
var
Arguments, Operator: String;
ExitCode: Integer;
begin
Arguments := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + AddQuotes(Script) +
' -Mode ' + Mode + ' -AppRoot ' + AddQuotes(ExpandConstant('{app}'));
if Mode = 'Install' then
begin
Operator := ExpandConstant('{param:OPERATOR|}');
if (Pos('"', Operator) > 0) or (Pos(#13, Operator) > 0) or (Pos(#10, Operator) > 0) then
RaiseException('Invalid /OPERATOR value.');
if Operator <> '' then
Arguments := Arguments + ' -Operator ' + AddQuotes(Operator);
if ExpandConstant('{param:ENABLESHUTDOWN|0}') = '1' then
Arguments := Arguments + ' -EnableShutdown';
end;
ExitCode := -1;
Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
Arguments, ExpandConstant('{sys}'), SW_HIDE, ewWaitUntilTerminated, ExitCode);
Log(Format('LanUps deployment %s: launched=%d, code=%d', [Mode, Ord(Result), ExitCode]));
Result := Result and (ExitCode = 0);
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
Result := '';
ExtractTemporaryFile('deployment.ps1');
if not RunDeployment(ExpandConstant('{tmp}\deployment.ps1'), 'Prepare') then
Result := CustomMessage('DeploymentFailed');
end;
procedure CurStepChanged(CurStep: TSetupStep);
begin
if CurStep = ssPostInstall then
if not RunDeployment(ExpandConstant('{app}\deployment.ps1'), 'Install') then
RaiseException(CustomMessage('DeploymentFailed'));
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
if CurUninstallStep = usUninstall then
if not RunDeployment(ExpandConstant('{app}\deployment.ps1'), 'Uninstall') then
RaiseException(CustomMessage('DeploymentFailed'));
end;
-4
View File
@@ -1,4 +0,0 @@
@echo off
setlocal
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Setup.ps1" %*
if errorlevel 1 pause
-57
View File
@@ -1,57 +0,0 @@
param([string]$Operator = [Security.Principal.WindowsIdentity]::GetCurrent().Name, [switch]$EnableShutdown)
$ErrorActionPreference = 'Stop'
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (!([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
if ($Operator -match '["\r\n]') { throw 'Invalid operator account' }
$arguments = '-NoProfile -ExecutionPolicy Bypass -File "{0}" -Operator "{1}"' -f $PSCommandPath, $Operator
if ($EnableShutdown) { $arguments += ' -EnableShutdown' }
$process = Start-Process powershell.exe -Verb RunAs -ArgumentList $arguments -Wait -PassThru -WindowStyle Hidden
exit $process.ExitCode
}
$destination = Join-Path $env:ProgramFiles 'LanUps'
$logDirectory = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps'
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
$log = Join-Path $logDirectory 'setup.log'
Start-Transcript -Path $log -Append | Out-Null
try {
foreach ($kind in @('Agent', 'Desktop')) {
if (!(Test-Path -LiteralPath (Join-Path $PSScriptRoot "$kind\LanUps.$kind.exe") -PathType Leaf)) {
throw "Extract the entire installer archive before running Setup.cmd: missing $kind"
}
}
$service = Get-Service 'LanUps.Agent' -ErrorAction SilentlyContinue
if ($service -and $service.Status -ne 'Stopped') { Stop-Service $service }
$task = Get-ScheduledTask -TaskName 'LanUps Desktop' -ErrorAction SilentlyContinue
if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask $task }
$existingDesktop = Join-Path $destination 'Desktop\LanUps.Desktop.exe'
Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object Path -EQ $existingDesktop |
ForEach-Object { Stop-Process -Id $_.Id; $_.WaitForExit() }
foreach ($kind in @('Agent', 'Desktop')) {
$target = Join-Path $destination $kind
New-Item -ItemType Directory -Path $target -Force | Out-Null
Copy-Item -Path (Join-Path $PSScriptRoot "$kind\*") -Destination $target -Recurse -Force
}
& (Join-Path $PSScriptRoot 'install.ps1') -Operator $Operator -EnableShutdown:$EnableShutdown
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut((Join-Path ([Environment]::GetFolderPath('CommonDesktopDirectory')) '局域网 UPS.lnk'))
$shortcut.TargetPath = $existingDesktop
$shortcut.WorkingDirectory = (Split-Path -Parent $existingDesktop)
$shortcut.IconLocation = "$existingDesktop,0"
$shortcut.Save()
if ($identity.Name -ieq $Operator) {
$personalPath = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) '局域网 UPS.lnk'
if (Test-Path -LiteralPath $personalPath) {
$personal = $shell.CreateShortcut($personalPath)
if ((Split-Path -Leaf $personal.TargetPath) -ieq 'LanUps.Desktop.exe') {
$personal.TargetPath = $existingDesktop
$personal.WorkingDirectory = (Split-Path -Parent $existingDesktop)
$personal.IconLocation = "$existingDesktop,0"
$personal.Save()
}
}
}
Write-Host "Installed: $destination"
} finally { Stop-Transcript | Out-Null }
@@ -0,0 +1,147 @@
#Requires -RunAsAdministrator
param(
[Parameter(Mandatory)][ValidateSet('Prepare', 'Install', 'Uninstall')][string]$Mode,
[Parameter(Mandatory)][string]$AppRoot,
[string]$Operator,
[switch]$EnableShutdown
)
$ErrorActionPreference = 'Stop'
$serviceName = 'LanUps.Agent'
$taskName = 'LanUps Desktop'
$serviceKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\LanUps.Agent'
function Confirm-InstallDirectory([string]$Path) {
if ($Path -notmatch '^[A-Za-z]:\\[^"\r\n]+$' -or $Path.Substring(2).Contains(':')) {
throw 'Select a local installation directory.'
}
$fullPath = [IO.Path]::GetFullPath($Path).TrimEnd('\')
$root = [IO.Path]::GetPathRoot($fullPath)
if ($fullPath.Length -le 3 -or [IO.DriveInfo]::new($root).DriveType -ne 'Fixed') {
throw 'Select a directory on a fixed local disk.'
}
$admins = 'S-1-5-32-544'
$system = 'S-1-5-18'
$installer = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
$trusted = @($admins, $system, $installer)
$sidType = [Security.Principal.SecurityIdentifier]
$directoryAcl = [Security.AccessControl.DirectorySecurity]::new()
$directoryAcl.SetAccessRuleProtection($true, $false)
$directoryAcl.SetOwner($sidType::new($admins))
foreach ($account in $trusted[0..1]) {
$directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new($account), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
}
$directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new('S-1-5-32-545'), 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
function Assert-ProtectedItem($item, [bool]$volumeRoot) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Choose a directory without junctions or symbolic links: $($item.FullName)" }
$acl = Get-Acl -LiteralPath $item.FullName
if ($acl.GetOwner($sidType).Value -notin $trusted) { throw "The installation path must be owned by administrators or Windows: $($item.FullName)" }
# Volume roots can permit creating new folders, but must protect existing children.
$unsafeRights = if ($volumeRoot) { 0x100C0040 } else { 0x500D0156 }
foreach ($rule in $acl.GetAccessRules($true, $true, $sidType)) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $trusted -and
!($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and
($rule.FileSystemRights -band $unsafeRights)) {
throw "Ordinary users can modify this installation path: $($item.FullName)"
}
}
}
Assert-ProtectedItem (Get-Item -LiteralPath $root -Force) $true
$pathToCheck = $root
foreach ($part in $fullPath.Substring(3).Split('\')) {
$pathToCheck = Join-Path $pathToCheck $part
if (!(Test-Path -LiteralPath $pathToCheck)) { [void][IO.Directory]::CreateDirectory($pathToCheck, $directoryAcl) }
Assert-ProtectedItem (Get-Item -LiteralPath $pathToCheck -Force) $false
}
foreach ($kind in 'Agent', 'Desktop') {
$existing = Join-Path $fullPath $kind
if (Test-Path -LiteralPath $existing) {
Assert-ProtectedItem (Get-Item -LiteralPath $existing -Force) $false
Get-ChildItem -LiteralPath $existing -Recurse -Force | ForEach-Object { Assert-ProtectedItem $_ $false }
}
}
foreach ($filename in 'deployment.ps1', 'install.ps1') {
$file = Join-Path $fullPath $filename
if (Test-Path -LiteralPath $file) { Assert-ProtectedItem (Get-Item -LiteralPath $file -Force) $false }
}
return $fullPath
}
function Stop-LanUps {
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask -InputObject $task }
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -and $service.Status -ne 'Stopped') {
Stop-Service -InputObject $service
$service.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(30))
}
$oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$desktopPaths = @(Join-Path $AppRoot 'Desktop\LanUps.Desktop.exe')
if ($oldPath -match '^"([A-Za-z]:\\[^"]+)\\Agent\\LanUps\.Agent\.exe"(?:\s|$)') {
$desktopPaths += Join-Path $Matches[1] 'Desktop\LanUps.Desktop.exe'
}
Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object { $_.Path -in $desktopPaths } |
ForEach-Object {
Stop-Process -Id $_.Id -ErrorAction SilentlyContinue
if (!$_.WaitForExit(10000)) { throw "LanUps desktop process $($_.Id) did not stop" }
}
}
$distributionLog = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps\setup.log'
New-Item -ItemType Directory -Path (Split-Path -Parent $distributionLog) -Force | Out-Null
Start-Transcript -LiteralPath $distributionLog -Append | Out-Null
try {
switch ($Mode) {
'Prepare' {
$AppRoot = Confirm-InstallDirectory $AppRoot
Stop-LanUps
}
'Install' {
if (!$Operator) {
$sessionId = (Get-Process -Id $PID).SessionId
$shell = Get-CimInstance Win32_Process -Filter "Name='explorer.exe' AND SessionId=$sessionId" | Select-Object -First 1
if ($shell) {
$owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwner
if (!$owner.ReturnValue -and $owner.User) { $Operator = "$($owner.Domain)\$($owner.User)" }
}
if (!$Operator) {
$Operator = (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue).Principal.UserId
}
if (!$Operator) {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if ($identity.IsSystem) { throw 'Specify /OPERATOR="DOMAIN\User" when running unattended as SYSTEM.' }
$Operator = $identity.Name
}
}
$oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$enable = $EnableShutdown -or $oldPath -match '(?i)\s--enable-shutdown\s*$'
& (Join-Path $PSScriptRoot 'install.ps1') -AppRoot $AppRoot -Operator $Operator -EnableShutdown:$enable
}
'Uninstall' {
$registered = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$expected = '"' + (Join-Path $AppRoot 'Agent\LanUps.Agent.exe') + '"'
if ($registered -and $registered -ine $expected -and $registered -ine "$expected --enable-shutdown") { break }
Stop-LanUps
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task) { Unregister-ScheduledTask -InputObject $task -Confirm:$false }
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
& (Join-Path $env:SystemRoot 'System32\sc.exe') delete $serviceName
if ($LASTEXITCODE) { throw "Could not remove $serviceName service." }
}
}
}
} catch {
Write-Host ($_ | Out-String)
throw
} finally {
Stop-Transcript | Out-Null
if ($Operator) {
try {
$account = [Security.Principal.NTAccount]::new($Operator)
$acl = Get-Acl -LiteralPath $distributionLog
$acl.SetAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account, 'Read', 'Allow'))
Set-Acl -LiteralPath $distributionLog -AclObject $acl
} catch { Write-Warning "Unable to grant access to the setup log: $($_.Exception.Message)" }
}
}
+37 -1
View File
@@ -1,11 +1,11 @@
#Requires -RunAsAdministrator
param(
[Parameter(Mandatory)][string]$Operator,
[string]$AppRoot = (Join-Path $env:ProgramFiles 'LanUps'),
[switch]$EnableShutdown
)
$ErrorActionPreference = 'Stop'
$appRoot = Join-Path $env:ProgramFiles 'LanUps'
$agent = Join-Path $appRoot 'Agent\LanUps.Agent.exe'
$desktop = Join-Path $appRoot 'Desktop\LanUps.Desktop.exe'
foreach ($app in @($agent, $desktop)) {
@@ -47,8 +47,44 @@ if ($installed) {
} else {
New-Service -Name 'LanUps.Agent' -BinaryPathName $command -DisplayName 'LAN UPS Agent' -StartupType Automatic | Out-Null
}
$sc = Join-Path $env:SystemRoot 'System32\sc.exe'
& $sc failure 'LanUps.Agent' reset= 86400 actions= 'restart/5000/restart/15000/restart/60000'
if ($LASTEXITCODE) { throw 'Cannot configure Agent service recovery' }
& $sc failureflag 'LanUps.Agent' 1
if ($LASTEXITCODE) { throw 'Cannot enable Agent service recovery' }
Start-Service -Name 'LanUps.Agent'
# The SCM can report Running before Kestrel is listening.
Add-Type -AssemblyName System.Net.Http
$handler = [Net.Http.HttpClientHandler]::new()
$handler.UseProxy = $false
$client = [Net.Http.HttpClient]::new($handler)
$client.Timeout = [TimeSpan]::FromSeconds(2)
$port = 47183
$configuredPort = 0
$machinePort = [Environment]::GetEnvironmentVariable('LANUPS_AGENT_PORT', 'Machine')
if ([int]::TryParse($machinePort, [ref]$configuredPort) -and $configuredPort -in 1..65535) { $port = $configuredPort }
$address = "http://127.0.0.1:$port/status"
$client.DefaultRequestHeaders.Add('X-LanUps-Token', [IO.File]::ReadAllText($token).Trim())
$deadline = [DateTime]::UtcNow.AddSeconds(25)
$ready = $false
try {
do {
try {
$status = $client.GetStringAsync($address).GetAwaiter().GetResult() | ConvertFrom-Json
if (!$status.endpoint -or !$status.update) { throw 'Unexpected Agent status response' }
$ready = $true
} catch {
$reason = $_.Exception.GetBaseException().Message
Start-Sleep -Milliseconds 300
}
} until ($ready -or [DateTime]::UtcNow -ge $deadline)
} finally { $client.Dispose() }
if (!$ready) {
$state = (Get-Service 'LanUps.Agent').Status
throw "Agent service did not respond at $address (service state: $state). $reason"
}
$action = New-ScheduledTaskAction -Execute $desktop -Argument '--tray' -WorkingDirectory (Split-Path -Parent $desktop)
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $Operator
$principal = New-ScheduledTaskPrincipal -UserId $Operator -LogonType Interactive -RunLevel Limited