? Log;
+
+ public LocalHttpServer(OrderQueryService queryService)
+ {
+ _queryService = queryService;
+ }
+
+ /// 浏览器里可直接打开的地址
+ public string BaseUrl => $"http://localhost:{Port}";
+
+ public bool IsRunning => _listener.IsListening;
+
+ /// 启动监听;失败抛 (端口被占 / 没权限)
+ public void Start()
+ {
+ if (IsRunning) return;
+
+ _listener.Prefixes.Clear();
+ // 两个都监听:前端页面默认用 localhost,但改 VITE_LOCAL_SERVICE 用 127.0.0.1 时也得能连
+ // (HttpListener 只接受 "注册过的 host",否则直接 400)
+ _listener.Prefixes.Add($"{BaseUrl}/");
+ _listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
+ _listener.Start();
+
+ _cts = new CancellationTokenSource();
+ _loop = Task.Run(() => AcceptLoopAsync(_cts.Token));
+
+ Log?.Invoke($"服务已启动:{BaseUrl}");
+ }
+
+ public void Stop()
+ {
+ if (!IsRunning) return;
+
+ try
+ {
+ _cts?.Cancel();
+ _listener.Stop();
+ _listener.Close();
+ }
+ catch (Exception ex)
+ {
+ Log?.Invoke($"停止服务时出错:{ex.Message}");
+ }
+ finally
+ {
+ Log?.Invoke("服务已停止");
+ }
+ }
+
+ private async Task AcceptLoopAsync(CancellationToken token)
+ {
+ while (!token.IsCancellationRequested && _listener.IsListening)
+ {
+ HttpListenerContext context;
+ try
+ {
+ context = await _listener.GetContextAsync().ConfigureAwait(false);
+ }
+ catch (Exception)
+ {
+ // Stop()/Close() 会让 GetContextAsync 抛异常,属于正常退出路径
+ break;
+ }
+
+ _ = Task.Run(() => HandleAsync(context), CancellationToken.None);
+ }
+ }
+
+ private async Task HandleAsync(HttpListenerContext context)
+ {
+ var request = context.Request;
+ var response = context.Response;
+
+ try
+ {
+ WriteCorsHeaders(request, response);
+
+ // 预检请求(含 PNA 预检)直接放行
+ if (request.HttpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
+ {
+ response.StatusCode = 204;
+ response.Close();
+ return;
+ }
+
+ var path = request.Url?.AbsolutePath ?? "/";
+ Log?.Invoke($"{request.HttpMethod} {path} ← {request.RemoteEndPoint?.Address}");
+
+ if (!request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
+ {
+ await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 GET" }).ConfigureAwait(false);
+ return;
+ }
+
+ if (path.Equals("/api/health", StringComparison.OrdinalIgnoreCase)
+ || path.Equals("/api/health/", StringComparison.OrdinalIgnoreCase))
+ {
+ await WriteJsonAsync(response, 200, new
+ {
+ ok = true,
+ name = "云仓视频溯源打印服务",
+ version = typeof(LocalHttpServer).Assembly.GetName().Version?.ToString() ?? "1.0.0",
+ port = Port,
+ serverTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
+ }).ConfigureAwait(false);
+ return;
+ }
+
+ const string queryPrefix = "/api/query/";
+ if (path.StartsWith(queryPrefix, StringComparison.OrdinalIgnoreCase))
+ {
+ var code = Uri.UnescapeDataString(path[queryPrefix.Length..]).Trim();
+ var result = _queryService.Query(code);
+
+ if (result.Ok)
+ {
+ await WriteJsonAsync(response, 200, result.Data).ConfigureAwait(false);
+ }
+ else
+ {
+ await WriteJsonAsync(response, result.StatusCode, new { ok = false, message = result.Message }).ConfigureAwait(false);
+ }
+ return;
+ }
+
+ // 浏览器直接打开本机服务时给一个说明页(方便排查、也是手工测试入口)
+ if (path == "/" || path.Equals("/index.html", StringComparison.OrdinalIgnoreCase))
+ {
+ var html = """
+
+ 云仓视频溯源软件(本机服务)
+
+ 云仓视频溯源软件(本机服务)
+ 服务运行中,只监听本机(127.0.0.1:17311)。
+
+ """;
+ await WriteHtmlAsync(response, 200, html).ConfigureAwait(false);
+ return;
+ }
+
+ await WriteJsonAsync(response, 404, new { ok = false, message = "接口不存在" }).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ Log?.Invoke($"处理请求出错:{ex.Message}");
+ try
+ {
+ await WriteJsonAsync(response, 500, new { ok = false, message = "本机服务内部错误" }).ConfigureAwait(false);
+ }
+ catch
+ {
+ // 响应已经发出去 / 连接断了,忽略
+ }
+ }
+ finally
+ {
+ try
+ {
+ response.Close();
+ }
+ catch
+ {
+ // 忽略
+ }
+ }
+ }
+
+ /// CORS + 私有网络访问(PNA)头
+ private static void WriteCorsHeaders(HttpListenerRequest request, HttpListenerResponse response)
+ {
+ // 回显 Origin(比写死 * 更稳:以后要带 cookie/凭据也能用)
+ var origin = request.Headers["Origin"];
+ response.Headers["Access-Control-Allow-Origin"] = string.IsNullOrEmpty(origin) ? "*" : origin;
+ response.Headers["Vary"] = "Origin";
+ response.Headers["Access-Control-Allow-Methods"] = "GET, OPTIONS";
+ response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Accept";
+ response.Headers["Access-Control-Max-Age"] = "600";
+
+ // 公网页面访问 localhost 时,Chrome 会带 Access-Control-Request-Private-Network: true
+ if (string.Equals(request.Headers["Access-Control-Request-Private-Network"], "true", StringComparison.OrdinalIgnoreCase))
+ {
+ response.Headers["Access-Control-Allow-Private-Network"] = "true";
+ }
+ }
+
+ private static async Task WriteJsonAsync(HttpListenerResponse response, int statusCode, object? payload)
+ {
+ var body = JsonUtil.ToJson(payload);
+ await WriteTextAsync(response, statusCode, "application/json; charset=utf-8", body).ConfigureAwait(false);
+ }
+
+ private static async Task WriteHtmlAsync(HttpListenerResponse response, int statusCode, string html)
+ {
+ await WriteTextAsync(response, statusCode, "text/html; charset=utf-8", html).ConfigureAwait(false);
+ }
+
+ private static async Task WriteTextAsync(HttpListenerResponse response, int statusCode, string contentType, string body)
+ {
+ var bytes = Encoding.UTF8.GetBytes(body);
+
+ response.StatusCode = statusCode;
+ response.ContentType = contentType;
+ response.ContentEncoding = Encoding.UTF8;
+ response.Headers["Cache-Control"] = "no-store";
+ response.ContentLength64 = bytes.Length;
+
+ await response.OutputStream.WriteAsync(bytes).ConfigureAwait(false);
+ }
+
+ public void Dispose()
+ {
+ Stop();
+ _cts?.Dispose();
+ _listener.Close();
+ }
+}
diff --git a/desktop/Services/OrderQueryService.cs b/desktop/Services/OrderQueryService.cs
new file mode 100644
index 0000000..b5bac60
--- /dev/null
+++ b/desktop/Services/OrderQueryService.cs
@@ -0,0 +1,48 @@
+namespace YuncangTrace.LocalService.Services;
+
+/// 一次查询的结果(HTTP 层和界面都复用)
+/// 是否查到
+/// HTTP 状态码(200 / 400 / 404 / 500)
+/// 失败原因
+/// 成功时的数据(**平铺**一个对象,前端按「项目/值」两列直接渲染)
+public sealed record QueryResult(bool Ok, int StatusCode, string Message, object? Data)
+{
+ public static QueryResult Success(object data) => new(true, 200, "ok", data);
+
+ public static QueryResult BadRequest(string message) => new(false, 400, message, null);
+
+ public static QueryResult NotFound(string message) => new(false, 404, message, null);
+
+ public static QueryResult Failed(string message) => new(false, 500, message, null);
+}
+
+///
+/// 按运单号查信息
+///
+/// ⚠️ **这里是接你们真实数据的地方**:现在返回演示数据(任何 code 都返回同一份)。
+/// 真实实现通常是:查本地 SQLite / 扫描本地打包视频目录 / 调内部接口,
+/// 然后把结果按字段平铺返回(前端页面按 key-value 展示,字段随你加)。
+///
+public sealed class OrderQueryService
+{
+ public QueryResult Query(string? code)
+ {
+ var value = (code ?? string.Empty).Trim();
+ if (value.Length == 0) return QueryResult.BadRequest("缺少运单号");
+
+ // ↓↓↓ 换成真实查询逻辑 ↓↓↓
+ var data = new Dictionary
+ {
+ ["code"] = value,
+ ["orderNo"] = "SO-20261017-001",
+ ["channel"] = "CH-1",
+ ["printStatus"] = "已打印",
+ ["scanTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
+ ["videoPath"] = @"D:\video\2026-10-17\demo.mp4",
+ ["source"] = "演示数据(请替换 OrderQueryService.Query)",
+ };
+ // ↑↑↑ 换成真实查询逻辑 ↑↑↑
+
+ return QueryResult.Success(data);
+ }
+}
diff --git a/desktop/Services/ProtocolHelper.cs b/desktop/Services/ProtocolHelper.cs
new file mode 100644
index 0000000..1c33d1d
--- /dev/null
+++ b/desktop/Services/ProtocolHelper.cs
@@ -0,0 +1,98 @@
+using Microsoft.Win32;
+
+namespace YuncangTrace.LocalService.Services;
+
+///
+/// 自定义协议(URL Scheme)——「网页叫醒本机应用」的唯一合法方式
+///
+/// 网页里写 yuncang://open?code=123,浏览器问一句「要打开云仓视频溯源软件吗?」,
+/// 系统就会按注册表 HKCU\Software\Classes\yuncang\shell\open\command 找到本 exe 并拉起,
+/// 形如:"C:\...\YuncangTrace.LocalService.exe" "yuncang://open?code=123"
+///
+/// 注意:
+/// - 网页**不能**直接执行 exe,也不能拿到返回值(所以还要配合 127.0.0.1 上的 HTTP 服务);
+/// - 协议注册在 HKCU,**不需要管理员权限**;
+/// - 卸载时应该调用 把注册表清掉。
+///
+public static class ProtocolHelper
+{
+ /// 协议名(前端用 VITE_APP_PROTOCOL 对齐;改了这里要一起改)
+ public const string Scheme = "yuncang";
+
+ /// 资源管理器 / 浏览器的提示名
+ public const string DisplayName = "云仓视频溯源软件";
+
+ /// 拼出唤醒地址:yuncang://open?code=xxx
+ public static string LaunchUrl(string? code)
+ {
+ return string.IsNullOrWhiteSpace(code)
+ ? $"{Scheme}://open"
+ : $"{Scheme}://open?code={Uri.EscapeDataString(code)}";
+ }
+
+ /// 从命令行参数里找出协议地址(被协议拉起时 Windows 会把它作为第一个参数)
+ public static string? FirstLaunchUrl(IEnumerable args)
+ {
+ return args.FirstOrDefault(arg =>
+ arg.StartsWith($"{Scheme}://", StringComparison.OrdinalIgnoreCase));
+ }
+
+ /// 从 yuncang://open?code=xxx 里取出 code(没有就返回 null)
+ public static string? ParseCode(string? url)
+ {
+ if (string.IsNullOrWhiteSpace(url)) return null;
+
+ var index = url.IndexOf('?');
+ if (index < 0 || index == url.Length - 1) return null;
+
+ foreach (var pair in url[(index + 1)..].Split('&', StringSplitOptions.RemoveEmptyEntries))
+ {
+ var parts = pair.Split('=', 2);
+ if (parts.Length == 2 && parts[0].Equals("code", StringComparison.OrdinalIgnoreCase))
+ {
+ var value = Uri.UnescapeDataString(parts[1].Replace('+', ' ')).Trim();
+ return value.Length == 0 ? null : value;
+ }
+ }
+
+ return null;
+ }
+
+ /// 协议是否已注册
+ public static bool IsRegistered()
+ {
+ using var key = Registry.CurrentUser.OpenSubKey($@"Software\Classes\{Scheme}\shell\open\command");
+ return key?.GetValue(null) is string value && value.Length > 0;
+ }
+
+ /// 当前注册的命令行(界面上展示,方便排查指向了哪个 exe)
+ public static string? RegisteredCommand()
+ {
+ using var key = Registry.CurrentUser.OpenSubKey($@"Software\Classes\{Scheme}\shell\open\command");
+ return key?.GetValue(null) as string;
+ }
+
+ /// 注册协议(指向当前 exe;HKCU,免管理员)
+ public static void Register()
+ {
+ var exePath = Environment.ProcessPath
+ ?? throw new InvalidOperationException("拿不到当前程序的路径,无法注册启动协议");
+
+ using (var scheme = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{Scheme}"))
+ {
+ scheme.SetValue(null, $"URL:{DisplayName}");
+ scheme.SetValue("URL Protocol", string.Empty);
+ }
+
+ using (var command = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{Scheme}\shell\open\command"))
+ {
+ command.SetValue(null, $"\"{exePath}\" \"%1\"");
+ }
+ }
+
+ /// 取消注册(卸载时调用)
+ public static void Unregister()
+ {
+ Registry.CurrentUser.DeleteSubKeyTree($@"Software\Classes\{Scheme}", throwOnMissingSubKey: false);
+ }
+}
diff --git a/desktop/Services/SingleInstance.cs b/desktop/Services/SingleInstance.cs
new file mode 100644
index 0000000..5aa8547
--- /dev/null
+++ b/desktop/Services/SingleInstance.cs
@@ -0,0 +1,117 @@
+using System.IO;
+using System.IO.Pipes;
+using System.Text;
+
+namespace YuncangTrace.LocalService.Services;
+
+///
+/// 单实例 + 参数转发(命名管道)
+///
+/// 场景:窗口已经开着,用户又点了一次 WMS 页面上的「查看打包视频」→ 系统按协议再启动一次本程序。
+/// 这时第二个实例**不应该**去抢 17311 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例,
+/// 由它把窗口激活并查询那个运单号。
+///
+public sealed class SingleInstance : IDisposable
+{
+ private readonly Mutex _mutex;
+ private readonly string _pipeName;
+ private readonly Action _onArgs;
+ private readonly CancellationTokenSource _cts = new();
+ private readonly bool _ownsMutex;
+
+ /// 本次是否是第一个实例(不是的话调用 后就可以退出了)
+ public bool IsFirstInstance { get; }
+
+ public SingleInstance(string name, Action onArgs)
+ {
+ _onArgs = onArgs;
+ _pipeName = $"{name}.pipe";
+
+ // 全局命名互斥体:跨会话也能认出来(同一个用户下就够了,用 Local\ 前缀)
+ _mutex = new Mutex(initiallyOwned: true, $@"Local\{name}.mutex", out var createdNew);
+ _ownsMutex = createdNew;
+ IsFirstInstance = createdNew;
+ }
+
+ /// 第一个实例调用:开一个后台线程等第二个实例送参数过来
+ public void StartListening()
+ {
+ var thread = new Thread(ListenLoop)
+ {
+ IsBackground = true,
+ Name = "single-instance-pipe",
+ };
+ thread.Start();
+ }
+
+ /// 第二个实例调用:把命令行参数送给已运行的实例(连不上就算了,不影响退出)
+ public void SendArgs(string[] args)
+ {
+ if (args.Length == 0) return;
+
+ try
+ {
+ using var client = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out);
+ client.Connect(1500);
+
+ using var writer = new StreamWriter(client, new UTF8Encoding(false)) { AutoFlush = true };
+ foreach (var arg in args) writer.WriteLine(arg);
+ }
+ catch (Exception)
+ {
+ // 拿不到第一个实例(可能正在退出):静默忽略,用户重新点一次即可
+ }
+ }
+
+ private void ListenLoop()
+ {
+ while (!_cts.IsCancellationRequested)
+ {
+ try
+ {
+ using var server = new NamedPipeServerStream(
+ _pipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances,
+ PipeTransmissionMode.Byte, PipeOptions.None);
+
+ server.WaitForConnection();
+
+ var args = new List();
+ using (var reader = new StreamReader(server, new UTF8Encoding(false)))
+ {
+ string? line;
+ while ((line = reader.ReadLine()) is not null)
+ {
+ if (line.Length > 0) args.Add(line);
+ }
+ }
+
+ if (args.Count > 0) _onArgs(args.ToArray());
+ }
+ catch (Exception)
+ {
+ if (_cts.IsCancellationRequested) return;
+ Thread.Sleep(200);
+ }
+ }
+ }
+
+ public void Dispose()
+ {
+ _cts.Cancel();
+
+ if (_ownsMutex)
+ {
+ try
+ {
+ _mutex.ReleaseMutex();
+ }
+ catch (ApplicationException)
+ {
+ // 不持有互斥体(理论上不会发生)
+ }
+ }
+
+ _mutex.Dispose();
+ _cts.Dispose();
+ }
+}
diff --git a/desktop/YuncangTrace.LocalService.csproj b/desktop/YuncangTrace.LocalService.csproj
new file mode 100644
index 0000000..138e96c
--- /dev/null
+++ b/desktop/YuncangTrace.LocalService.csproj
@@ -0,0 +1,24 @@
+
+
+
+ WinExe
+
+ net8.0-windows
+ true
+ enable
+ enable
+ latest
+
+
+ YuncangTrace.LocalService
+ YuncangTrace.LocalService
+ app.manifest
+
+ 1.0.0
+ 云仓视频溯源软件
+ 云仓
+ 云仓视频溯源软件(本机服务)
+ zh-CN
+
+
+
diff --git a/desktop/app.manifest b/desktop/app.manifest
new file mode 100644
index 0000000..a9a3579
--- /dev/null
+++ b/desktop/app.manifest
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+ PerMonitorV2
+ true
+ true
+
+
+
+
+
+
+
+
+
+