using System;
using System.Collections.Generic;
using System.Linq;
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);
}
}