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

HaloPixelToolBox

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

公开
关注 0 Fork 0 Star 0
UTF-8
using CommunityToolkit.Mvvm.ComponentModel;
using HaloPixelToolBox.Client.Profiles.CrossVersionProfiles;
using HaloPixelToolBox.Core.Models.Notifications;
using HaloPixelToolBox.Core.Utilities;
using Microsoft.UI.Dispatching;
using System.Threading.Channels;
using Windows.UI.Notifications.Management;

namespace HaloPixelToolBox.Client.Utilities;

public sealed partial class MessageNotificationService : ObservableObject, IDisposable
{
    private readonly DispatcherQueue dispatcher;
    private readonly CancellationTokenSource cancellation = new();
    private readonly Channel<PendingMessage> queue = Channel.CreateBounded<PendingMessage>(3);
    private readonly Dictionary<MessageNotificationSource, PendingMessage> pending = [];
    private readonly MessageNotificationFilter filter = new();
    private readonly DesktopMessageReader reader = new();
    private readonly WindowsMessageNotificationReader windowsReader = new();
    private readonly WindowsNotificationTracker windowsNotifications = new();
    private readonly UnreadMessageTracker previews = new();
    private readonly Dictionary<MessageNotificationSource, bool> previewAvailability = [];
    private readonly HaloPixelDevice device = new();
    private readonly object sync = new();
    private DesktopMessageListener? listener;
    private bool disposed;
    private string? lastWindowsStatus;

    private sealed class PendingMessage(MessageNotificationSource source, bool test, int generation)
    {
        public MessageNotificationSource Source { get; } = source;
        public bool Test { get; } = test;
        public int Generation { get; } = generation;
        public List<DesktopMessageSignal> Signals { get; } = [];
        public MessageNotification? Details;
        public Task<MessageNotification>? Reading;
    }

    [ObservableProperty]
    public partial string StatusText { get; set; } = "消息提示已关闭";
    [ObservableProperty]
    public partial string WindowsNotificationStatusText { get; set; } = "Windows 系统通知读取已关闭";

    public MessageNotificationService(DispatcherQueue dispatcher)
    {
        this.dispatcher = dispatcher;
        _ = Task.Run(ProcessQueueAsync);
        _ = Task.Run(WatchPreviewsAsync);
        _ = Task.Run(WatchWindowsNotificationsAsync);
    }

    // 在 UI 线程调用,以便 NativeWindow 和 WinEvent 使用主窗口的消息循环。
    public void RefreshSettings()
    {
        lock (sync)
        {
            if (disposed)
                return;
            filter.Options = new(SystemProfile.EnableWeChatNotifications,
                SystemProfile.EnableQQNotifications, SystemProfile.EnableWeComNotifications);
            foreach (var source in pending.Keys.ToArray())
                if (!filter.IsCurrent(source, pending[source].Generation))
                    pending.Remove(source);
            foreach (var source in Enum.GetValues<MessageNotificationSource>())
                if (!filter.Options.IsEnabled(source))
                {
                    previews.Reset(source);
                    windowsNotifications.Reset(source);
                    previewAvailability.Remove(source);
                }
            if (!filter.Options.AnyEnabled)
            {
                while (queue.Reader.TryRead(out _)) { }
                pending.Clear();
            }
        }
        if (!filter.Options.AnyEnabled)
        {
            listener?.Dispose();
            listener = null;
            SetStatus("消息提示已关闭");
            SetWindowsStatus("Windows 系统通知读取已关闭");
            return;
        }
        try
        {
            if (listener is null)
            {
                listener = new DesktopMessageListener();
                listener.MessageReceived += OnMessageReceived;
            }
            SetStatus("正在监听系统通知、新消息弹窗和任务栏提醒");
        }
        catch (Exception ex)
        {
            SetStatus($"消息监听启动失败:{ex.Message}");
            Console.WriteLine($"[ERROR]消息监听启动失败:{ex.Message}");
        }
    }

    public void RequestTest(MessageNotificationSource source) => Enqueue(source, test: true,
        details: new(source, "测试发送者", "这是一条消息内容测试"));

