From 67a043c89b3ea06e6a847bb795ddadf5b31dc3cb Mon Sep 17 00:00:00 2001 From: TongTongStudio Date: Sat, 28 Nov 2026 16:26:39 +0800 Subject: [PATCH] Initial LanUps implementation and native installers --- .gitattributes | 8 + .gitignore | 4 + README.md | 30 ++ desktop/LanUps.slnx | 5 + desktop/README.md | 61 ++++ desktop/deploy/linux/lanups-agent.service | 14 + desktop/deploy/linux/lanups-desktop.desktop | 5 + desktop/deploy/linux/postinst | 23 ++ desktop/deploy/linux/postrm | 3 + desktop/deploy/linux/prerm | 6 + desktop/deploy/linux/start-desktop | 3 + desktop/deploy/macos/local.lanups.agent.plist | 11 + .../deploy/macos/local.lanups.desktop.plist | 8 + desktop/deploy/macos/postinstall | 24 ++ desktop/deploy/macos/preinstall | 8 + desktop/deploy/native/macos/go.mod | 5 + desktop/deploy/native/macos/go.sum | 16 + desktop/deploy/native/macos/main.go | 69 ++++ desktop/deploy/native/windows/main.go | 77 +++++ desktop/deploy/native_packages.py | 197 +++++++++++ desktop/deploy/package.ps1 | 40 +++ desktop/deploy/package.py | 98 ++++++ desktop/deploy/router/control | 8 + desktop/deploy/router/install.sh | 121 +++++++ desktop/deploy/router/lanups-fsd.init | 11 + desktop/deploy/router/lanups-hotplug | 15 + desktop/deploy/router/lanups-policy | 42 +++ desktop/deploy/router/lanups-router | 4 + desktop/deploy/router/postinst | 8 + desktop/deploy/router/prerm | 8 + desktop/deploy/unix/install.sh | 100 ++++++ desktop/deploy/windows/Setup.cmd | 4 + desktop/deploy/windows/Setup.ps1 | 57 ++++ desktop/deploy/windows/install.ps1 | 56 ++++ desktop/src/LanUps.Agent/Coordinator.cs | 204 ++++++++++++ desktop/src/LanUps.Agent/LanUps.Agent.csproj | 13 + desktop/src/LanUps.Agent/LinkerRoots.xml | 7 + desktop/src/LanUps.Agent/Program.cs | 77 +++++ desktop/src/LanUps.Core/AgentClient.cs | 43 +++ desktop/src/LanUps.Core/AgentJson.cs | 11 + desktop/src/LanUps.Core/LanUps.Core.csproj | 3 + desktop/src/LanUps.Core/NutMonitor.cs | 130 ++++++++ desktop/src/LanUps.Desktop/App.axaml | 19 ++ desktop/src/LanUps.Desktop/App.axaml.cs | 29 ++ desktop/src/LanUps.Desktop/Assets/ups.ico | Bin 0 -> 10012 bytes desktop/src/LanUps.Desktop/Assets/ups.png | Bin 0 -> 4129 bytes desktop/src/LanUps.Desktop/CloseDialog.axaml | 15 + .../src/LanUps.Desktop/CloseDialog.axaml.cs | 34 ++ desktop/src/LanUps.Desktop/DesktopSettings.cs | 75 +++++ .../src/LanUps.Desktop/LanUps.Desktop.csproj | 13 + desktop/src/LanUps.Desktop/MainWindow.axaml | 83 +++++ .../src/LanUps.Desktop/MainWindow.axaml.cs | 306 ++++++++++++++++++ desktop/src/LanUps.Desktop/Program.cs | 9 + .../src/LanUps.Desktop/ShutdownDialog.axaml | 13 + .../LanUps.Desktop/ShutdownDialog.axaml.cs | 73 +++++ desktop/tests/agent_integration.py | 125 +++++++ desktop/tests/desktop_smoke.py | 94 ++++++ docs/lede.md | 10 + docs/roadmap.md | 18 ++ go.mod | 3 + internal/monitor/monitor.go | 54 ++++ internal/nut/client.go | 61 ++++ internal/nut/client_test.go | 47 +++ internal/web/handler.go | 27 ++ internal/web/static/index.html | 89 +++++ main.go | 36 +++ 66 files changed, 2870 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 README.md create mode 100644 desktop/LanUps.slnx create mode 100644 desktop/README.md create mode 100644 desktop/deploy/linux/lanups-agent.service create mode 100644 desktop/deploy/linux/lanups-desktop.desktop create mode 100644 desktop/deploy/linux/postinst create mode 100644 desktop/deploy/linux/postrm create mode 100644 desktop/deploy/linux/prerm create mode 100644 desktop/deploy/linux/start-desktop create mode 100644 desktop/deploy/macos/local.lanups.agent.plist create mode 100644 desktop/deploy/macos/local.lanups.desktop.plist create mode 100644 desktop/deploy/macos/postinstall create mode 100644 desktop/deploy/macos/preinstall create mode 100644 desktop/deploy/native/macos/go.mod create mode 100644 desktop/deploy/native/macos/go.sum create mode 100644 desktop/deploy/native/macos/main.go create mode 100644 desktop/deploy/native/windows/main.go create mode 100644 desktop/deploy/native_packages.py create mode 100644 desktop/deploy/package.ps1 create mode 100644 desktop/deploy/package.py create mode 100644 desktop/deploy/router/control create mode 100644 desktop/deploy/router/install.sh create mode 100644 desktop/deploy/router/lanups-fsd.init create mode 100644 desktop/deploy/router/lanups-hotplug create mode 100644 desktop/deploy/router/lanups-policy create mode 100644 desktop/deploy/router/lanups-router create mode 100644 desktop/deploy/router/postinst create mode 100644 desktop/deploy/router/prerm create mode 100644 desktop/deploy/unix/install.sh create mode 100644 desktop/deploy/windows/Setup.cmd create mode 100644 desktop/deploy/windows/Setup.ps1 create mode 100644 desktop/deploy/windows/install.ps1 create mode 100644 desktop/src/LanUps.Agent/Coordinator.cs create mode 100644 desktop/src/LanUps.Agent/LanUps.Agent.csproj create mode 100644 desktop/src/LanUps.Agent/LinkerRoots.xml create mode 100644 desktop/src/LanUps.Agent/Program.cs create mode 100644 desktop/src/LanUps.Core/AgentClient.cs create mode 100644 desktop/src/LanUps.Core/AgentJson.cs create mode 100644 desktop/src/LanUps.Core/LanUps.Core.csproj create mode 100644 desktop/src/LanUps.Core/NutMonitor.cs create mode 100644 desktop/src/LanUps.Desktop/App.axaml create mode 100644 desktop/src/LanUps.Desktop/App.axaml.cs create mode 100644 desktop/src/LanUps.Desktop/Assets/ups.ico create mode 100644 desktop/src/LanUps.Desktop/Assets/ups.png create mode 100644 desktop/src/LanUps.Desktop/CloseDialog.axaml create mode 100644 desktop/src/LanUps.Desktop/CloseDialog.axaml.cs create mode 100644 desktop/src/LanUps.Desktop/DesktopSettings.cs create mode 100644 desktop/src/LanUps.Desktop/LanUps.Desktop.csproj create mode 100644 desktop/src/LanUps.Desktop/MainWindow.axaml create mode 100644 desktop/src/LanUps.Desktop/MainWindow.axaml.cs create mode 100644 desktop/src/LanUps.Desktop/Program.cs create mode 100644 desktop/src/LanUps.Desktop/ShutdownDialog.axaml create mode 100644 desktop/src/LanUps.Desktop/ShutdownDialog.axaml.cs create mode 100644 desktop/tests/agent_integration.py create mode 100644 desktop/tests/desktop_smoke.py create mode 100644 docs/lede.md create mode 100644 docs/roadmap.md create mode 100644 go.mod create mode 100644 internal/monitor/monitor.go create mode 100644 internal/nut/client.go create mode 100644 internal/nut/client_test.go create mode 100644 internal/web/handler.go create mode 100644 internal/web/static/index.html create mode 100644 main.go diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f1c7760 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +* text=auto +desktop/deploy/linux/** text eol=lf +desktop/deploy/macos/** text eol=lf +desktop/deploy/router/** text eol=lf +*.sh text eol=lf +*.cmd text eol=crlf +*.ico binary +*.png binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1bbf9e3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/.dotnet/ +/artifacts/ +**/bin/ +**/obj/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..ae71ec3 --- /dev/null +++ b/README.md @@ -0,0 +1,30 @@ +# 局域网 UPS + +雷迪司 H1000M 通过 USB 连接 LEDE 路由器。路由器运行 NUT 服务端,自研监控通过 `192.168.5.1:3493` 获取状态,并在浏览器内显示。 + +## 运行监控 + +在本目录使用 Go 1.22 或更新版本运行: + +```sh +go run . -nut 192.168.5.1:3493 -ups h1000m +``` + +打开 `http://127.0.0.1:8080`。程序默认每次查询结束后等待 3 秒再轮询,可用 `-interval 5s` 调整。断线期间页面会标明最后一次成功读取的时间,恢复后自动显示新数据。该版本提供只读监控,自动关机可由设备侧已有的 UPS 客户端负责。 + +部署到 Windows 或 NAS 可先运行 `go build .` 生成当前平台的单文件程序。需要从其他局域网设备访问时,使用 `-listen <本机局域网IP>:8080`。页面没有登录功能,适合在受信任的局域网使用。 + +## 目录 + +| 路径 | 职责 | +| --- | --- | +| `main.go` | 启动参数、应用入口 | +| `internal/nut/` | NUT 协议客户端及测试 | +| `internal/monitor/` | 轮询、历史读数和连接状态 | +| `internal/web/` | HTTP 接口和嵌入式网页 | +| `desktop/` | Avalonia + Semi 桌面客户端、NUT 客户端库和后台程序 | +| `docs/` | 部署与进度说明 | + +- [LEDE 路由器部署](docs/lede.md) +- [真机验证与群晖评估排程](docs/roadmap.md) +- [桌面端构建与关闭行为](desktop/README.md) diff --git a/desktop/LanUps.slnx b/desktop/LanUps.slnx new file mode 100644 index 0000000..f4aed33 --- /dev/null +++ b/desktop/LanUps.slnx @@ -0,0 +1,5 @@ + + + + + diff --git a/desktop/README.md b/desktop/README.md new file mode 100644 index 0000000..864170b --- /dev/null +++ b/desktop/README.md @@ -0,0 +1,61 @@ +# 局域网 UPS 桌面端与系统服务 + +Agent 连接 LEDE 上的 NUT,负责轮询、保存服务器配置和处理 `FSD`。Avalonia + Semi 桌面端通过本机 `127.0.0.1:47183` 与 Agent 通信,显示读数、发现 UPS、保存设置并响应关机提醒。接口需要本机凭据文件 `agent.token`,桌面用户只需读取凭据。桌面退出后,系统服务继续工作。 + +## 关机确认 + +Agent 收到有效的 `FSD` 后开始 60 秒倒计时。已登录用户的桌面程序会从托盘弹出确认框,可立即关机或取消本次。如果用户没有响应,Agent 到时执行关机。通信中断不会触发新的关机;已经收到的关机信号仍按原截止时间处理。截止时间和已处理状态保存在 Agent 本机,便于服务重启后恢复进度并避免同一持续信号重复发起关机。 + +Agent 默认运行模拟模式。以 `--enable-shutdown` 启动才执行系统关机程序。系统服务需要相应权限。若尚无人登录,弹窗无法显示,Agent 仍会执行后台策略。 + +LEDE 上的 `upsd` 发布读数。要在真实停电时发布 `FSD`,可启用路由器安装器的低电量策略,或手动配置 NUT 主监控。Agent 通过轮询读取 `FSD`。若另有系统负责切断 UPS 输出,应预留至少 60 秒加设备关机所需时间,确保倒计时能完成。 + +设置页支持「更新」发现 NUT 名称,还可配置关闭窗口行为。桌面状态日志和关机弹窗事件会写入桌面用户日志。Agent 自身的后台事件写入服务日志,由各平台的服务管理器收集。 + +## 开发联调 + +使用 .NET 10 SDK。先为两个进程设置同一个 `LANUPS_AGENT_TOKEN` 环境变量,指向当前用户私有目录中的绝对文件路径。在同一个环境执行: + +```sh +dotnet run --project src/LanUps.Agent -- --provision +dotnet run --project src/LanUps.Agent +``` + +在另一个继承同样环境变量的终端运行 `dotnet run --project src/LanUps.Desktop`。凭据只需生成一次。联调可保留模拟模式和默认 NUT 地址 `192.168.5.1:3493`,实际验证关机弹窗时使用隔离的模拟 NUT 服务。 + +## 发布与开机自启 + +### 安装包 + +项目根目录下的 `artifacts/native-installers-optimized/` 包含精简版原生安装包及 `SHA256SUMS`。Linux 使用 Native AOT,Windows 和 macOS 使用裁剪后的自包含发布。目标设备均无需单独安装 .NET。旧安装包保留在 `artifacts/native-installers/`。 + +### 构建精简版 + +在已安装目标平台工具链的**构建机**上运行 `desktop/deploy/package.ps1 -Mode Aot -Targets `,或者通过 `dotnet publish -c Release -r --self-contained true -p:PublishAot=true -p:OptimizationPreference=Size` 分别发布 Agent 和 Desktop。Windows 需要 MSVC 原生链接工具,macOS 需要 Xcode 命令行工具,Linux 需要 Clang 和对应架构的系统库。用 `-Mode Trimmed` 可构建同样无需外置运行时的裁剪版本。把各目标的发布结果分别放在 `artifacts/installer-payload-optimized//Agent` 和 `Desktop` 后,运行 `desktop/deploy/package.ps1 -Mode Pack` 可一次打包所有平台。DEB 会从实际 ELF 产物记录最低 glibc 版本。 + +| 平台 | 安装入口 | 自动配置 | +| --- | --- | --- | +| OpenWrt / LEDE | `opkg install ./lanups-router_0.1.0-1_all.ipk` | 安装 NUT 依赖,安装后配置 H1000M、LAN 监听和服务自启。UPS 暂不可读时,在下一次 USB 接入时自动重试 | +| Windows x64 | 双击 `LanUps-Setup-win-x64.exe` 并确认管理员提示 | 安装到 Program Files,注册 Windows 服务、自启任务和桌面快捷方式 | +| Debian / Ubuntu x64 或 ARM64 | 用软件安装器打开 `.deb`,或用 `sudo apt install ./lanups_0.1.0-1_<架构>.deb` | 安装后启用 systemd 服务和应用启动项,授权桌面账户读取本机凭据。首次安装后重新登录使用户组生效 | +| macOS Intel / Apple Silicon | 双击对应架构的 `.pkg`,由 macOS 安装器运行安装流程 | 安装 `.app` 和 LaunchDaemon,并为当前已登录用户配置 LaunchAgent。发布包未签名或公证 | + +首次安装默认模拟关机。确认流程后,Windows 可用 `-EnableShutdown` 重新运行 EXE,Linux 和 macOS 可通过服务配置加 `--enable-shutdown`。路由器执行 `lanups-router --enable-fsd` 才启用低电量联动。该模式只在读到 `OB` 和 `LB` 时发布 `FSD`,通信中断不会发布。策略不会主动关闭路由器或切断 UPS 输出。若 UPS 已发出 `FSD`,市电持续恢复约两分钟后,策略会重启 NUT 服务清除锁存状态。启用前应确认电池剩余时间足够覆盖客户端的 60 秒倒计时和关机时间。 + +### 手动部署 + +使用 `dotnet publish <项目路径> -c Release -r --self-contained true -o <输出目录>` 分别发布 `src/LanUps.Agent` 和 `src/LanUps.Desktop`。Windows x64 用 `win-x64`,Linux x64 用 `linux-x64`,Apple Silicon 用 `osx-arm64`,Intel Mac 用 `osx-x64`。将系统服务的二进制和配置放到普通用户不可写的目录。 + +### Windows + +以管理员身份将发布目录分别放入 `%ProgramFiles%\LanUps\Agent` 和 `%ProgramFiles%\LanUps\Desktop`,然后运行 `deploy/windows/install.ps1 -Operator '<计算机名>\<桌面账号>'`。脚本为指定桌面用户授予本机凭据读取权限,注册自动启动的 Windows 服务,并创建登录时启动托盘程序的计划任务。确认模拟流程后,可在初次注册时另加 `-EnableShutdown`,或在停止服务后把服务启动参数改为 `--enable-shutdown` 再启动。后台日志可在事件查看器中查看,并可按需调整 Windows 事件日志级别。 + +### Linux + +以管理员身份把发布目录放入 `/opt/lanups/agent` 和 `/opt/lanups/desktop`,用 `/opt/lanups/agent/LanUps.Agent --provision` 生成 `/etc/LanUps/agent.token`。将凭据的组设为获准操作的用户组并设为 `0640`。目录、其他配置与程序文件由 root 管理。把 `deploy/linux/lanups-agent.service` 放入 `/etc/systemd/system/` 后运行 `systemctl daemon-reload` 和 `systemctl enable --now lanups-agent`。将 `deploy/linux/lanups-desktop.desktop` 放入桌面用户的 `~/.config/autostart/`。需要启用真实关机时,在 systemd 的 `ExecStart` 后加 `--enable-shutdown` 并重启服务。查看后台日志可用 `journalctl -u lanups-agent`。 + +### macOS + +以管理员身份把发布目录放入 `/usr/local/libexec/lanups/agent` 和 `/usr/local/libexec/lanups/desktop`,运行 `/usr/local/libexec/lanups/agent/LanUps.Agent --provision`。本机凭据位于 `/Library/Application Support/LanUps/agent.token`,应只给指定桌面用户或授权组读取权限。将 `deploy/macos/local.lanups.agent.plist` 安装到 `/Library/LaunchDaemons/`,由 root 管理,再以系统域加载。将 `deploy/macos/local.lanups.desktop.plist` 安装到桌面用户的 `~/Library/LaunchAgents/`,由该用户在登录会话加载。需要启用真实关机时,在后台 LaunchDaemon 的 `ProgramArguments` 中追加 `--enable-shutdown` 并重载。跨平台发布产物要在目标版本上验收登录启动、权限和通知表现。 + +[Go 网页监控仍可独立运行](../README.md)。 diff --git a/desktop/deploy/linux/lanups-agent.service b/desktop/deploy/linux/lanups-agent.service new file mode 100644 index 0000000..df623eb --- /dev/null +++ b/desktop/deploy/linux/lanups-agent.service @@ -0,0 +1,14 @@ +[Unit] +Description=LAN UPS Agent +After=network-online.target +Wants=network-online.target + +[Service] +Type=exec +ExecStart=/opt/lanups/agent/LanUps.Agent +Restart=on-failure +RestartSec=5 +UMask=0077 + +[Install] +WantedBy=multi-user.target diff --git a/desktop/deploy/linux/lanups-desktop.desktop b/desktop/deploy/linux/lanups-desktop.desktop new file mode 100644 index 0000000..12fb614 --- /dev/null +++ b/desktop/deploy/linux/lanups-desktop.desktop @@ -0,0 +1,5 @@ +[Desktop Entry] +Type=Application +Name=局域网 UPS +Exec=/opt/lanups/desktop/LanUps.Desktop --tray +Terminal=false diff --git a/desktop/deploy/linux/postinst b/desktop/deploy/linux/postinst new file mode 100644 index 0000000..2889d1c --- /dev/null +++ b/desktop/deploy/linux/postinst @@ -0,0 +1,23 @@ +#!/bin/sh +set -eu +[ "${1:-}" = configure ] || exit 0 +data=/etc/LanUps +token=$data/agent.token +group=lanups-operators +install -d -m 0755 -o root -g root "$data" +getent group "$group" >/dev/null || groupadd --system "$group" +if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /opt/lanups/agent/LanUps.Agent --provision; fi +chown root:"$group" "$token" +chmod 0640 "$token" + +operator=${SUDO_USER:-} +if [ -z "$operator" ] || [ "$operator" = root ]; then operator=$(getent passwd 1000 | cut -d: -f1); fi +if [ -n "$operator" ] && [ "$(id -u "$operator")" -ge 1000 ]; then usermod -a -G "$group" "$operator"; fi + +if command -v systemctl >/dev/null; then + systemctl enable lanups-agent.service + if [ -d /run/systemd/system ]; then + systemctl daemon-reload + deb-systemd-invoke restart lanups-agent.service + fi +fi diff --git a/desktop/deploy/linux/postrm b/desktop/deploy/linux/postrm new file mode 100644 index 0000000..f545b8f --- /dev/null +++ b/desktop/deploy/linux/postrm @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +if [ -d /run/systemd/system ] && command -v systemctl >/dev/null; then systemctl daemon-reload; fi diff --git a/desktop/deploy/linux/prerm b/desktop/deploy/linux/prerm new file mode 100644 index 0000000..252a639 --- /dev/null +++ b/desktop/deploy/linux/prerm @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +if [ "${1:-}" = remove ] && command -v systemctl >/dev/null; then + if [ -d /run/systemd/system ]; then deb-systemd-invoke stop lanups-agent.service || :; fi + systemctl disable lanups-agent.service || : +fi diff --git a/desktop/deploy/linux/start-desktop b/desktop/deploy/linux/start-desktop new file mode 100644 index 0000000..be193b6 --- /dev/null +++ b/desktop/deploy/linux/start-desktop @@ -0,0 +1,3 @@ +#!/bin/sh +[ -r /etc/LanUps/agent.token ] || exit 0 +exec /opt/lanups/desktop/LanUps.Desktop --tray diff --git a/desktop/deploy/macos/local.lanups.agent.plist b/desktop/deploy/macos/local.lanups.agent.plist new file mode 100644 index 0000000..d757d68 --- /dev/null +++ b/desktop/deploy/macos/local.lanups.agent.plist @@ -0,0 +1,11 @@ + + + + Labellocal.lanups.agent + ProgramArguments/usr/local/libexec/lanups/agent/LanUps.Agent + RunAtLoad + Umask63 + KeepAliveSuccessfulExit + StandardOutPath/var/log/lanups-agent.log + StandardErrorPath/var/log/lanups-agent-error.log + diff --git a/desktop/deploy/macos/local.lanups.desktop.plist b/desktop/deploy/macos/local.lanups.desktop.plist new file mode 100644 index 0000000..fcdcc57 --- /dev/null +++ b/desktop/deploy/macos/local.lanups.desktop.plist @@ -0,0 +1,8 @@ + + + + Labellocal.lanups.desktop + ProgramArguments/Applications/LanUps.app/Contents/MacOS/LanUps.Desktop--tray + RunAtLoad + LimitLoadToSessionTypeAqua + diff --git a/desktop/deploy/macos/postinstall b/desktop/deploy/macos/postinstall new file mode 100644 index 0000000..f06a24e --- /dev/null +++ b/desktop/deploy/macos/postinstall @@ -0,0 +1,24 @@ +#!/bin/sh +set -eu +data='/Library/Application Support/LanUps' +token="$data/agent.token" +install -d -m 0755 -o root -g wheel "$data" +if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /usr/local/libexec/lanups/agent/LanUps.Agent --provision; fi +chmod 0600 "$token" + +user=$(/usr/bin/stat -f '%Su' /dev/console) +case "$user" in root|loginwindow|_mbsetupuser|'') user='';; esac +if [ -n "$user" ]; then + uid=$(id -u "$user") + home=$(/usr/bin/dscl . -read "/Users/$user" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //') + case "$home" in /*) ;; *) echo 'Cannot determine the desktop account home' >&2; exit 1;; esac + chmod -N "$token" + chmod +a "user:$user allow read" "$token" + sudo -u "$user" mkdir -p "$home/Library/LaunchAgents" + sudo -u "$user" install -m 0644 /usr/local/libexec/lanups/local.lanups.desktop.plist "$home/Library/LaunchAgents/local.lanups.desktop.plist" +fi + +launchctl bootstrap system /Library/LaunchDaemons/local.lanups.agent.plist +if [ -n "$user" ] && launchctl print "gui/$uid" >/dev/null 2>&1; then + launchctl bootstrap "gui/$uid" "$home/Library/LaunchAgents/local.lanups.desktop.plist" +fi diff --git a/desktop/deploy/macos/preinstall b/desktop/deploy/macos/preinstall new file mode 100644 index 0000000..4b8edbc --- /dev/null +++ b/desktop/deploy/macos/preinstall @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +[ "${3:-/}" = / ] || { echo 'Install LanUps onto the running macOS system volume.' >&2; exit 1; } +if launchctl print system/local.lanups.agent >/dev/null 2>&1; then launchctl bootout system/local.lanups.agent; fi +user=$(/usr/bin/stat -f '%Su' /dev/console) +case "$user" in root|loginwindow|_mbsetupuser|'') exit 0;; esac +uid=$(id -u "$user") +if launchctl print "gui/$uid/local.lanups.desktop" >/dev/null 2>&1; then launchctl bootout "gui/$uid/local.lanups.desktop"; fi diff --git a/desktop/deploy/native/macos/go.mod b/desktop/deploy/native/macos/go.mod new file mode 100644 index 0000000..803a894 --- /dev/null +++ b/desktop/deploy/native/macos/go.mod @@ -0,0 +1,5 @@ +module lan-ups-macos-packager + +go 1.26.4 + +require go.digitalxero.dev/osx v0.3.0 diff --git a/desktop/deploy/native/macos/go.sum b/desktop/deploy/native/macos/go.sum new file mode 100644 index 0000000..42ada63 --- /dev/null +++ b/desktop/deploy/native/macos/go.sum @@ -0,0 +1,16 @@ +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/github/smimesign v0.2.0 h1:Hho4YcX5N1I9XNqhq0fNx0Sts8MhLonHd+HRXVGNjvk= +github.com/github/smimesign v0.2.0/go.mod h1:iZiiwNT4HbtGRVqCQu7uJPEZCuEE5sfSSttcnePkDl4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.digitalxero.dev/osx v0.3.0 h1:PwlFuyUEcT5/4HxHAf1DjHaCRZuVcrQkC7W0yvL8k8E= +go.digitalxero.dev/osx v0.3.0/go.mod h1:RndPJgzpTmsGwHBK6mU9KmQq5F+YgPHn/FjETzvc230= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +software.sslmate.com/src/go-pkcs12 v0.7.0 h1:Db8W44cB54TWD7stUFFSWxdfpdn6fZVcDl0w3R4RVM0= +software.sslmate.com/src/go-pkcs12 v0.7.0/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI= diff --git a/desktop/deploy/native/macos/main.go b/desktop/deploy/native/macos/main.go new file mode 100644 index 0000000..5950207 --- /dev/null +++ b/desktop/deploy/native/macos/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "io/fs" + "log" + "os" + "path/filepath" + "strings" + + "go.digitalxero.dev/osx/pkg" +) + +func main() { + if len(os.Args) != 6 { + log.Fatal("usage: macpack payload preinstall postinstall architecture output.pkg") + } + root, prePath, postPath, architecture, output := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5] + if architecture != pkg.ArchARM64 && architecture != pkg.ArchX8664 { + log.Fatal("invalid macOS architecture") + } + pre, err := os.ReadFile(prePath) + check(err) + post, err := os.ReadFile(postPath) + check(err) + component := pkg.NewPackage().WithIdentifier("local.lanups").WithName("LanUps").WithVersion("0.1.0"). + WithPreInstallScript(pre).WithPostInstallScript(post) + check(filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + relative, err := filepath.Rel(root, path) + if err != nil { + return err + } + name := filepath.ToSlash(relative) + mode := fs.FileMode(0o644) + if strings.HasSuffix(name, "/LanUps.Agent") || strings.HasSuffix(name, "/LanUps.Desktop") { + mode = 0o755 + } + component.WithFileFromPath("/"+name, path).WithMode(mode).Add() + return nil + })) + product, err := pkg.NewProduct().WithTitle("LanUps").WithIdentifier("local.lanups.product").WithVersion("0.1.0"). + WithHostArchitectures(architecture).WithMinOSVersion("15.0").WithComponent(component).Build() + check(err) + file, err := os.Create(output) + check(err) + _, err = product.WriteTo(file) + check(err) + check(file.Close()) + + file, err = os.Open(output) + check(err) + defer file.Close() + info, err := file.Stat() + check(err) + archive, err := pkg.Open(file, info.Size()) + check(err) + check(archive.Verify()) + installed, err := archive.Component("local.lanups") + check(err) + check(installed.Verify()) +} + +func check(err error) { + if err != nil { + log.Fatal(err) + } +} diff --git a/desktop/deploy/native/windows/main.go b/desktop/deploy/native/windows/main.go new file mode 100644 index 0000000..8dca24b --- /dev/null +++ b/desktop/deploy/native/windows/main.go @@ -0,0 +1,77 @@ +//go:build windows + +package main + +import ( + "archive/zip" + "fmt" + "io" + "io/fs" + "os" + "os/exec" + "path/filepath" +) + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "LanUps installation failed:", err) + os.Exit(1) + } +} + +func run() error { + self, err := os.Executable() + if err != nil { + return err + } + archive, err := zip.OpenReader(self) + if err != nil { + return err + } + defer archive.Close() + stage, err := os.MkdirTemp("", "LanUps-Setup-") + if err != nil { + return err + } + defer os.RemoveAll(stage) + for _, entry := range archive.File { + path := filepath.FromSlash(entry.Name) + if !fs.ValidPath(entry.Name) || !filepath.IsLocal(path) || !entry.Mode().IsRegular() { + return fmt.Errorf("invalid installer entry: %q", entry.Name) + } + if err := extract(filepath.Join(stage, path), entry); err != nil { + return err + } + } + if len(os.Args) == 2 && os.Args[1] == "--verify" { + fmt.Printf("Verified %d installer files\n", len(archive.File)) + return nil + } + setup := filepath.Join(stage, "Setup.ps1") + args := append([]string{"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", setup}, os.Args[1:]...) + powershell := filepath.Join(os.Getenv("SystemRoot"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe") + command := exec.Command(powershell, args...) + command.Stdout, command.Stderr = os.Stdout, os.Stderr + return command.Run() +} + +func extract(path string, entry *zip.File) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + input, err := entry.Open() + if err != nil { + return err + } + defer input.Close() + output, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + return err + } + _, err = io.Copy(output, input) + closeErr := output.Close() + if err != nil { + return err + } + return closeErr +} diff --git a/desktop/deploy/native_packages.py b/desktop/deploy/native_packages.py new file mode 100644 index 0000000..09ff65f --- /dev/null +++ b/desktop/deploy/native_packages.py @@ -0,0 +1,197 @@ +"""Build native system installers from the LanUps publish payloads.""" + +import hashlib +import io +import os +from pathlib import Path +import plistlib +import re +import shutil +import struct +import subprocess +import sys +import tarfile +import tempfile + +sys.dont_write_bytecode = True +from package import DEPLOY, ICON, ROOT, binaries, tar_bytes, windows_package + +NATIVE = DEPLOY / 'native' +OUTPUT = Path(os.environ.get('LANUPS_INSTALLER_OUTPUT', ROOT / 'artifacts' / 'native-installers-optimized')).resolve() + + +def script(path): + return path.read_bytes().replace(b'\r\n', b'\n') + + +def tar_parents(archive, name, known): + parts = name.removeprefix('./').split('/')[:-1] + for length in range(1, len(parts) + 1): + path = './' + '/'.join(parts[:length]) + if path not in known: + directory = tarfile.TarInfo(path) + directory.type = tarfile.DIRTYPE + directory.mode = 0o755 + archive.addfile(directory) + known.add(path) + + +def router_package(): + source = DEPLOY / 'router' + control, data = io.BytesIO(), io.BytesIO() + with tarfile.open(fileobj=control, mode='w:gz') as archive: + for name in ('control', 'postinst', 'prerm'): + tar_bytes(archive, './' + name, script(source / name), 0o644 if name == 'control' else 0o755) + with tarfile.open(fileobj=data, mode='w:gz') as archive: + directories = set() + for source_name, name in { + 'install.sh': './usr/lib/lanups-router/install.sh', + 'lanups-policy': './usr/sbin/lanups-policy', + 'lanups-fsd.init': './etc/init.d/lanups-fsd', + 'lanups-router': './usr/sbin/lanups-router', + 'lanups-hotplug': './etc/hotplug.d/usb/95-lanups-router', + }.items(): + tar_parents(archive, name, directories) + tar_bytes(archive, name, script(source / source_name), 0o755) + path = OUTPUT / 'lanups-router_0.1.0-1_all.ipk' + with tarfile.open(path, 'w:gz') as archive: + for name, value in (('debian-binary', b'2.0\n'), ('control.tar.gz', control.getvalue()), ('data.tar.gz', data.getvalue())): + tar_bytes(archive, './' + name, value, 0o644) + return path + + +def write_ar_member(output, name, data): + size = len(data) if isinstance(data, bytes) else data.stat().st_size + output.write(f'{name + "/":16s}{0:<12d}{0:<6d}{0:<6d}{"100644":8s}{size:<10d}`\n'.encode('ascii')) + if isinstance(data, bytes): + output.write(data) + else: + with data.open('rb') as stream: + shutil.copyfileobj(stream, output) + if size % 2: + output.write(b'\n') + + +def linux_package(rid, stage): + source = DEPLOY / 'linux' + architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid] + control, data = stage / 'control.tar.gz', stage / 'data.tar.gz' + libc_version = (0, 0, 0) + with tarfile.open(data, 'w:gz', compresslevel=5) as archive: + directories = set() + for kind in ('Agent', 'Desktop'): + for path, name, executable in binaries(rid, kind): + if executable or path.suffix == '.so': + contents = path.read_bytes() + if contents.startswith(b'\x7fELF'): + for major, minor, patch in re.findall(rb'GLIBC_(\d+)\.(\d+)(?:\.(\d+))?\x00', contents): + libc_version = max(libc_version, (int(major), int(minor), int(patch or b'0'))) + item = tarfile.TarInfo(f'./opt/lanups/{kind.lower()}/{name}') + tar_parents(archive, item.name, directories) + item.size = path.stat().st_size + item.mode = 0o755 if executable else 0o644 + with path.open('rb') as stream: + archive.addfile(item, stream) + launcher = script(source / 'lanups-desktop.desktop') + b'Icon=lanups\n' + for name, content, mode in ( + ('./lib/systemd/system/lanups-agent.service', script(source / 'lanups-agent.service'), 0o644), + ('./etc/xdg/autostart/lanups-desktop.desktop', launcher.replace(b'/opt/lanups/desktop/LanUps.Desktop --tray', b'/usr/lib/lanups/start-desktop'), 0o644), + ('./usr/lib/lanups/start-desktop', script(source/'start-desktop'), 0o755), + ('./usr/share/applications/lanups-desktop.desktop', launcher.replace(b' --tray', b''), 0o644), + ('./usr/share/icons/hicolor/256x256/apps/lanups.png', ICON.read_bytes(), 0o644), + ): + tar_parents(archive, name, directories) + tar_bytes(archive, name, content, mode) + libc = 'libc6' + if libc_version[0]: + version = '.'.join(str(part) for part in (libc_version if libc_version[2] else libc_version[:2])) + libc = f'libc6 (>= {version})' + metadata = ( + 'Package: lanups\nVersion: 0.1.0-1\n' f'Architecture: {architecture}\n' + 'Maintainer: LanUps Project\nSection: utils\nPriority: optional\n' + f'Depends: adduser, passwd, init-system-helpers, {libc}, libgcc-s1, libstdc++6, libssl3 | libssl3t64, libx11-6, libx11-xcb1, libxcb1, libxext6, libxi6, libxrandr2, libice6, libsm6, libfontconfig1, libgl1, libicu72 | libicu74 | libicu76 | libicu77 | libicu78\n' + 'Description: LAN UPS Agent and desktop monitor\n' + ) + with tarfile.open(control, 'w:gz') as archive: + tar_bytes(archive, './control', metadata.encode(), 0o644) + for name in ('postinst', 'prerm', 'postrm'): + tar_bytes(archive, './'+name, script(source / name), 0o755) + path = OUTPUT / f'lanups_0.1.0-1_{architecture}.deb' + with path.open('wb') as output: + output.write(b'!\n') + for name, payload in (('debian-binary', b'2.0\n'), ('control.tar.gz', control), ('data.tar.gz', data)): + write_ar_member(output, name, payload) + control.unlink() + data.unlink() + return path + + +def mac_package(rid, stage, builder): + source = DEPLOY / 'macos' + payload = stage / rid + for kind in ('Agent','Desktop'): + prefix = 'usr/local/libexec/lanups/agent' if kind == 'Agent' else 'Applications/LanUps.app/Contents/MacOS' + for path, name, executable in binaries(rid, kind): + destination = payload / prefix / name + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, destination) + bundle = payload / 'Applications/LanUps.app/Contents' + (bundle / 'Resources').mkdir() + plist = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop', + CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL', + CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0') + (bundle / 'Info.plist').write_bytes(plistlib.dumps(plist)) + icon = ICON.read_bytes() + (bundle / 'Resources/ups.icns').write_bytes(b'icns' + struct.pack('>I', len(icon)+16) + b'ic08' + struct.pack('>I', len(icon)+8) + icon) + for path, location in (('local.lanups.agent.plist','Library/LaunchDaemons'), ('local.lanups.desktop.plist','usr/local/libexec/lanups')): + target = payload / location / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(script(source / path)) + for name in ('preinstall', 'postinstall'): + (stage / name).write_bytes(script(source / name)) + output = OUTPUT / f'LanUps-{rid}.pkg' + subprocess.run([str(builder), str(payload), str(stage/'preinstall'), str(stage/'postinstall'), + 'arm64' if rid == 'osx-arm64' else 'x86_64', str(output)], check=True) + return output + + +def main(targets): + OUTPUT.mkdir(parents=True, exist_ok=True) + packages = [router_package()] + with tempfile.TemporaryDirectory(dir=OUTPUT.parent) as temp: + stage = Path(temp) + extension = '.exe' if os.name == 'nt' else '' + builder = stage / ('macpack' + extension) + if any(rid.startswith('osx-') for rid in targets): + subprocess.run(['go','build','-mod=readonly','-trimpath','-o',str(builder),'.'],cwd=NATIVE/'macos',check=True) + for rid in targets: + if rid.startswith('linux-'): + output = linux_package(rid, stage) + elif rid.startswith('osx-'): + output = mac_package(rid, stage, builder) + elif rid == 'win-x64': + stub = stage / 'setup.exe' + env = dict(os.environ, GOOS='windows', GOARCH='amd64', CGO_ENABLED='0') + subprocess.run(['go','build','-trimpath','-ldflags=-s -w','-o',str(stub),str(NATIVE/'windows/main.go')],cwd=ROOT,env=env,check=True) + payload = windows_package(rid, stage / 'windows-payload.zip') + output = OUTPUT / 'LanUps-Setup-win-x64.exe' + with output.open('wb') as stream: + for part in (stub,payload): + with part.open('rb') as file: + shutil.copyfileobj(file, stream) + if os.name == 'nt': + subprocess.run([str(output),'--verify'],check=True) + else: + raise ValueError(f'Unsupported target: {rid}') + packages.append(output) + print(output.name, flush=True) + archives = [path for path in OUTPUT.iterdir() if path.suffix in {'.exe', '.deb', '.pkg', '.ipk'}] + with (OUTPUT / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums: + for path in sorted(archives): + with path.open('rb') as stream: + sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n") + print(packages[0].name, flush=True) + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/desktop/deploy/package.ps1 b/desktop/deploy/package.ps1 new file mode 100644 index 0000000..044f273 --- /dev/null +++ b/desktop/deploy/package.ps1 @@ -0,0 +1,40 @@ +param( + [string[]]$Targets = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64'), + [ValidateSet('Aot','Trimmed','Pack')][string]$Mode = 'Pack' +) +$ErrorActionPreference = 'Stop' +$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$localDotnet = Join-Path $root '.dotnet\dotnet.exe' +$dotnet = if (Test-Path -LiteralPath $localDotnet) { $localDotnet } else { (Get-Command dotnet -ErrorAction Stop).Source } +if (Test-Path -LiteralPath $localDotnet) { + $env:DOTNET_CLI_HOME = Join-Path $root '.dotnet' + $env:NUGET_PACKAGES = Join-Path $env:DOTNET_CLI_HOME 'packages' +} +$allowed = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64') +$platform = if ($IsWindows -or $env:OS -eq 'Windows_NT') { 'win' } elseif ($IsMacOS) { 'osx' } else { 'linux' } +$payload = if ($env:LANUPS_INSTALLER_PAYLOAD) { $env:LANUPS_INSTALLER_PAYLOAD } else { Join-Path $root 'artifacts\installer-payload-optimized' } +foreach ($rid in $Targets) { + if ($rid -notin $allowed) { throw "Unsupported target: $rid" } + if ($Mode -eq 'Pack') { continue } + if ($Mode -eq 'Aot' -and !$rid.StartsWith("$platform-")) { throw "Native AOT for $rid must be built on a $($rid.Split('-')[0]) host" } + $publish = if ($Mode -eq 'Aot') { @('-p:PublishAot=true','-p:OptimizationPreference=Size') } else { @('-p:PublishTrimmed=true') } + foreach ($kind in @('Agent','Desktop')) { + $project = Join-Path $root "desktop\src\LanUps.$kind\LanUps.$kind.csproj" + $output = Join-Path $payload "$rid\$kind" + $temporary = "$output.$([guid]::NewGuid()).publish" + & $dotnet publish $project -c Release -r $rid --self-contained true @publish --disable-build-servers -o $temporary -v minimal + if ($LASTEXITCODE) { exit $LASTEXITCODE } + if (Test-Path -LiteralPath $output) { + $backup = "$output.$([guid]::NewGuid()).previous" + Move-Item -LiteralPath $output -Destination $backup + try { Move-Item -LiteralPath $temporary -Destination $output } catch { Move-Item -LiteralPath $backup -Destination $output; throw } + $resolvedBackup = (Resolve-Path -LiteralPath $backup).Path + $resolvedParent = (Resolve-Path -LiteralPath (Split-Path -Parent $output)).Path + if ((Split-Path -Parent $resolvedBackup) -eq $resolvedParent -and (Split-Path -Leaf $resolvedBackup) -like "$kind.*.previous") { + Remove-Item -LiteralPath $resolvedBackup -Recurse -Force + } + } else { Move-Item -LiteralPath $temporary -Destination $output } + } +} +& python (Join-Path $PSScriptRoot 'native_packages.py') @Targets +exit $LASTEXITCODE diff --git a/desktop/deploy/package.py b/desktop/deploy/package.py new file mode 100644 index 0000000..9876d80 --- /dev/null +++ b/desktop/deploy/package.py @@ -0,0 +1,98 @@ +"""Assemble installable archives from self-contained dotnet publish output.""" + +import hashlib +import io +import os +from pathlib import Path +import plistlib +import struct +import sys +import tarfile +import zipfile + +DEPLOY = Path(__file__).resolve().parent +ROOT = DEPLOY.parent.parent +PAYLOAD = Path(os.environ.get('LANUPS_INSTALLER_PAYLOAD', ROOT / 'artifacts' / 'installer-payload-optimized')).resolve() +DIST = ROOT / 'artifacts' / 'installers' +ICON = DEPLOY.parent / 'src' / 'LanUps.Desktop' / 'Assets' / 'ups.png' + + +def binaries(rid, kind): + directory = PAYLOAD / rid / kind + executable = directory / f"LanUps.{kind}{'.exe' if rid.startswith('win-') else ''}" + if not executable.is_file(): + raise FileNotFoundError(executable) + for path in sorted(directory.rglob('*')): + if path.is_file() and path.suffix.lower() not in {'.pdb', '.dbg'} and not any(part.endswith('.dSYM') for part in path.parts): + yield path, path.relative_to(directory).as_posix(), path == executable + + +def tar_bytes(archive, name, data, mode): + item = tarfile.TarInfo(name) + item.size = len(data) + item.mode = mode + archive.addfile(item, io.BytesIO(data)) + + +def unix_package(rid): + mac = rid.startswith('osx-') + path = DIST / f'LanUps-{rid}.tar.gz' + with tarfile.open(path, 'w:gz', compresslevel=5) as archive: + tar_bytes(archive, 'install.sh', (DEPLOY / 'unix' / 'install.sh').read_bytes().replace(b'\r\n', b'\n'), 0o755) + tar_bytes(archive, 'architecture', rid.split('-', 1)[1].encode() + b'\n', 0o644) + folder = DEPLOY / ('macos' if mac else 'linux') + for sidecar in sorted(folder.iterdir()): + tar_bytes(archive, sidecar.name, sidecar.read_bytes(), 0o644) + for kind in ('Agent', 'Desktop'): + prefix = 'LanUps.app/Contents/MacOS' if mac and kind == 'Desktop' else kind.lower() + for source, filename, executable in binaries(rid, kind): + item = tarfile.TarInfo(f'{prefix}/{filename}') + item.size = source.stat().st_size + item.mode = 0o755 if executable else 0o644 + with source.open('rb') as stream: + archive.addfile(item, stream) + if mac: + info = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop', + CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL', + CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0') + tar_bytes(archive, 'LanUps.app/Contents/Info.plist', plistlib.dumps(info), 0o644) + png = ICON.read_bytes() + image = b'icns' + struct.pack('>I', len(png) + 16) + b'ic08' + struct.pack('>I', len(png) + 8) + png + tar_bytes(archive, 'LanUps.app/Contents/Resources/ups.icns', image, 0o644) + else: + tar_bytes(archive, 'ups.png', ICON.read_bytes(), 0o644) + return path + + +def windows_package(rid, path=None): + path = path or DIST / f'LanUps-{rid}.zip' + path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED, compresslevel=5) as archive: + for filename in ('Setup.cmd', 'Setup.ps1', 'install.ps1'): + script = (DEPLOY / 'windows' / filename).read_text(encoding='utf-8-sig') + archive.writestr(filename, script.replace('\n', '\r\n').encode('utf-8-sig' if filename.endswith('.ps1') else 'ascii')) + for kind in ('Agent', 'Desktop'): + for source, filename, _ in binaries(rid, kind): + archive.write(source, f'{kind}/{filename}') + return path + + +def main(targets): + DIST.mkdir(parents=True, exist_ok=True) + router = DIST / 'LanUps-openwrt.tar.gz' + with tarfile.open(router, 'w:gz') as archive: + for source in sorted((DEPLOY / 'router').iterdir()): + tar_bytes(archive, source.name, source.read_bytes().replace(b'\r\n', b'\n'), 0o755) + print(router.name, flush=True) + for rid in targets: + path = windows_package(rid) if rid.startswith('win-') else unix_package(rid) + print(path.name, flush=True) + archives = sorted([*DIST.glob('LanUps-*.zip'), *DIST.glob('LanUps-*.tar.gz')]) + with (DIST / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums: + for path in archives: + with path.open('rb') as stream: + sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n") + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/desktop/deploy/router/control b/desktop/deploy/router/control new file mode 100644 index 0000000..a92e35b --- /dev/null +++ b/desktop/deploy/router/control @@ -0,0 +1,8 @@ +Package: lanups-router +Version: 0.1.0-1 +Architecture: all +Maintainer: LanUps Project +Section: utils +Priority: optional +Depends: nut-server, nut-driver-blazer_usb, nut-upsc +Description: LAN UPS configuration and optional low-battery policy for OpenWrt diff --git a/desktop/deploy/router/install.sh b/desktop/deploy/router/install.sh new file mode 100644 index 0000000..f92ac42 --- /dev/null +++ b/desktop/deploy/router/install.sh @@ -0,0 +1,121 @@ +#!/bin/sh +set -eu + +mode=read-only +case "${1:-}" in + '') ;; + --enable-fsd) mode=fsd ;; + --check) mode=check ;; + *) echo 'Usage: sh install.sh [--check|--enable-fsd]' >&2; exit 2 ;; +esac +[ "$(id -u)" = 0 ] && command -v uci >/dev/null || { echo 'Run as root on OpenWrt/LEDE' >&2; exit 1; } +base=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +lan=$(uci -q get network.lan.ipaddr | cut -d/ -f1) +case "$lan" in ''|*[!0-9.]*) echo 'A static LAN IPv4 address is required' >&2; exit 1;; esac + +usb='' +for device in /sys/bus/usb/devices/*; do + if [ -r "$device/idVendor" ] && [ "$(cat "$device/idVendor"):$(cat "$device/idProduct")" = 0665:5161 ]; then + usb=$(sed -n 's/^DEVNAME=//p' "$device/uevent") + break + fi +done +[ -n "$usb" ] || { echo 'Connect the H1000M USB device (0665:5161) before installing' >&2; exit 1; } +if [ "$mode" = check ]; then + echo "LAN $lan; UPS USB 0665:5161 ($usb)" + if command -v upsc >/dev/null; then upsc h1000m@127.0.0.1 ups.status || echo 'Current UPS data is unavailable'; fi + exit 0 +fi +[ -z "$(uci -q changes nut_server || :)" ] || { echo 'Commit or discard pending nut_server edits before installing' >&2; exit 1; } + +if [ "${LANUPS_SKIP_PACKAGES:-0}" = 1 ]; then + command -v upsc >/dev/null && [ -x /etc/init.d/nut-server ] || { echo 'NUT package dependencies are not ready' >&2; exit 1; } +elif command -v opkg >/dev/null; then + missing='' + packages='nut-server nut-driver-blazer_usb nut-upsc' + if [ "$mode" = fsd ] && ! command -v timeout >/dev/null; then packages="$packages coreutils-timeout"; fi + for package in $packages; do + if ! opkg list-installed "$package" | grep -q "^$package - "; then missing="$missing $package"; fi + done + if [ -n "$missing" ]; then + opkg update || echo 'Some feeds did not refresh; trying available indexes' >&2 + # Package names are constants defined above. + opkg install $missing + fi +elif command -v apk >/dev/null; then + apk add nut-server nut-driver-blazer_usb nut-upsc + if [ "$mode" = fsd ] && ! command -v timeout >/dev/null; then apk add coreutils-timeout; fi +else + echo 'No supported OpenWrt package manager found' >&2; exit 1 +fi + +umask 077 +mkdir -p /etc/lanups +backup=$(mktemp /etc/lanups/nut-server.XXXXXX) +cp /etc/config/nut_server "$backup" +changed=1 +if [ "$(uci -q get nut_server.h1000m.driver || :)" = blazer_usb ] && + [ "$(uci -q get nut_server.h1000m.port || :)" = auto ] && + [ "$(uci -q get nut_server.h1000m.vendorid || :)" = 0665 ] && + [ "$(uci -q get nut_server.h1000m.productid || :)" = 5161 ] && + uci show nut_server | grep -Fq ".address='$lan'" && + uci show nut_server | grep -Fq ".address='127.0.0.1'"; then + changed=0 +fi + +if [ "$changed" = 1 ]; then + uci set nut_server.h1000m=driver + uci set nut_server.h1000m.driver=blazer_usb + uci set nut_server.h1000m.port=auto + uci set nut_server.h1000m.vendorid=0665 + uci set nut_server.h1000m.productid=5161 + for entry in "lanups_local:127.0.0.1" "lanups_lan:$lan"; do + section=${entry%%:*}; ip=${entry#*:} + if ! uci show nut_server | grep -Fq ".address='$ip'"; then + uci set "nut_server.$section=listen_address" + uci set "nut_server.$section.address=$ip" + uci set "nut_server.$section.port=3493" + fi + done +fi + +if [ "$mode" = fsd ]; then + command -v timeout >/dev/null && command -v nc >/dev/null || { echo 'FSD mode requires timeout and nc' >&2; uci revert nut_server; exit 1; } + password=$(uci -q get nut_server.lanups_policy.password || :) + if [ -z "$password" ]; then password=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n'); fi + case "$password" in ''|*[!A-Fa-f0-9]*) echo 'Invalid FSD service credential' >&2; uci revert nut_server; exit 1;; esac + uci set nut_server.lanups_policy=user + uci set nut_server.lanups_policy.username=lanups_policy + uci set "nut_server.lanups_policy.password=$password" + uci set nut_server.lanups_policy.actions=FSD + changed=1 +fi + +chown nut:nut "/dev/$usb" +chmod 0660 "/dev/$usb" +if [ "$changed" = 1 ]; then uci commit nut_server; fi +if [ "$mode" = fsd ]; then chmod 0600 /etc/config/nut_server; fi +if [ "$changed" = 1 ] || ! /etc/init.d/nut-server running || ! upsc h1000m@127.0.0.1 ups.status >/dev/null 2>&1; then + /etc/init.d/nut-server restart +fi +state='' +for attempt in 1 2 3 4 5 6 7 8 9 10; do + state=$(upsc h1000m@127.0.0.1 ups.status 2>/dev/null) && break + sleep 1 +done +if [ -z "$state" ]; then + if [ "$changed" = 1 ]; then cp "$backup" /etc/config/nut_server; /etc/init.d/nut-server restart || :; fi + echo "NUT could not read H1000M; backup: $backup" >&2 + exit 1 +fi +/etc/init.d/nut-server enable +if [ "$mode" = fsd ]; then + if [ "$base" != /usr/lib/lanups-router ]; then + cp "$base/lanups-policy" /usr/sbin/lanups-policy + cp "$base/lanups-fsd.init" /etc/init.d/lanups-fsd + fi + chmod 0755 /usr/sbin/lanups-policy /etc/init.d/lanups-fsd + /etc/init.d/lanups-fsd enable + /etc/init.d/lanups-fsd restart +fi +echo "NUT ready: h1000m@$lan:3493 ($state); installer mode: $mode; backup: $backup" diff --git a/desktop/deploy/router/lanups-fsd.init b/desktop/deploy/router/lanups-fsd.init new file mode 100644 index 0000000..4c2e00c --- /dev/null +++ b/desktop/deploy/router/lanups-fsd.init @@ -0,0 +1,11 @@ +#!/bin/sh /etc/rc.common +START=83 +STOP=27 +USE_PROCD=1 + +start_service() { + procd_open_instance + procd_set_param command /usr/sbin/lanups-policy + procd_set_param respawn + procd_close_instance +} diff --git a/desktop/deploy/router/lanups-hotplug b/desktop/deploy/router/lanups-hotplug new file mode 100644 index 0000000..7890343 --- /dev/null +++ b/desktop/deploy/router/lanups-hotplug @@ -0,0 +1,15 @@ +#!/bin/sh +# Sourced by OpenWrt hotplug. A separate process owns the retry lock. +case "${ACTION:-}:${PRODUCT:-}" in + add:665/5161/*|add:0665/5161/*) + if [ -f /etc/lanups/pending ] && [ -n "${DEVNAME:-}" ]; then + ( + lock=/var/run/lanups-router-setup.lock + mkdir "$lock" 2>/dev/null || exit 0 + trap 'rmdir "$lock"' EXIT + sleep 2 + LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router 2>&1 | logger -t lanups-router + ) /dev/null 2>&1 & + fi + ;; +esac diff --git a/desktop/deploy/router/lanups-policy b/desktop/deploy/router/lanups-policy new file mode 100644 index 0000000..66500c0 --- /dev/null +++ b/desktop/deploy/router/lanups-policy @@ -0,0 +1,42 @@ +#!/bin/sh +set -eu + +online_since=0 +while :; do + if state=$(upsc h1000m@127.0.0.1 ups.status 2>/dev/null); then + case " $state " in + *' FSD '*) + case " $state " in + *' OL '*) + read -r uptime _ &2 +fi +exit 0 diff --git a/desktop/deploy/router/prerm b/desktop/deploy/router/prerm new file mode 100644 index 0000000..38d1aa4 --- /dev/null +++ b/desktop/deploy/router/prerm @@ -0,0 +1,8 @@ +#!/bin/sh +[ -z "${IPKG_INSTROOT:-}" ] || exit 0 +[ "${1:-remove}" = remove ] || exit 0 +if [ -x /etc/init.d/lanups-fsd ]; then + /etc/init.d/lanups-fsd stop 2>/dev/null || : + /etc/init.d/lanups-fsd disable 2>/dev/null || : +fi +exit 0 diff --git a/desktop/deploy/unix/install.sh b/desktop/deploy/unix/install.sh new file mode 100644 index 0000000..4d35333 --- /dev/null +++ b/desktop/deploy/unix/install.sh @@ -0,0 +1,100 @@ +#!/bin/sh +set -eu + +operator=${SUDO_USER:-} +mode=simulation +while [ "$#" -gt 0 ]; do + case "$1" in + --user) [ "$#" -ge 2 ] || exit 2; operator=$2; shift 2;; + --enable-shutdown) mode=shutdown; shift;; + *) echo 'Usage: sudo sh install.sh [--user ACCOUNT] [--enable-shutdown]' >&2; exit 2;; + esac +done +[ "$(id -u)" = 0 ] || { echo 'Run the installer with sudo' >&2; exit 1; } +case "$operator" in ''|*[!A-Za-z0-9_.-]*) echo 'Supply the desktop account using --user' >&2; exit 1;; esac +uid=$(id -u "$operator") +[ "$uid" != 0 ] || { echo 'Use a non-root desktop account' >&2; exit 1; } +gid=$(id -g "$operator") +base=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +platform=$(uname -s) +version=$(cat "$base/architecture") +case "$(uname -m):$version" in x86_64:x64|arm64:arm64|aarch64:arm64) ;; *) echo 'This package targets a different CPU' >&2; exit 1;; esac + +case "$platform" in + Linux) + command -v systemctl >/dev/null + home=$(getent passwd "$operator" | cut -d: -f6) + root=/opt/lanups; data=/etc/LanUps; group=root + test -f "$base/lanups-agent.service" + ;; + Darwin) + home=$(dscl . -read "/Users/$operator" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //') + root=/usr/local/libexec/lanups; data='/Library/Application Support/LanUps'; group=wheel + test -f "$base/local.lanups.agent.plist" + if [ -e /Applications/LanUps.app ] && [ ! -L /Applications/LanUps.app ]; then + echo '/Applications/LanUps.app already exists and is not managed by this installer' >&2; exit 1 + fi + ;; + *) echo 'This installer supports Linux with systemd and macOS' >&2; exit 1;; +esac +case "$home" in /*) ;; *) echo 'Cannot determine the desktop account home' >&2; exit 1;; esac + +install -d -m 0755 -o root -g "$group" "$root" "$data" +stage=$(mktemp -d "$root/release.XXXXXX") +chmod 0755 "$stage" +cp -R "$base/agent" "$stage/agent" +chmod 0755 "$stage/agent/LanUps.Agent" +if [ "$platform" = Linux ]; then + cp -R "$base/desktop" "$stage/desktop" + chmod 0755 "$stage/desktop/LanUps.Desktop" + install -m 0644 "$base/ups.png" "$stage/ups.png" +else + cp -R "$base/LanUps.app" "$stage/LanUps.app" + chmod 0755 "$stage/LanUps.app/Contents/MacOS/LanUps.Desktop" +fi +chown -R root:"$group" "$stage" +chmod -R go-w "$stage" + +token="$data/agent.token" +if [ ! -f "$token" ]; then "$stage/agent/LanUps.Agent" --provision; fi +chmod 0600 "$token" + +if [ "$platform" = Linux ]; then + getent group lanups-operators >/dev/null || groupadd --system lanups-operators + usermod -a -G lanups-operators "$operator" + chown root:lanups-operators "$token" + chmod 0640 "$token" + + args='' + [ "$mode" = simulation ] || args=' --enable-shutdown' + sed "s|^ExecStart=.*|ExecStart=$stage/agent/LanUps.Agent$args|" "$base/lanups-agent.service" >"$stage/lanups-agent.service" + install -m 0644 "$stage/lanups-agent.service" /etc/systemd/system/lanups-agent.service + install -d -m 0755 /usr/local/share/applications + sed "s|^Exec=.*|Exec=$stage/desktop/LanUps.Desktop|; /^Icon=/d; \$a Icon=$stage/ups.png" "$base/lanups-desktop.desktop" >"$stage/menu.desktop" + install -m 0644 "$stage/menu.desktop" /usr/local/share/applications/lanups-desktop.desktop + sed "s|^Exec=.*|Exec=$stage/desktop/LanUps.Desktop --tray|" "$base/lanups-desktop.desktop" >"$stage/autostart.desktop" + sudo -u "$operator" mkdir -p "$home/.config/autostart" + sudo -u "$operator" install -m 0644 "$stage/autostart.desktop" "$home/.config/autostart/lanups-desktop.desktop" + systemctl daemon-reload + systemctl enable lanups-agent.service + systemctl restart lanups-agent.service +else + chmod -N "$token" + chmod +a "user:$operator allow read" "$token" + if launchctl print system/local.lanups.agent >/dev/null 2>&1; then launchctl bootout system/local.lanups.agent; fi + suffix='' + [ "$mode" = simulation ] || suffix='--enable-shutdown' + sed "s|/usr/local/libexec/lanups/agent/LanUps.Agent|$stage/agent/LanUps.Agent$suffix|" \ + "$base/local.lanups.agent.plist" >"$stage/agent.plist" + install -m 0644 -o root -g wheel "$stage/agent.plist" /Library/LaunchDaemons/local.lanups.agent.plist + if launchctl print "gui/$uid/local.lanups.desktop" >/dev/null 2>&1; then launchctl bootout "gui/$uid/local.lanups.desktop"; fi + app=/Applications/LanUps.app + ln -sfn "$stage/LanUps.app" "$app" + sudo -u "$operator" mkdir -p "$home/Library/LaunchAgents" + sudo -u "$operator" install -m 0644 "$base/local.lanups.desktop.plist" "$home/Library/LaunchAgents/local.lanups.desktop.plist" + launchctl bootstrap system /Library/LaunchDaemons/local.lanups.agent.plist + if launchctl print "gui/$uid" >/dev/null 2>&1; then + launchctl bootstrap "gui/$uid" "$home/Library/LaunchAgents/local.lanups.desktop.plist" + fi +fi +echo "LAN UPS installed ($mode). The desktop client automatically starts at login." diff --git a/desktop/deploy/windows/Setup.cmd b/desktop/deploy/windows/Setup.cmd new file mode 100644 index 0000000..55cec72 --- /dev/null +++ b/desktop/deploy/windows/Setup.cmd @@ -0,0 +1,4 @@ +@echo off +setlocal +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Setup.ps1" %* +if errorlevel 1 pause diff --git a/desktop/deploy/windows/Setup.ps1 b/desktop/deploy/windows/Setup.ps1 new file mode 100644 index 0000000..8c36e24 --- /dev/null +++ b/desktop/deploy/windows/Setup.ps1 @@ -0,0 +1,57 @@ +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 } diff --git a/desktop/deploy/windows/install.ps1 b/desktop/deploy/windows/install.ps1 new file mode 100644 index 0000000..4ae2bbe --- /dev/null +++ b/desktop/deploy/windows/install.ps1 @@ -0,0 +1,56 @@ +#Requires -RunAsAdministrator +param( + [Parameter(Mandatory)][string]$Operator, + [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)) { + if (!(Test-Path -LiteralPath $app -PathType Leaf)) { throw "Missing $app" } +} +$operatorSid = ([Security.Principal.NTAccount]::new($Operator)).Translate([Security.Principal.SecurityIdentifier]).Value +$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps' +$token = Join-Path $data 'agent.token' +New-Item -ItemType Directory -Path $data -Force | Out-Null +$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18') +$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') +$operatorId = [Security.Principal.SecurityIdentifier]::new($operatorSid) +$directoryRules = [Security.AccessControl.DirectorySecurity]::new() +$directoryRules.SetAccessRuleProtection($true, $false) +foreach ($principalId in @($system, $administrators)) { + $directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) +} +$directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'ReadAndExecute', 'Allow')) +Set-Acl -LiteralPath $data -AclObject $directoryRules +if (!(Test-Path -LiteralPath $token)) { + & $agent --provision + if ($LASTEXITCODE) { throw 'Unable to create local Agent credential' } +} +$tokenRules = [Security.AccessControl.FileSecurity]::new() +$tokenRules.SetAccessRuleProtection($true, $false) +foreach ($principalId in @($system, $administrators)) { + $tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'Allow')) +} +$tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'Read', 'Allow')) +Set-Acl -LiteralPath $token -AclObject $tokenRules + +$command = '"' + $agent + '"' +if ($EnableShutdown) { $command += ' --enable-shutdown' } +$installed = Get-CimInstance Win32_Service -Filter "Name='LanUps.Agent'" +if ($installed) { + Stop-Service 'LanUps.Agent' -ErrorAction Stop + $changed = Invoke-CimMethod -InputObject $installed -MethodName Change -Arguments @{PathName=$command;StartMode='Automatic'} + if ($changed.ReturnValue) { throw "Cannot update Agent service: $($changed.ReturnValue)" } +} else { + New-Service -Name 'LanUps.Agent' -BinaryPathName $command -DisplayName 'LAN UPS Agent' -StartupType Automatic | Out-Null +} +Start-Service -Name 'LanUps.Agent' + +$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 +Register-ScheduledTask -TaskName 'LanUps Desktop' -Action $action -Trigger $trigger -Principal $principal -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) -Force | Out-Null +Start-ScheduledTask -TaskName 'LanUps Desktop' diff --git a/desktop/src/LanUps.Agent/Coordinator.cs b/desktop/src/LanUps.Agent/Coordinator.cs new file mode 100644 index 0000000..0474cdb --- /dev/null +++ b/desktop/src/LanUps.Agent/Coordinator.cs @@ -0,0 +1,204 @@ +using System.Diagnostics; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; +using LanUps.Core; + +namespace LanUps.Agent; + +internal sealed class Coordinator +{ + private static readonly TimeSpan Countdown = TimeSpan.FromMinutes(1); + private readonly object _gate = new(); + private readonly string _settingsPath; + private readonly bool _dryRun; + private readonly ILogger _log; + private readonly CancellationToken _stopping; + private readonly string _shutdownStatePath; + private NutEndpoint _endpoint; + private UpsUpdate _update = new(null, null, false); + private ShutdownNotice? _pending; + private string? _lastAction; + private string? _previousStatus; + private bool _signalLatched; + private CancellationTokenSource? _monitor; + + public Coordinator(string settingsPath, bool dryRun, ILogger log, CancellationToken stopping) + { + _settingsPath = settingsPath; + _shutdownStatePath = Path.ChangeExtension(settingsPath, dryRun ? ".simulation.json" : ".shutdown.json"); + _dryRun = dryRun; + _log = log; + _stopping = stopping; + _endpoint = LoadEndpoint(); + if (File.Exists(_shutdownStatePath)) + { + var saved = JsonSerializer.Deserialize(File.ReadAllText(_shutdownStatePath), ShutdownJson.Default.ShutdownState); + if (saved?.Endpoint == _endpoint) + { + _pending = saved.Pending; + _signalLatched = saved.SignalLatched; + _lastAction = saved.LastAction; + } + } + } + + public void Start() + { + lock (_gate) + { + if (_pending is { } pending) _ = WaitForDeadlineAsync(pending); + StartMonitor(); + } + } + + public AgentState Snapshot() + { + lock (_gate) return new(_endpoint, _update, _pending, _lastAction, _dryRun); + } + + public bool SetEndpoint(NutEndpoint endpoint) + { + lock (_gate) + { + if (endpoint == _endpoint) return true; + if (_pending is not null) return false; + WriteJson(_settingsPath, endpoint, AgentJson.Default.NutEndpoint); + _endpoint = endpoint; + _update = new(null, null, false); + _signalLatched = false; + _previousStatus = null; + _lastAction = null; + StartMonitor(); + return true; + } + } + + public bool Respond(Guid id, bool confirm) => Finish(id, confirm ? "用户确认" : "用户取消", confirm); + + private NutEndpoint LoadEndpoint() + { + if (!File.Exists(_settingsPath)) return NutEndpoint.Default; + var saved = JsonSerializer.Deserialize(File.ReadAllText(_settingsPath), AgentJson.Default.NutEndpoint); + if (saved is not null && NutEndpoint.TryParse(saved.Host, saved.Port.ToString(), saved.Name, out var endpoint)) return endpoint; + throw new InvalidDataException("Invalid saved NUT endpoint"); + } + + private void StartMonitor() + { + _monitor?.Cancel(); + var monitor = CancellationTokenSource.CreateLinkedTokenSource(_stopping); + _monitor = monitor; + var endpoint = _endpoint; + _ = Task.Run(async () => + { + try { await NutMonitor.RunAsync(endpoint, update => Observe(monitor, update), monitor.Token); } + catch (OperationCanceledException) when (monitor.IsCancellationRequested) { } + finally + { + lock (_gate) + { + if (_monitor == monitor) _monitor = null; + monitor.Dispose(); + } + } + }); + } + + private void Observe(CancellationTokenSource monitor, UpsUpdate update) + { + lock (_gate) + { + if (_monitor != monitor || monitor.IsCancellationRequested) return; + _update = update; + var status = update.Error is { } error ? $"通讯中断 {error}" : $"UPS 状态 {update.LastReading?.Get("ups.status")}"; + if (status != _previousStatus) _log.LogInformation("{Status}", status); + _previousStatus = status; + if (update.Error is not null || update.LastReading is not { } reading) return; + + var hasSignal = reading.Has("FSD"); + if (!hasSignal) + { + if (_signalLatched) { _signalLatched = false; SaveShutdownState(); } + return; + } + if (_signalLatched) return; + _signalLatched = true; + if (_pending is not null) { SaveShutdownState(); return; } + var pending = new ShutdownNotice(Guid.NewGuid(), DateTimeOffset.UtcNow + Countdown); + _pending = pending; + _lastAction = null; + SaveShutdownState(); + _log.LogWarning("收到 FSD,关机倒计时至 {Deadline}", pending.Deadline); + _ = WaitForDeadlineAsync(pending); + } + } + + private async Task WaitForDeadlineAsync(ShutdownNotice pending) + { + try + { + while (pending.Deadline - DateTimeOffset.UtcNow is { } remaining && remaining > TimeSpan.Zero) + await Task.Delay(TimeSpan.FromMilliseconds(Math.Ceiling(remaining.TotalMilliseconds)), _stopping); + if (!_stopping.IsCancellationRequested) Finish(pending.Id, "60 秒内无响应", true); + } + catch (OperationCanceledException) when (_stopping.IsCancellationRequested) { } + } + + private bool Finish(Guid id, string reason, bool shutdown) + { + lock (_gate) + { + if (_pending?.Id != id) return false; + _pending = null; + _lastAction = shutdown ? $"{reason} · {(_dryRun ? "已模拟关机" : "已提交关机")}" : reason; + SaveShutdownState(); + _log.LogWarning("{Result}", _lastAction); + if (shutdown && !_dryRun) _ = Task.Run(ExecuteShutdownAsync); + return true; + } + } + + private async Task ExecuteShutdownAsync() + { + try + { + var executable = OperatingSystem.IsWindows() ? Path.Combine(Environment.SystemDirectory, "shutdown.exe") : + OperatingSystem.IsMacOS() ? "/sbin/shutdown" : "/usr/bin/systemctl"; + var arguments = OperatingSystem.IsWindows() ? "/s /t 0" : OperatingSystem.IsMacOS() ? "-h now" : "poweroff"; + using var process = Process.Start(new ProcessStartInfo(executable, arguments) { UseShellExecute = false }); + if (process is null) throw new IOException("未能启动系统关机程序"); + await process.WaitForExitAsync(); + if (process.ExitCode != 0) throw new IOException($"关机程序退出码 {process.ExitCode}"); + } + catch (Exception ex) + { + lock (_gate) + { + _lastAction = $"关机执行失败:{ex.Message}"; + SaveShutdownState(); + _log.LogError(ex, "关机执行失败"); + } + } + } + + private void SaveShutdownState() + { + try { WriteJson(_shutdownStatePath, new ShutdownState(_endpoint, _pending, _signalLatched, _lastAction), ShutdownJson.Default.ShutdownState); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { _log.LogError(ex, "保存关机状态失败"); } + } + + private static void WriteJson(string path, T value, JsonTypeInfo type) + { + var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try { File.WriteAllText(temp, JsonSerializer.Serialize(value, type)); File.Move(temp, path, overwrite: true); } + finally { if (File.Exists(temp)) File.Delete(temp); } + } + +} + +internal sealed record ShutdownState(NutEndpoint Endpoint, ShutdownNotice? Pending, bool SignalLatched, string? LastAction); + +[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)] +[JsonSerializable(typeof(ShutdownState))] +internal sealed partial class ShutdownJson : JsonSerializerContext; diff --git a/desktop/src/LanUps.Agent/LanUps.Agent.csproj b/desktop/src/LanUps.Agent/LanUps.Agent.csproj new file mode 100644 index 0000000..0a46e5c --- /dev/null +++ b/desktop/src/LanUps.Agent/LanUps.Agent.csproj @@ -0,0 +1,13 @@ + + Exenet10.0enableenable + + true + + + + + + + + + diff --git a/desktop/src/LanUps.Agent/LinkerRoots.xml b/desktop/src/LanUps.Agent/LinkerRoots.xml new file mode 100644 index 0000000..6df3373 --- /dev/null +++ b/desktop/src/LanUps.Agent/LinkerRoots.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/desktop/src/LanUps.Agent/Program.cs b/desktop/src/LanUps.Agent/Program.cs new file mode 100644 index 0000000..b2c760d --- /dev/null +++ b/desktop/src/LanUps.Agent/Program.cs @@ -0,0 +1,77 @@ +using System.Security.Cryptography; +using LanUps.Agent; +using LanUps.Core; +using Microsoft.AspNetCore.Mvc; + +if (args is ["--provision"]) +{ + var path = AgentLocation.TokenPath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + using var writer = new StreamWriter(file); + writer.Write(Convert.ToHexString(RandomNumberGenerator.GetBytes(32))); + return; +} + +if (args.Length > 0 && args is not ["--enable-shutdown"]) + throw new ArgumentException("Usage: LanUps.Agent [--provision | --enable-shutdown]"); + +var token = Convert.FromHexString(File.ReadAllText(AgentLocation.TokenPath).Trim()); +if (token.Length != 32) throw new InvalidDataException("Agent token must contain 32 bytes"); + +var options = new WebApplicationOptions { Args = [], ContentRootPath = AppContext.BaseDirectory }; +var builder = WebApplication.CreateSlimBuilder(options); +builder.Services.ConfigureHttpJsonOptions(json => json.SerializerOptions.TypeInfoResolverChain.Insert(0, AgentJson.Default)); +builder.Services.AddWindowsService(service => service.ServiceName = "LanUps.Agent"); +builder.WebHost.ConfigureKestrel(server => +{ + server.Listen(System.Net.IPAddress.Loopback, AgentLocation.Port); + server.Limits.MaxRequestBodySize = 4096; +}); +builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning); +var app = builder.Build(); +var agent = new Coordinator(Path.ChangeExtension(AgentLocation.TokenPath, ".json"), args.Length == 0, app.Logger, app.Lifetime.ApplicationStopping); +app.Lifetime.ApplicationStarted.Register(agent.Start); + +app.Use(async (context, next) => +{ + byte[]? supplied = null; + var candidate = context.Request.Headers["X-LanUps-Token"].ToString(); + if (candidate.Length == 64) + { + try { supplied = Convert.FromHexString(candidate); } + catch (FormatException) { } + } + if (supplied is null || !CryptographicOperations.FixedTimeEquals(token, supplied)) + { + context.Response.StatusCode = 401; + await context.Response.WriteAsync("后台服务认证失败"); + return; + } + context.Response.Headers.CacheControl = "no-store"; + await next(); +}); + +app.MapGet("/status", () => agent.Snapshot()); +app.MapPut("/endpoint", ([FromBody] NutEndpoint proposed) => +{ + if (!NutEndpoint.TryParse(proposed.Host, proposed.Port.ToString(), proposed.Name, out var endpoint)) + return Results.BadRequest("请输入有效的 NUT 配置"); + try { return agent.SetEndpoint(endpoint) ? Results.Ok(endpoint) : Results.Conflict("关机倒计时正在执行"); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return Results.Text("保存后台配置失败", statusCode: 500); } +}); +app.MapGet("/ups", async (string host, int port, CancellationToken cancellation) => +{ + if (!NutEndpoint.TryServer(host, port.ToString(), out var address, out _)) return Results.BadRequest("无效的服务器地址或端口"); + try + { + var names = await NutMonitor.DiscoverAsync(address, port, cancellation); + return Results.Json(names.ToArray(), AgentJson.Default.StringArray); + } + catch (Exception ex) when (ex is System.Net.Sockets.SocketException or IOException or OperationCanceledException) + { return Results.Text(ex is OperationCanceledException ? "NUT 查询超时" : ex.Message, statusCode: 502); } +}); +app.MapPost("/shutdown/{id:guid}/{decision}", (Guid id, string decision) => decision is "confirm" or "cancel" && agent.Respond(id, decision == "confirm") + ? Results.Ok(decision) : Results.Conflict("关机请求已处理或不存在")); +await app.RunAsync(); diff --git a/desktop/src/LanUps.Core/AgentClient.cs b/desktop/src/LanUps.Core/AgentClient.cs new file mode 100644 index 0000000..ac5d8dd --- /dev/null +++ b/desktop/src/LanUps.Core/AgentClient.cs @@ -0,0 +1,43 @@ +using System.Net.Http.Json; +using System.Text.Json.Serialization.Metadata; + +namespace LanUps.Core; + +public sealed record ShutdownNotice(Guid Id, DateTimeOffset Deadline); +public sealed record AgentState(NutEndpoint Endpoint, UpsUpdate Update, ShutdownNotice? Pending, string? LastAction, bool DryRun); + +public static class AgentLocation +{ + public static int Port => int.TryParse(Environment.GetEnvironmentVariable("LANUPS_AGENT_PORT"), out var port) && port is > 0 and <= 65535 ? port : 47183; + public static string TokenPath => Environment.GetEnvironmentVariable("LANUPS_AGENT_TOKEN") ?? Path.Combine( + OperatingSystem.IsWindows() ? Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) : + OperatingSystem.IsMacOS() ? "/Library/Application Support" : "/etc", "LanUps", "agent.token"); +} + +public sealed class AgentClient : IDisposable +{ + private readonly HttpClient _http = new(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) + { + BaseAddress = new Uri($"http://127.0.0.1:{AgentLocation.Port}/"), Timeout = TimeSpan.FromSeconds(5) + }; + + public Task StatusAsync(CancellationToken token) => SendAsync(HttpMethod.Get, "status", null, AgentJson.Default.AgentState, token); + public Task SaveAsync(NutEndpoint endpoint, CancellationToken token) => + SendAsync(HttpMethod.Put, "endpoint", JsonContent.Create(endpoint, AgentJson.Default.NutEndpoint), AgentJson.Default.NutEndpoint, token); + public Task DiscoverAsync(string host, int port, CancellationToken token) => + SendAsync(HttpMethod.Get, $"ups?host={Uri.EscapeDataString(host)}&port={port}", null, AgentJson.Default.StringArray, token); + public Task RespondAsync(Guid id, bool confirm, CancellationToken token) => + SendAsync(HttpMethod.Post, $"shutdown/{id}/{(confirm ? "confirm" : "cancel")}", null, AgentJson.Default.String, token); + + private async Task SendAsync(HttpMethod method, string path, HttpContent? content, JsonTypeInfo type, CancellationToken cancellation) + { + using var request = new HttpRequestMessage(method, path) { Content = content }; + request.Headers.TryAddWithoutValidation("X-LanUps-Token", (await File.ReadAllTextAsync(AgentLocation.TokenPath, cancellation)).Trim()); + using var response = await _http.SendAsync(request, cancellation); + if (!response.IsSuccessStatusCode) + throw new IOException(await response.Content.ReadAsStringAsync(cancellation)); + return await response.Content.ReadFromJsonAsync(type, cancellation) ?? throw new IOException("后台服务未返回数据"); + } + + public void Dispose() => _http.Dispose(); +} diff --git a/desktop/src/LanUps.Core/AgentJson.cs b/desktop/src/LanUps.Core/AgentJson.cs new file mode 100644 index 0000000..731a62a --- /dev/null +++ b/desktop/src/LanUps.Core/AgentJson.cs @@ -0,0 +1,11 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace LanUps.Core; + +[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)] +[JsonSerializable(typeof(AgentState))] +[JsonSerializable(typeof(NutEndpoint))] +[JsonSerializable(typeof(string[]))] +[JsonSerializable(typeof(string))] +public sealed partial class AgentJson : JsonSerializerContext; diff --git a/desktop/src/LanUps.Core/LanUps.Core.csproj b/desktop/src/LanUps.Core/LanUps.Core.csproj new file mode 100644 index 0000000..b5d5886 --- /dev/null +++ b/desktop/src/LanUps.Core/LanUps.Core.csproj @@ -0,0 +1,3 @@ + + net10.0enableenable + diff --git a/desktop/src/LanUps.Core/NutMonitor.cs b/desktop/src/LanUps.Core/NutMonitor.cs new file mode 100644 index 0000000..41f7cd6 --- /dev/null +++ b/desktop/src/LanUps.Core/NutMonitor.cs @@ -0,0 +1,130 @@ +using System.Net.Sockets; +using System.Text; +using System.Text.RegularExpressions; + +namespace LanUps.Core; + +public sealed record NutEndpoint(string Host, int Port, string Name) +{ + public static NutEndpoint Default { get; } = new("192.168.5.1", 3493, "h1000m"); + + public static bool TryParse(string? host, string? port, string? name, out NutEndpoint endpoint) + { + host = host?.Trim(); + name = name?.Trim(); + if (TryServer(host, port, out var server, out var number) && + name is not null && Regex.IsMatch(name, @"\A[A-Za-z0-9_.-]{1,128}\z")) + { + endpoint = new(server, number, name); + return true; + } + endpoint = Default; + return false; + } + + public static bool TryServer(string? host, string? port, out string server, out int number) + { + server = (host ?? "").Trim(); + return int.TryParse(port, out number) && number is > 0 and <= 65535 && + Uri.CheckHostName(server) != UriHostNameType.Unknown; + } +} + +public sealed record UpsReading(DateTimeOffset At, IReadOnlyDictionary Values) +{ + public string? Get(string key) => Values.GetValueOrDefault(key); + public bool Has(string flag) => (Get("ups.status") ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains(flag, StringComparer.Ordinal); +} + +public sealed record UpsUpdate(UpsReading? LastReading, string? Error, bool NewShutdownSignal); + +public static class NutMonitor +{ + public static async Task RunAsync(NutEndpoint endpoint, Action publish, CancellationToken cancellation) + { + UpsReading? lastReading = null; + var shutdownSignalSeen = false; + while (!cancellation.IsCancellationRequested) + { + string? error = null; + var newSignal = false; + try + { + lastReading = await ReadAsync(endpoint, cancellation).ConfigureAwait(false); + var hasSignal = lastReading.Has("FSD"); + newSignal = hasSignal && !shutdownSignalSeen; + shutdownSignalSeen = hasSignal; + } + catch (Exception ex) when (ex is SocketException or IOException or OperationCanceledException) + { + cancellation.ThrowIfCancellationRequested(); + error = ex is OperationCanceledException ? "连接或读取超时" : ex.Message; + } + cancellation.ThrowIfCancellationRequested(); + publish(new(lastReading, error, newSignal)); + await Task.Delay(TimeSpan.FromSeconds(3), cancellation).ConfigureAwait(false); + } + } + + public static async Task> DiscoverAsync(string host, int port, CancellationToken cancellation) + { + var rows = await ListAsync(host, port, "LIST UPS", cancellation).ConfigureAwait(false); + var names = new List(); + foreach (var row in rows) + { + var parts = row.Split(' ', 3); + if (parts.Length != 3 || parts[0] != "UPS") + throw new IOException("NUT 返回了格式错误的 UPS 名称"); + if (Regex.IsMatch(parts[1], @"\A[A-Za-z0-9_.-]{1,128}\z")) + names.Add(parts[1]); + } + return names.Distinct(StringComparer.Ordinal).ToArray(); + } + + private static async Task ReadAsync(NutEndpoint endpoint, CancellationToken cancellation) + { + var rows = await ListAsync(endpoint.Host, endpoint.Port, $"LIST VAR {endpoint.Name}", cancellation).ConfigureAwait(false); + var values = new Dictionary(StringComparer.Ordinal); + var prefix = $"VAR {endpoint.Name} "; + foreach (var line in rows) + { + if (!line.StartsWith(prefix, StringComparison.Ordinal)) + throw new IOException("NUT 返回了格式错误的变量"); + var separator = line.IndexOf(' ', prefix.Length); + if (separator <= prefix.Length || separator + 2 >= line.Length || line[separator + 1] != '"' || line[^1] != '"') + throw new IOException("NUT 返回了格式错误的变量"); + values[line[prefix.Length..separator]] = Regex.Replace(line[(separator + 2)..^1], "\\\\([\\\\\"])", "$1"); + } + if (string.IsNullOrWhiteSpace(values.GetValueOrDefault("ups.status"))) + throw new IOException("NUT 未返回供电状态"); + return new(DateTimeOffset.Now, values); + } + + private static async Task> ListAsync(string host, int port, string request, CancellationToken cancellation) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + timeout.CancelAfter(TimeSpan.FromSeconds(3)); + var token = timeout.Token; + using var client = new TcpClient(); + await client.ConnectAsync(host, port, token).ConfigureAwait(false); + using var stream = client.GetStream(); + await stream.WriteAsync(Encoding.ASCII.GetBytes(request + "\n"), token).ConfigureAwait(false); + + using var reader = new StreamReader(stream, Encoding.UTF8); + var header = await reader.ReadLineAsync(token).ConfigureAwait(false); + if (header != $"BEGIN {request}") + throw new IOException(header ?? "NUT 服务端关闭了连接"); + + var rows = new List(); + for (var row = 0; row < 512; row++) + { + var line = await reader.ReadLineAsync(token).ConfigureAwait(false); + if (line == $"END {request}") + return rows; + if (line is null || line.StartsWith("ERR ", StringComparison.Ordinal)) + throw new IOException(line?.StartsWith("ERR ", StringComparison.Ordinal) == true ? line : "NUT 返回了不完整的读数"); + rows.Add(line); + } + throw new IOException("NUT 响应超出监控范围"); + } +} diff --git a/desktop/src/LanUps.Desktop/App.axaml b/desktop/src/LanUps.Desktop/App.axaml new file mode 100644 index 0000000..1b5ae12 --- /dev/null +++ b/desktop/src/LanUps.Desktop/App.axaml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/desktop/src/LanUps.Desktop/App.axaml.cs b/desktop/src/LanUps.Desktop/App.axaml.cs new file mode 100644 index 0000000..7a50951 --- /dev/null +++ b/desktop/src/LanUps.Desktop/App.axaml.cs @@ -0,0 +1,29 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; + +namespace LanUps.Desktop; + +public sealed partial class App : Application +{ + public override void Initialize() => AvaloniaXamlLoader.Load(this); + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + desktop.MainWindow = new MainWindow(desktop.Args?.Contains("--tray", StringComparer.Ordinal) == true); + base.OnFrameworkInitializationCompleted(); + } + + private void ShowDashboard(object? sender, EventArgs args) + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow: MainWindow window }) + window.Restore(); + } + + private void ExitDesktop(object? sender, EventArgs args) + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + desktop.Shutdown(); + } +} diff --git a/desktop/src/LanUps.Desktop/Assets/ups.ico b/desktop/src/LanUps.Desktop/Assets/ups.ico new file mode 100644 index 0000000000000000000000000000000000000000..c67d95b79cac7bc4cf900edfea02e914353d34d1 GIT binary patch literal 10012 zcmaiY2{=^m+y9wk#xnMul06YwzFMpqvW4tfvQ3L6$(kkGjHRrh5R$Ep?2^bf6B1bq zp~4ih@7c%9|BUke|E}wOulG0Cb>_@-?)|<$_x(I`000Ki04yv3bQc6}!2rMy0017I zKWh*KfLZ97px~c%GPItj0svXrKkHiPH-;JjP^draVmJUOA^`x4{j=tx1%OE=NFns0 z=of~aA>jIp5(Bk~Z$2{4}5)ij0f5CveNg>(S|YvjuiyYhKWb@PD7S$#M?Ds>j> z<)E|>stOh<_&bfHN){=mNbH?EewU_Cn?2tYmNOa0+EC)1)CHMXEWB+Y|(?~ z{O}R;I+fBn`A~-*L_%+u%qD0fWNdBN)GwdmMi=f*I=cTxsH!+?I zy)&srW6M*sJHN2^<*%^3Sq4iYhLOwGTTk~|X}(S=ptmAVi&6U>-igtM4!0|4t zeSn?gyu#u)Lw708^EQo_xp&}Xhs>7zsSqDLK~9b~Gbr+laHoez`lx^45qUmYPZUFw z^l84~<@%y2BRlme$3gkMx|Sq1n%_5B&*_yIIR@&pp3}I$D-vWOPB*d(Yd*m}lk)B= zC8xl7Ekn&x4RrYbl5?oa0MCBT3I3{EP|n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;Xw=+Vv;sc7;xIht+jg&hY4>ZQ!3F(z1dmkklzD@kSFxi&aZ^@;o) z^CZ;-MA-!kkR~ZVTo)9G9g@n9H=y`j&SHM$ypal!QFhb^j0Y?njCP&v-o#|{&N%4i zUetau5`~%kC=Sal_S>s>@NGq2@(cZ sAG>Fh^SAjQHcYD~Q-OTm|MNfg{vYqjn|lJQ;YDu;6oQ)m^98~G16nubIRF3v literal 0 HcmV?d00001 diff --git a/desktop/src/LanUps.Desktop/Assets/ups.png b/desktop/src/LanUps.Desktop/Assets/ups.png new file mode 100644 index 0000000000000000000000000000000000000000..e47696a4d02dc4661b9c6f14d02a8b2e93755b44 GIT binary patch literal 4129 zcmZWsdpwls7k}o>G#R4HNJ_L_i8YmW-80$fVleKNWZE#c3sMtBX3A~~r9ucZQ?^XW zEeQ=~WRr4jT~=k7iVSjDcHCyn`+HxRe*5|CAJ6A~-_LWNbI$ji?>XmruTUI!EySc?)cNT{vyms03dAz-H^TSKFx_I>=dQ*FSdqxL<7O%#A2bjerE_w(-z; zZ*%e{$bhon!d`H(SM87`Rp-e7=J1)?fwfD)y5?)WkXE!VH+FbQP2kxRz7X@>q#;J- zmPOb}rqPImyqY&v#8L(;K7DGw5Lczn726AJ;aku-l{<9to{=36n$xcf?9)Q8O4 zErCUBy{5on95*lcPG1!}+eB5gp#J=}6yZO6fymx9+S)USAlT9h8wn~mV6=CYN5ghJ zX;%Pa5y(%Xj;)1sT!QG1&sI7C&T-%0`59_kh1?@#O@6sAY-x@yp_PO9YB-$ z9z3aB8E7~IQZ%|=XbRL}E%3zk%ZK3yCSdhmNjx;@)3E9|AkkZ`m230>XAoIcYw#R6 zzC#J**kZscyScT@6)+kRr3V&cgEKS)^fQaW3B^9LN9;vx=Uj$L+VG+Syamjscfq18 zIGWa@MbW}CO+VCL9aZJVK_q&WcRU3Qq9=MbaCk9Q{C!~Bkh|_K$Sr_Ms*Nr>t{934 zidyCOLx??~{LJfzLK%Oj$~r=q>d`A@-JFD*xJy7>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$K-C9=51KShCIq;8Dhx%Cxo$4+c zB={PxJN!Yoq8(Z7b_Qd?6GUT01J^-5tkDmo_(FAG%^`WP3>F2&N2oj0E9M98jjq(J z{U=vN2j(u5j=`2fq_7nd2gsN>T^S;ifXbjFFddDvkcW&w@3VGAA1(nU~r=7^hi z_g=)en%vtc?w|3ZJ4ji+)?jYW+M5LJE0YcsW-EgF5--wL47{ZMDpZ6>I|6&^xMS<> zkP_NdFB1)CNxM^9zv=!%$QYlSuR3T=>j7x*5hSW# zYt7lOB+_#V#~AN&@0Dy-gnCmUGKjOY6f?(7-wVvJza-Hl+fa!Y1i=M`<2I!@hF6bS z`M2orE#<*8qv@RrAhmdrp#sQnE};zEzhrGv*>I~?xnjIzK7Rr&XME{ho%K?Iqy|B< zIU;;7rtJGh?&gF1Q?G?S>^B2w9NGpU@x!I7L^PO)IL3qE$GP zjs2F_Gr==oKMc1}@LLMho|eWOHys_yYn*3>=h$yR66bqCg+NM1*g6wXY>Df*tjBE5 z0glD79F3UbnNK`^lwt7N`(UWifn=fjSD;Us)S?D5L2u)VwFWP;nCL-n+27-Vc=Nwj z{$*%#ob~Vf`Z9N5gengWq^7+uPEs%Id?YnvI!Ou(h&Dt?)v zn-RmA85l6WmjBqmf<92A1d86k9gMq4&Jf8vLRa2{z8oDimDL(p_#H#=1#D-0W`14^rhkCT+<{qzb;tIuaQ$KCF}Fq+ZxS`Wi{bY`Z^=Zs(M@cb5{k?5_gLlR&7 zIH4H%4ND2=jjBjV$|y54!HDyRR>@ioG8Z&iX(LZB!;3efg48I{&efH~;uy_M(%a=! zpF&Nw0HWIYFOM|~Xrs1ikm#?`^gtGzHKlW_Tx^vv57G|#??3kJk9W_B8Qsx~*`=+f T;m?s@f3U~aac8a#_2T~kDoV65 literal 0 HcmV?d00001 diff --git a/desktop/src/LanUps.Desktop/CloseDialog.axaml b/desktop/src/LanUps.Desktop/CloseDialog.axaml new file mode 100644 index 0000000..99ca112 --- /dev/null +++ b/desktop/src/LanUps.Desktop/CloseDialog.axaml @@ -0,0 +1,15 @@ + + + + + + + + +