XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

HaloPixelToolBox

【WinUI3】基于USB HID通讯的花再音响工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using HaloPixelToolBox.Core.Models.Notifications;
using HaloPixelToolBox.Core.Utilities;
using Windows.UI.Notifications;
using Windows.UI.Notifications.Management;

namespace HaloPixelToolBox.Client.Utilities;

internal sealed record WindowsMessageNotificationSnapshot(UserNotificationListenerAccessStatus Access,
    IReadOnlyList<WindowsMessageNotification> Messages);

/// <summary>仅使用 Windows 标准通知的结构化文本;不截图、不访问 QQ UIA。</summary>
internal sealed class WindowsMessageNotificationReader
{
    private UserNotificationListener? listener;
    private Task<WindowsMessageNotificationSnapshot>? reading;

    public async Task<WindowsMessageNotificationSnapshot?> ReadAsync(MessageNotificationOptions options, CancellationToken token)
    {
        if (reading is null || reading.IsCompleted)
            reading = ReadCoreAsync(options, token);
        try { return await reading.WaitAsync(TimeSpan.FromSeconds(3), token); }
        catch (TimeoutException) { return null; }
    }

    private async Task<WindowsMessageNotificationSnapshot> ReadCoreAsync(MessageNotificationOptions options, CancellationToken token)
    {
        listener ??= UserNotificationListener.Current;
        var access = listener.GetAccessStatus();
        if (access != UserNotificationListenerAccessStatus.Allowed)
            return new(access, []);
        var notifications = await listener.GetNotificationsAsync(NotificationKinds.Toast).AsTask(token);
        var messages = new List<WindowsMessageNotification>();
        foreach (var notification in notifications)
        {
            try
            {
                var appId = notification.AppInfo.AppUserModelId;
                var source = WindowsMessageNotificationParser.GetSource(appId, notification.AppInfo.DisplayInfo.DisplayName);
                if (source is null || !options.IsEnabled(source.Value))
                    continue;
                var visual = notification.Notification.Visual;
                var binding = visual.GetBinding(KnownNotificationBindings.ToastGeneric) ?? visual.Bindings.FirstOrDefault();
                var texts = binding?.GetTextElements().Select(element => element.Text) ?? [];
                messages.Add(new(appId, notification.Id, notification.CreationTime,
                    WindowsMessageNotificationParser.Parse(source.Value, texts)));
            }
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                Console.WriteLine($"[WARN]系统消息通知读取失败:{ex.GetType().Name}");
            }
        }
        return new(access, messages);
    }

    // 必须由设置页的按钮在 UI 线程调用;拒绝授权时保留明确的状态提示。
    public static async Task<UserNotificationListenerAccessStatus> RequestAccessAsync() =>
        await UserNotificationListener.Current.RequestAccessAsync();
}