    private void OnMessageReceived(DesktopMessageSignal signal)
    {
        // QQ 使用 Windows 通知 ID 与文本,避免任务栏事件抢先发出不带详情的提示。
        if (signal.Source != MessageNotificationSource.QQ)
            Enqueue(signal.Source, test: false, signal: signal);
    }

    private void Enqueue(MessageNotificationSource source, bool test, DesktopMessageSignal? signal = null,
        MessageNotification? details = null, bool authoritative = false)
    {
        lock (sync)
        {
            if (disposed || !filter.Options.IsEnabled(source))
                return;
            if (pending.TryGetValue(source, out var existing))
            {
                if (signal is { } next && !existing.Signals.Contains(next))
                    existing.Signals.Add(next);
                if (details is { HasDetails: true } && !existing.Test)
                    existing.Details = details;
                return;
            }
            if (!test && !filter.TryAccept(source, DateTimeOffset.UtcNow) && !authoritative)
                return;
            var item = new PendingMessage(source, test, filter.GetGeneration(source)) { Details = details };
            if (signal is { } first)
                item.Signals.Add(first);
            if (details is null)
                item.Reading = Task.Run(() => CaptureDetailsAsync(item));
            if (queue.Writer.TryWrite(item))
            {
                pending[source] = item;
                SetStatus($"{MessageNotificationClassifier.GetDisplayName(source)}提示等待发送");
            }
        }
    }

    private async Task<MessageNotification> CaptureDetailsAsync(PendingMessage item)
    {
        // 任务栏闪烁经常先于弹窗显示,给通知卡片留下填充发送者和正文的时间。
        await Task.Delay(600, cancellation.Token);
        DesktopMessageSignal[] signals;
        lock (sync)
        {
            if (!filter.IsCurrent(item.Source, item.Generation))
                return new(item.Source);
            signals = item.Signals.ToArray();
        }
        return await reader.ReadAsync(item.Source, signals, cancellation.Token);
    }

