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 Messages); /// 仅使用 Windows 标准通知的结构化文本;不截图、不访问 QQ UIA。 internal sealed class WindowsMessageNotificationReader { private UserNotificationListener? listener; private Task? reading; public async Task 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 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(); 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 RequestAccessAsync() => await UserNotificationListener.Current.RequestAccessAsync(); }