packServer/desktop/Services/Agent/ServiceInstaller.cs
liufumingren bca8f7270c 本机预览/云台/拉通道全部改走 WebSocket(桌面 1.0.75)
桌面端
- 新增 LocalWsServer(ws://127.0.0.1:17301):hello / ping / get_channels /
  start_preview / stop_preview / open_window / close_window / ptz / ptz_preset,
  一条连接可同时推多路 JPEG 帧(帧头带 sid);慢命令并发派发,云台命令按连接串行,
  页面断开自动清理会话与满帧率窗口
- LocalHttpServer 删除预览(MJPEG/快照/满帧率窗口)、/api/hik/channels、/api/hik/ptz*,
  HTTP 17300 只保留 /api/query/{code}、/api/activate-login、/api/playback/download,
  其余 POST 统一回 404 并提示已迁到 WS;不再依赖 HCNetSDK
- App 自行组装 HikStreamService -> HikPreviewService + HikNativePreviewService 注入 WS
- 后台服务加固:框架依赖(开发版)安装/启动时自动写服务环境变量 DOTNET_ROOT,
  避免 LocalSystem 找不到用户目录里的 .NET 8 而报「后台服务启动超时」

前端
- 新增 api/localWs.ts(连接/断线/请求-响应/二进制帧分发),补 getChannels / openWindow /
  closeWindow / ptz / ptzPreset
- CamerasView 预览只走 WS(保留「唤起本机软件 -> 等待 -> 提示安装」兜底),
  满帧率窗口、云台、预置点改走 WS
- NvrsView 拉取通道改走 WS(连不上时自动唤起一次再重试)
- CameraLayoutCanvas 合成画面 4 路改 WS 推帧
- 删除 createHikPreview/closeHikPreview*/openHikWindow/closeHikWindow*/ptzControl/ptzPreset
  与 isLocalServiceAlive/waitForLocalService

其他
- 移除 cameras.has_ptz(迁移 20261019233000)与相关接口/字段/UI
- 通道号按 struStreamMode 映射(IP 通道空槽导致 51 之后整体错位)
- 扫码 24 小时内只保留最后一次扫描(后上报时间更新时覆盖)
- 清理历史 DESKTOP 占位通道(迁移 20261019230000)
- README / desktop README 补 17301 与 WS 接口说明,修正已删除的 /api/health 描述
2026-10-20 00:47:31 +08:00

574 lines
21 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace YuncangTrace.LocalService.Services;
/// <summary>Windows 服务当前状态(SCM 的 dwCurrentState)</summary>
public enum AgentServiceState
{
Unknown = 0,
NotInstalled,
Stopped,
StartPending,
StopPending,
Running,
}
/// <summary>
/// 「扫码后台服务」的安装/卸载/启停(服务名 <c>YuncangTraceAgent</c>)。
///
/// 设计要点:
/// - **服务跑自己的 exe 副本**(<c>%ProgramData%\YuncangTrace\agent\YuncangTraceAgent.exe</c>),
/// MSI 升级替换安装目录的 exe 时不会撞「文件被占用」;
/// - 安装/卸载/启停都需要管理员权限 → 用 <c>runas</c> 起一个临时进程执行(**只在这些操作时弹 UAC**);
/// - 服务以 <c>LocalSystem</c> 自动启动,用户注销/退出桌面端不影响扫码上报。
/// </summary>
public static class ServiceInstaller
{
public const string ServiceName = "YuncangTraceAgent";
public const string DisplayName = "云仓视频溯源-扫码服务";
/// <summary>提权 helper 的命令行标记</summary>
private const string ControlArg = "--agent-control";
private const int ErrorCancelled = 1223;
private sealed class HelperResult
{
public bool Ok { get; set; }
public string Message { get; set; } = "";
}
/// <summary>这次启动是不是「服务管理 helper」</summary>
public static bool IsHelperCall(string[] args)
=> args.Length > 0 && args[0].Equals(ControlArg, StringComparison.OrdinalIgnoreCase);
/// <summary>服务是否已注册(读注册表,普通权限即可)</summary>
public static bool IsInstalled
{
get
{
try
{
using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{ServiceName}");
return key is not null;
}
catch
{
return false;
}
}
}
/// <summary>服务是否正在运行</summary>
public static bool IsRunning => QueryState() == AgentServiceState.Running;
/// <summary>服务副本是否和当前程序版本不一致(升级后需要更新)</summary>
public static bool NeedsBinaryUpdate
{
get
{
try
{
var source = Environment.ProcessPath;
if (string.IsNullOrEmpty(source) || !File.Exists(source)) return false;
if (!File.Exists(AgentPaths.AgentExe)) return true;
var running = FileVersionInfo.GetVersionInfo(AgentPaths.AgentExe).FileVersion ?? "";
var current = FileVersionInfo.GetVersionInfo(source).FileVersion ?? "";
if (!string.Equals(running, current, StringComparison.OrdinalIgnoreCase)) return true;
return new FileInfo(source).Length != new FileInfo(AgentPaths.AgentExe).Length;
}
catch
{
return true;
}
}
}
// ==================== 桌面端调用(会弹 UAC) ====================
public static Task<(bool Ok, string Message)> InstallOrUpdateAsync(CancellationToken ct = default)
=> RunElevatedAsync("install", ct);
public static Task<(bool Ok, string Message)> UninstallAsync(CancellationToken ct = default)
=> RunElevatedAsync("uninstall", ct);
public static Task<(bool Ok, string Message)> StartAsync(CancellationToken ct = default)
=> RunElevatedAsync("start", ct);
public static Task<(bool Ok, string Message)> StopAsync(CancellationToken ct = default)
=> RunElevatedAsync("stop", ct);
private static async Task<(bool Ok, string Message)> RunElevatedAsync(string action, CancellationToken ct)
{
var exe = Environment.ProcessPath;
if (string.IsNullOrEmpty(exe)) return (false, "找不到当前程序路径,无法请求管理员权限");
var resultFile = Path.Combine(Path.GetTempPath(), $"yuncang_agent_{Guid.NewGuid():N}.json");
try
{
var psi = new ProcessStartInfo(exe, $"{ControlArg} {action} \"{resultFile}\"")
{
UseShellExecute = true, // runas 只能走 ShellExecute
Verb = "runas",
WindowStyle = ProcessWindowStyle.Hidden,
};
using var process = await Task.Run(() => Process.Start(psi), ct).ConfigureAwait(false);
if (process is null) return (false, "提权进程启动失败");
await process.WaitForExitAsync(ct).ConfigureAwait(false);
var result = ReadResult(resultFile);
return result is null
? (false, $"操作没有返回结果(退出码 {process.ExitCode})")
: (result.Ok, result.Message);
}
catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)
{
return (false, "已取消管理员授权(安装/管理后台服务需要管理员权限)");
}
catch (Exception ex)
{
return (false, ex.Message);
}
finally
{
TryDelete(resultFile);
}
}
// ==================== 提权 helper 入口 ====================
/// <summary>
/// 提权后的实际执行体:<c>--agent-control install|uninstall|start|stop "&lt;结果文件&gt;"</c>
/// </summary>
public static void RunHelper(string[] args)
{
var action = args.Length > 1 ? args[1].ToLowerInvariant() : "";
var resultFile = args.Length > 2 ? args[2] : "";
HelperResult result;
try
{
result = action switch
{
"install" => InstallCore(),
"uninstall" => UninstallCore(),
"start" => StartCore(),
"stop" => StopCore(),
_ => new HelperResult { Ok = false, Message = $"未知操作:{action}" },
};
}
catch (Exception ex)
{
result = new HelperResult { Ok = false, Message = ex.Message };
}
if (resultFile.Length > 0)
{
try
{
File.WriteAllText(resultFile, JsonSerializer.Serialize(result));
}
catch (Exception ex)
{
AppLog.Write($"[agent] 写服务管理结果失败:{ex.Message}");
}
}
AppLog.Write($"[agent] 服务管理({action}):{(result.Ok ? "成功" : "失败")} {result.Message}");
}
private static HelperResult InstallCore()
{
if (!ClockSyncService.IsElevated) return Fail("提权失败:当前进程不是管理员权限");
var source = Environment.ProcessPath;
if (string.IsNullOrEmpty(source) || !File.Exists(source)) return Fail("找不到当前程序 exe");
Directory.CreateDirectory(AgentPaths.MachineRoot);
Directory.CreateDirectory(AgentPaths.AgentDir);
// 桌面端(普通用户)要能写 agent.json / channels.json / 命令文件,并读状态
RunTool("icacls.exe", AgentPaths.MachineRoot, "/grant", "*S-1-5-32-545:(OI)(CI)M", "/T", "/C", "/Q");
// 先停旧服务,才能替换副本 exe
StopCore();
WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled,
TimeSpan.FromSeconds(15));
// 服务进程退出后文件句柄还要几十毫秒才释放 → 重试几次
Exception? copyError = null;
for (var attempt = 0; attempt < 20; attempt++)
{
try
{
CopyAgentFiles(source);
copyError = null;
break;
}
catch (Exception ex)
{
copyError = ex;
Thread.Sleep(500);
}
}
if (copyError is not null) return Fail($"复制后台服务程序失败:{copyError.Message}");
var binPath = $"\"{AgentPaths.AgentExe}\" --service";
if (!IsInstalled)
{
var create = RunSc("create", ServiceName,
"binPath=", binPath,
"start=", "auto",
"DisplayName=", DisplayName);
// 1072 = 服务标记为删除(上一次卸载还没完全生效)→ 等一会重试
for (var i = 0; i < 20 && create.Code == 1072; i++)
{
Thread.Sleep(500);
create = RunSc("create", ServiceName,
"binPath=", binPath,
"start=", "auto",
"DisplayName=", DisplayName);
}
if (create.Code != 0) return Fail($"创建服务失败({create.Code}):{create.Output}");
}
else
{
var config = RunSc("config", ServiceName, "binPath=", binPath, "start=", "auto");
if (config.Code != 0) return Fail($"更新服务配置失败({config.Code}):{config.Output}");
}
RunSc("description", ServiceName, "云仓视频溯源扫码服务(后台收码/上报,退出桌面端后仍运行)");
// 崩溃自动重启:5s → 10s → 30s
RunSc("failure", ServiceName, "reset=", "86400",
"actions=", "restart/5000/restart/10000/restart/30000");
// ⚠️ 开发版(框架依赖)必须告诉服务 .NET 装在哪:
// 服务以 LocalSystem 跑,看不到当前用户 PATH / DOTNET_ROOT,
// apphost 会直接报「You must install .NET」→ 服务永远进不了 Running → 桌面提示“后台服务启动超时”。
EnsureServiceDotnetEnvironment();
var start = StartCore();
if (!start.Ok) return start;
return new HelperResult
{
Ok = true,
Message = $"后台服务已安装并启动:{AgentPaths.AgentExe}",
};
}
/// <summary>
/// 开发版(框架依赖)装服务时,把 .NET 运行时目录写进服务的环境变量。
///
/// 服务以 <c>LocalSystem</c> 身份运行:看不到当前用户目录里的 .NET(本机 8.0 装在
/// <c>%LOCALAPPDATA%\Microsoft\dotnet</c>),apphost 直接报 “You must install .NET” 并退出 →
/// SCM 状态一直进不了 Running → 桌面端只会看到「后台服务启动超时」。
///
/// 自包含单文件发布不需要(运行时就在 exe 里)。
/// </summary>
private static void EnsureServiceDotnetEnvironment()
{
try
{
var sourceDir = Path.GetDirectoryName(Environment.ProcessPath ?? string.Empty) ?? string.Empty;
var frameworkDependent = File.Exists(Path.Combine(sourceDir, "YuncangTrace.LocalService.dll"));
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
$@"SYSTEM\CurrentControlSet\Services\{ServiceName}", writable: true);
if (key is null) return;
if (!frameworkDependent)
{
// 换回自包含版时把上次写的值清掉,避免指到一个不存在的目录
if (key.GetValue("Environment") is not null) key.DeleteValue("Environment", throwOnMissingValue: false);
return;
}
var runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location); // ...\shared\Microsoft.NETCore.App\8.0.x
if (runtimeDir is null) return;
var dotnetRoot = Path.GetFullPath(Path.Combine(runtimeDir, "..", ".."));
if (!File.Exists(Path.Combine(dotnetRoot, "dotnet.exe"))) return;
key.SetValue("Environment",
new[] { $"DOTNET_ROOT={dotnetRoot}", $"PATH={dotnetRoot};%PATH%" },
Microsoft.Win32.RegistryValueKind.MultiString);
AppLog.Write($"[agent] 开发版服务已写入 DOTNET_ROOT={dotnetRoot}");
}
catch (Exception ex)
{
AppLog.Write($"[agent] 写服务 DOTNET_ROOT 失败:{ex.Message}");
}
}
private static HelperResult UninstallCore()
{
if (!ClockSyncService.IsElevated) return Fail("提权失败:当前进程不是管理员权限");
StopCore();
WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled,
TimeSpan.FromSeconds(15));
if (IsInstalled)
{
var delete = RunSc("delete", ServiceName);
if (delete.Code != 0 && delete.Code != 1060)
{
return Fail($"删除服务失败({delete.Code}):{delete.Output}");
}
// sc delete 是异步的:等注册表项真的消失,避免下次安装报 1072(标记为删除)
for (var i = 0; i < 40 && IsInstalled; i++) Thread.Sleep(250);
}
// 只删「服务程序 + 服务专用文件」,通道/扫码记录保留给桌面端回写
foreach (var file in new[]
{
AgentPaths.ConfigFile, AgentPaths.TokenFile, AgentPaths.StatusFile,
AgentPaths.CommandFile, AgentPaths.DiscoveredFile,
})
{
TryDelete(file);
}
TryDeleteDirectory(AgentPaths.AgentDir);
return new HelperResult { Ok = true, Message = "后台服务已卸载" };
}
private static HelperResult StartCore()
{
if (!IsInstalled) return Fail("服务未安装");
// ⚠️ 每次启动前都补齐 .NET 环境变量:服务副本可能是开发版(框架依赖),
// 而 `.NET Runtime` 事件里只会看到 “You must install .NET”,界面上则表现为「启动超时」。
EnsureServiceDotnetEnvironment();
var (code, output) = RunSc("start", ServiceName);
// 1056 = 已在运行;1053 = 已受理但还没进入 Running(下面轮询确认)
if (code is not (0 or 1056 or 1053)) return Fail($"启动服务失败({code}):{output}");
return WaitForState(state => state == AgentServiceState.Running, TimeSpan.FromSeconds(20))
? new HelperResult { Ok = true, Message = "后台服务已启动" }
: Fail("后台服务启动超时(查看 事件查看器/服务日志)");
}
private static HelperResult StopCore()
{
if (!IsInstalled) return new HelperResult { Ok = true, Message = "服务未安装,无需停止" };
var (code, output) = RunSc("stop", ServiceName);
// 1062 = 服务未启动;1073 = 已停止
if (code is not (0 or 1062 or 1073)) return Fail($"停止服务失败({code}):{output}");
return WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled,
TimeSpan.FromSeconds(15))
? new HelperResult { Ok = true, Message = "后台服务已停止" }
: Fail("后台服务停止超时");
}
private static HelperResult Fail(string message) => new() { Ok = false, Message = message };
/// <summary>
/// 把当前程序复制到 ProgramData 作为服务副本。
/// 单文件发布只复制一个 exe;开发环境(framework-dependent)连 dll/json 一起复制,
/// 但不复制 <c>native</c>(服务不跑 ffmpeg / 海康 SDK)。
/// </summary>
private static void CopyAgentFiles(string source)
{
var sourceDir = Path.GetDirectoryName(source)
?? throw new InvalidOperationException("取不到程序目录");
var singleFile = !File.Exists(Path.Combine(sourceDir, "YuncangTrace.LocalService.dll"));
foreach (var file in Directory.EnumerateFiles(AgentPaths.AgentDir))
{
try
{
File.Delete(file);
}
catch
{
// 旧文件删不掉就覆盖写
}
}
if (singleFile)
{
File.Copy(source, AgentPaths.AgentExe, overwrite: true);
return;
}
foreach (var file in Directory.EnumerateFiles(sourceDir))
{
var extension = Path.GetExtension(file).ToLowerInvariant();
if (extension is not (".exe" or ".dll" or ".json")) continue;
if (Path.GetFileName(file).Contains("ffmpeg", StringComparison.OrdinalIgnoreCase)) continue;
File.Copy(file, Path.Combine(AgentPaths.AgentDir, Path.GetFileName(file)), overwrite: true);
}
if (!File.Exists(AgentPaths.AgentExe)) File.Copy(source, AgentPaths.AgentExe, overwrite: true);
}
// ==================== 状态查询(SCM,无需管理员) ====================
public static AgentServiceState QueryState()
{
IntPtr manager = IntPtr.Zero;
IntPtr service = IntPtr.Zero;
try
{
manager = OpenSCManager(null, null, ScManagerConnect);
if (manager == IntPtr.Zero) return AgentServiceState.Unknown;
service = OpenService(manager, ServiceName, ServiceQueryStatus);
if (service == IntPtr.Zero) return AgentServiceState.NotInstalled;
if (!QueryServiceStatus(service, out var status)) return AgentServiceState.Unknown;
return status.dwCurrentState switch
{
1 => AgentServiceState.Stopped,
2 => AgentServiceState.StartPending,
3 => AgentServiceState.StopPending,
4 => AgentServiceState.Running,
_ => AgentServiceState.Unknown,
};
}
catch
{
return AgentServiceState.Unknown;
}
finally
{
if (service != IntPtr.Zero) CloseServiceHandle(service);
if (manager != IntPtr.Zero) CloseServiceHandle(manager);
}
}
private static bool WaitForState(Func<AgentServiceState, bool> predicate, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (predicate(QueryState())) return true;
Thread.Sleep(250);
}
return predicate(QueryState());
}
// ==================== 工具 ====================
private static (int Code, string Output) RunSc(params string[] args) => RunTool("sc.exe", args);
private static (int Code, string Output) RunTool(string file, params string[] args)
{
try
{
var psi = new ProcessStartInfo(file)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var arg in args) psi.ArgumentList.Add(arg);
using var process = Process.Start(psi);
if (process is null) return (-1, $"{file} 启动失败");
var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
process.WaitForExit();
return (process.ExitCode, output.Trim());
}
catch (Exception ex)
{
return (-1, ex.Message);
}
}
private static HelperResult? ReadResult(string path)
{
try
{
if (!File.Exists(path)) return null;
var text = File.ReadAllText(path);
return string.IsNullOrWhiteSpace(text) ? null : JsonSerializer.Deserialize<HelperResult>(text);
}
catch
{
return null;
}
}
private static void TryDelete(string path)
{
try
{
if (File.Exists(path)) File.Delete(path);
}
catch
{
// 忽略
}
}
private static void TryDeleteDirectory(string path)
{
try
{
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
}
catch
{
// 文件还被占用时下次安装会覆盖,不必强求
}
}
// ==================== Win32 ====================
private const uint ScManagerConnect = 0x0001;
private const uint ServiceQueryStatus = 0x0004;
[StructLayout(LayoutKind.Sequential)]
private struct ServiceStatus
{
public uint dwServiceType;
public uint dwCurrentState;
public uint dwControlsAccepted;
public uint dwWin32ExitCode;
public uint dwServiceSpecificExitCode;
public uint dwCheckPoint;
public uint dwWaitHint;
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenSCManager(string? machineName, string? databaseName, uint desiredAccess);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenService(IntPtr manager, string serviceName, uint desiredAccess);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool QueryServiceStatus(IntPtr service, out ServiceStatus status);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CloseServiceHandle(IntPtr handle);
}