    private async Task WatchPreviewsAsync()
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
        try
        {
            while (await timer.WaitForNextTickAsync(cancellation.Token))
                foreach (var source in Enum.GetValues<MessageNotificationSource>())
                {
                    if (source != MessageNotificationSource.WeChat)
                        continue;
                    int generation;
                    lock (sync)
                    {
                        if (!filter.Options.IsEnabled(source))
                            continue;
                        generation = filter.GetGeneration(source);
                    }
                    var snapshot = await reader.ReadPreviewsAsync(source, cancellation.Token);
                    lock (sync)
                    {
                        if (!filter.IsCurrent(source, generation))
                            continue;
                        var available = snapshot is not null;
                        if (!previewAvailability.TryGetValue(source, out var oldAvailability) || oldAvailability != available)
                        {
                            previewAvailability[source] = available;
                            var name = MessageNotificationClassifier.GetDisplayName(source);
                            Console.WriteLine($"[INFO]{name}{(available ? "会话预览可读取" : "当前未提供可读取的会话预览;详情需要通知弹窗")}");
                        }
                        if (snapshot is null)
                            continue;
                        foreach (var message in previews.Update(source, snapshot))
                            Enqueue(source, test: false, details: message, authoritative: true);
                    }
                }
        }
        catch (OperationCanceledException) { }
    }

    private async Task WatchWindowsNotificationsAsync()
    {
        // 未打包的桌面版本不一定支持 NotificationChanged 事件;读取通知 ID 差量也适用于该版本。
        using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(500));
        try
        {
            while (await timer.WaitForNextTickAsync(cancellation.Token))
            {
                MessageNotificationOptions options;
                Dictionary<MessageNotificationSource, int> generations;
                lock (sync)
                {
                    options = filter.Options;
                    if (!options.AnyEnabled)
                        continue;
                    generations = Enum.GetValues<MessageNotificationSource>().Where(options.IsEnabled)
                        .ToDictionary(source => source, filter.GetGeneration);
                }
                try
                {
                    var snapshot = await windowsReader.ReadAsync(options, cancellation.Token);
                    lock (sync)
                    {
                        if (!filter.Options.AnyEnabled)
                            continue;
                        if (snapshot is null)
                        {
                            SetWindowsStatus("Windows 系统通知读取超时,正在重试");
                            continue;
                        }
                        if (snapshot.Access != UserNotificationListenerAccessStatus.Allowed)
                        {
                            foreach (var source in Enum.GetValues<MessageNotificationSource>())
                                windowsNotifications.Reset(source);
                            SetWindowsStatus(snapshot.Access == UserNotificationListenerAccessStatus.Denied
                                ? "Windows 未允许读取系统通知,QQ 消息提示暂不可用"
                                : "请点击“允许读取系统通知”以启用 QQ 消息提示");
                            continue;
                        }
                        SetWindowsStatus("Windows 系统通知可读取;QQ 直接读取发送者和正文");
                        foreach (var (source, generation) in generations)
                            if (filter.IsCurrent(source, generation))
                                foreach (var message in windowsNotifications.Update(source, snapshot.Messages))
                                    Enqueue(source, test: false, details: message, authoritative: true);
                    }
                }
                catch (Exception ex) when (ex is not OperationCanceledException)
                {
                    SetWindowsStatus($"Windows 系统通知暂不可读取:{ex.GetType().Name}({ex.HResult:X8})");
                }
            }
        }
        catch (OperationCanceledException) { }
    }

    public async Task RequestWindowsNotificationAccessAsync()
    {
        try
        {
            var access = await WindowsMessageNotificationReader.RequestAccessAsync();
            SetWindowsStatus(access == UserNotificationListenerAccessStatus.Allowed
                ? "Windows 已允许读取系统通知"
                : "Windows 未允许读取系统通知,QQ 消息提示暂不可用");
        }
        catch (Exception ex)
        {
            SetWindowsStatus($"系统通知授权失败:{ex.GetType().Name}({ex.HResult:X8})");
        }
    }

    private async Task ProcessQueueAsync()
    {
        try
        {
            await foreach (var message in queue.Reader.ReadAllAsync(cancellation.Token))
            {
                var captured = message.Reading is null ? null : await message.Reading;
                MessageNotification notification;
                lock (sync)
                {
                    if (pending.TryGetValue(message.Source, out var item) && ReferenceEquals(item, message))
                        pending.Remove(message.Source);
                    if (!filter.IsCurrent(message.Source, message.Generation))
                        continue;
                    notification = message.Details ?? captured ?? new(message.Source);
                }
                var name = MessageNotificationClassifier.GetDisplayName(message.Source);
                try
                {
                    if (!device.Initialize())
                    {
                        SetStatus("未连接花再 Halo PixelBar;本次消息提示已跳过");
                        continue;
                    }
                    var capacity = device.ShowMessageNotification(notification.DisplayText);
                    var detailStatus = notification.Sender.Length > 0 && notification.Content.Length > 0
                        ? "含发送者和内容" : notification.HasDetails ? "含部分消息详情" : "未读取到详情,请开启客户端消息预览";
                    SetStatus($"已发送{name}{(message.Test ? "测试" : "消息")}提示({detailStatus})");
                    Console.WriteLine($"[INFO]{name}{(message.Test ? "测试" : "新消息")}原生提示已发送({detailStatus},字符上限 {capacity.MaxTextLength},分包上限 {capacity.MaxPacketTextBytes})");
                }
                catch (Exception ex)
                {
                    SetStatus($"{name}提示发送失败:{ex.Message}");
                    Console.WriteLine($"[ERROR]{name}提示发送失败:{ex.Message}");
                    continue;
                }
                await Task.Delay(HaloPixelDevice.MessageDisplayDuration, cancellation.Token);
            }
        }
        catch (OperationCanceledException) { }
    }

    private void SetStatus(string text)
    {
        if (dispatcher.HasThreadAccess)
            StatusText = text;
        else
            dispatcher.TryEnqueue(() => StatusText = text);
    }

    private void SetWindowsStatus(string text)
    {
        lock (sync)
        {
            if (lastWindowsStatus == text)
                return;
            lastWindowsStatus = text;
        }
        Console.WriteLine($"[INFO]{text}");
        if (dispatcher.HasThreadAccess)
            WindowsNotificationStatusText = text;
        else
            dispatcher.TryEnqueue(() => WindowsNotificationStatusText = text);
    }

    public void Dispose()
    {
        lock (sync)
        {
            if (disposed)
                return;
            disposed = true;
            filter.Options = new();
        }
        listener?.Dispose();
        listener = null;
        cancellation.Cancel();
        queue.Writer.TryComplete();
    }
}