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 System.Text;

namespace HaloPixelToolBox.Client.Test;

internal class MessageNotificationTests
{
    [SMTest]
    public static void OfficialMessageProtocolVectors()
    {
        var query = HaloPixelMessageProtocol.BuildCapacityQuery();
        XFECode.Assert(query.Length == 64 && query.Take(8).SequenceEqual(
            new byte[] { 0x2e, 0xaa, 0xec, 0xe7, 0, 1, 1, 0x7f }), "官方消息查询报文不一致");

        // VID=2D99 / PID=A106 的实机回复,BB 为设备方向头。
        byte[] response = [0x2f, 0xbb, 0xec, 0xe7, 0, 4, 1, 80, 50, 0, 0x15];
        XFECode.Assert(HaloPixelMessageProtocol.TryParseCapacity(response, out var capacity)
            && capacity == new MessageNotificationCapacity(80, 50), "未正确解析原生消息通道容量");
        var packet = HaloPixelMessageProtocol.BuildNotification("QQ", capacity).Single();
        XFECode.Assert(packet.Length == 64 && packet.Take(11).SequenceEqual(
            new byte[] { 0x2e, 0xaa, 0xec, 0xe8, 0, 4, 1, 2, 0x51, 0x51, 0x27 }), "官方消息写入报文不一致");
        XFECode.Assert(packet[6] == 1 && HidPacketBuilder.BuildText("QQ")[6] != 1,
            "消息提示必须使用独立于普通文本的来源编号");

        response[^1] ^= 1;
        XFECode.Assert(!HaloPixelMessageProtocol.TryParseCapacity(response, out _), "必须拒绝校验损坏的回复");
        response[6] = 0;
        response[^1] = 0x14;
        XFECode.Assert(!HaloPixelMessageProtocol.TryParseCapacity(response, out _), "必须拒绝普通文本通道的回复");
        XFECode.Assert(!HaloPixelMessageProtocol.TryParseCapacity(response.AsSpan(0, 9), out _), "必须拒绝不完整的回复");
    }

    [SMTest]
    public static void MessageUtf8AndFragmentation()
    {
        var text = string.Concat(Enumerable.Repeat("微信😀QQ企业微信", 30));
        foreach (var packetLimit in new byte[] { 0, 13, 54, 255 })
        {
            var packets = HaloPixelMessageProtocol.BuildNotification(text, new(100, packetLimit));
            var textBytes = new List<byte>();
            foreach (var packet in packets)
            {
                var payloadLength = (packet[4] << 8) | packet[5];
                XFECode.Assert(packet.Length == 64 && payloadLength <= 57 && packet[6] == 1,
                    "每个分包必须适配 64 字节 HID 报告,并携带消息来源编号");
                XFECode.Assert(packet[payloadLength + 6] == (byte)packet.Skip(1).Take(payloadLength + 5).Sum(b => b),
                    "分包校验错误");
                textBytes.AddRange(packet.Skip(8).Take(payloadLength - 2));
            }
            var decoded = new UTF8Encoding(false, true).GetString(textBytes.ToArray());
            XFECode.Assert(textBytes.Count <= 255 && textBytes.Count == packets[0][7]
                && packets.All(packet => packet[7] == textBytes.Count), "分包必须携带完整内容的总字节数");
            XFECode.Assert(text.StartsWith(decoded, StringComparison.Ordinal) && decoded.EnumerateRunes().Count() <= 100,
                "不能截断 UTF-8 字符或超过设备的文字容量");
        }
        var controlPacket = HaloPixelMessageProtocol.BuildNotification("微信\n\t提示", new(50, 54)).Single();
        XFECode.Assert(Encoding.UTF8.GetString(controlPacket, 8, controlPacket[7]) == "微信提示", "应过滤控制字符");
    }

    [SMTest]
    public static void NotificationSourcesAndPopupFiltering()
    {
        XFECode.Assert(MessageNotificationClassifier.GetSource("WeChat.exe") == MessageNotificationSource.WeChat
            && MessageNotificationClassifier.GetSource("Weixin") == MessageNotificationSource.WeChat
            && MessageNotificationClassifier.GetSource("QQ.EXE") == MessageNotificationSource.QQ
            && MessageNotificationClassifier.GetSource("WXWork") == MessageNotificationSource.WeCom, "软件识别错误");
        foreach (var unrelated in new[] { "QQMusic", "WeChatAppEx", "WXWorkWeb", "msedge", "mywechat", "explorer" })
            XFECode.Assert(MessageNotificationClassifier.GetSource(unrelated) is null, "不应把辅助进程或其它软件识别为消息来源");
        XFECode.Assert(MessageNotificationClassifier.IsNotificationPopup("WeChatNewMsgWnd", 400, 150, false)
            && MessageNotificationClassifier.IsNotificationPopup("mmui::NotificationWindow", 420, 200, false)
            && MessageNotificationClassifier.IsNotificationPopup("Chrome_WidgetWin_1", 400, 180, true), "应识别消息弹窗");
        XFECode.Assert(!MessageNotificationClassifier.IsNotificationPopup("Chrome_WidgetWin_1", 1200, 900, true)
            && !MessageNotificationClassifier.IsNotificationPopup("Chrome_WidgetWin_1", 400, 180, false)
            && !MessageNotificationClassifier.IsNotificationPopup("WeChatMainWndForPC", 400, 180, true), "主界面不应触发新消息提示");
    }

    [SMTest]
    public static void OptionalSourcesAndDuplicateAlerts()
    {
        var filter = new MessageNotificationFilter();
        var now = DateTimeOffset.UtcNow;
        XFECode.Assert(!filter.Options.AnyEnabled && !filter.TryAccept(MessageNotificationSource.WeChat, now), "消息提示必须默认关闭");
        filter.Options = new(WeChat: true);
        XFECode.Assert(filter.TryAccept(MessageNotificationSource.WeChat, now), "关闭期间的消息不应影响开启后的去重");
        XFECode.Assert(!filter.TryAccept(MessageNotificationSource.WeChat, now.AddSeconds(1))
            && !filter.TryAccept(MessageNotificationSource.QQ, now), "重复或关闭来源的提醒不应发送");
        filter.Options = new(WeChat: true, QQ: true, WeCom: true);
        XFECode.Assert(filter.TryAccept(MessageNotificationSource.QQ, now)
            && filter.TryAccept(MessageNotificationSource.WeCom, now)
            && filter.TryAccept(MessageNotificationSource.WeChat, now.AddSeconds(3)), "不同软件应独立去重,后续新消息应继续提示");
        filter.Options = new();
        XFECode.Assert(!filter.TryAccept(MessageNotificationSource.WeChat, now.AddMinutes(1)), "关闭选项必须立即阻止后续消息");
    }

    [SMTest]
    public static void DisabledSourcesInvalidateQueuedMessages()
    {
        var filter = new MessageNotificationFilter { Options = new(WeChat: true, QQ: true) };
        var weChatGeneration = filter.GetGeneration(MessageNotificationSource.WeChat);
        var qqGeneration = filter.GetGeneration(MessageNotificationSource.QQ);
        XFECode.Assert(filter.TryAccept(MessageNotificationSource.WeChat, DateTimeOffset.UtcNow), "开启后应接受新消息");
        filter.Options = new(QQ: true);
        filter.Options = new(WeChat: true, QQ: true);
        XFECode.Assert(!filter.IsCurrent(MessageNotificationSource.WeChat, weChatGeneration),
            "关闭后重新开启不能重放关闭前排队的旧消息");
        XFECode.Assert(filter.IsCurrent(MessageNotificationSource.QQ, qqGeneration),
            "切换微信选项不应该丢弃 QQ 的待处理消息");
        XFECode.Assert(filter.TryAccept(MessageNotificationSource.WeChat, DateTimeOffset.UtcNow),
            "重新开启后应立即接受真正的新消息");
    }

    [SMTest]
    public static void SenderAndMessageContent()
    {
        foreach (var source in Enum.GetValues<MessageNotificationSource>())
        {
            var message = MessageNotificationTextParser.Parse(source,
                [MessageNotificationClassifier.GetDisplayName(source), "测试发送者", "10:35", "[2]", "你好😀", "下一行", "关闭"]);
            XFECode.Assert(message.Sender == "测试发送者" && message.Content == "你好😀 下一行", "应读取发送者和多行正文,排除时间及通知按钮");
            XFECode.Assert(message.DisplayText == $"{MessageNotificationClassifier.GetDisplayName(source)} 测试发送者:你好😀 下一行",
                "发送到音响的内容应同时包含来源、发送者和正文");
            var combined = MessageNotificationTextParser.Parse(source, ["测试发送者:消息内容"]);
            XFECode.Assert(combined.Sender == "测试发送者" && combined.Content == "消息内容", "应解析单行通知预览");
            var generic = MessageNotificationTextParser.Parse(source, ["有新消息"]);
            XFECode.Assert(!generic.HasDetails && generic.DisplayText.EndsWith(":有新消息"), "客户端隐藏的正文不能伪造为消息详情");
            var url = MessageNotificationTextParser.Parse(source, ["https://example.com"]);
            XFECode.Assert(url.Sender.Length == 0 && url.Content == "https://example.com", "网址不应误识别为发送者");
        }
    }

    [SMTest]
    public static void UnreadPreviewChanges()
    {
        var tracker = new UnreadMessageTracker();
        var source = MessageNotificationSource.WeChat;
        UnreadMessagePreview old = new("会话一", "测试发送者", "旧消息", 2);
        XFECode.Assert(tracker.Update(source, [old]).Count == 0, "开启时已有未读消息只能作为基线");
        XFECode.Assert(tracker.Update(source, [old]).Count == 0, "未变化的预览不能重复提示");
        XFECode.Assert(tracker.Update(source, [old with { Content = "我自己发出的内容" }]).Count == 0,
            "未读数没有增加时,自己发出的消息刷新预览不能误触发新消息提示");
        var updated = tracker.Update(source, [old with { Content = "新内容", UnreadCount = 3 }]);
        XFECode.Assert(updated.Count == 1 && updated[0].Sender == "测试发送者" && updated[0].Content == "新内容",
            "新增未读消息必须带发送者和更新后的正文");
        XFECode.Assert(tracker.Update(source, [old with { Content = "新内容", UnreadCount = 4 }]).Count == 1,
            "连续收到相同正文时应根据未读数量识别新消息");
        XFECode.Assert(tracker.Update(source, [old with { UnreadCount = 0 }]).Count == 0, "已读变化不能触发消息通知");
        tracker.Reset(source);
        XFECode.Assert(tracker.Update(source, [old]).Count == 0, "关闭再开启不能补发历史未读内容");
    }

    [SMTest]
    public static void WindowsNotificationIdentityAndText()
    {
        XFECode.Assert(WindowsMessageNotificationParser.GetSource("Tencent.QQNT", "QQ") == MessageNotificationSource.QQ,
            "应识别 QQ 的系统通知应用身份");
        XFECode.Assert(WindowsMessageNotificationParser.GetSource("unknown.desktop.id", "QQ") == MessageNotificationSource.QQ,
            "桌面应用的其它 AUMID 应通过精确应用名称识别");
        XFECode.Assert(WindowsMessageNotificationParser.GetSource("Tencent.QQMusic", "QQ音乐") is null
            && WindowsMessageNotificationParser.GetSource("Tencent.QQBrowser", "QQ浏览器") is null,
            "不能把 QQ 音乐或 QQ 浏览器的通知当成聊天消息");
        foreach (var source in Enum.GetValues<MessageNotificationSource>())
        {
            var message = WindowsMessageNotificationParser.Parse(source, ["测试发送者", "123", "提醒:下午开会"]);
            XFECode.Assert(message.Sender == "测试发送者" && message.Content == "123 提醒:下午开会",
                "系统通知应原样保留数字正文和冒号,不把正文误解析成发送者");
            var branded = WindowsMessageNotificationParser.Parse(source,
                [MessageNotificationClassifier.GetDisplayName(source), "测试发送者:消息内容"]);
            XFECode.Assert(branded is { Sender: "测试发送者", Content: "消息内容" }, "应读取带软件标题的单行正文");
        }
    }

    [SMTest]
    public static void WindowsNotificationIdsAndUpdates()
    {
        var tracker = new WindowsNotificationTracker();
        var now = DateTimeOffset.UtcNow;
        WindowsMessageNotification old = new("Tencent.QQNT", 1, now, new(MessageNotificationSource.QQ, "测试发送者", "旧消息"));
        XFECode.Assert(tracker.Update(MessageNotificationSource.QQ, [old]).Count == 0, "首次系统通知快照不能重放历史");
        XFECode.Assert(tracker.Update(MessageNotificationSource.QQ, [old]).Count == 0, "相同通知 ID 和正文不能重复发送");
        var fresh = old with { Id = 2, CreatedAt = now.AddSeconds(1), Message = old.Message with { Content = "真实新内容" } };
        var result = tracker.Update(MessageNotificationSource.QQ, [old, fresh]);
        XFECode.Assert(result.Count == 1 && result[0].Content == "真实新内容", "新增系统通知必须携带真实正文");
        var updated = fresh with { Message = fresh.Message with { Content = "更新后的内容" } };
        XFECode.Assert(tracker.Update(MessageNotificationSource.QQ, [old, updated]).Count == 1,
            "应用更新相同通知 ID 时应发送更新后的消息");
        XFECode.Assert(tracker.Update(MessageNotificationSource.QQ, []).Count == 0
            && tracker.Update(MessageNotificationSource.QQ, [old, updated]).Count == 0,
            "移除或短暂空快照不能造成旧通知重放");
        tracker.Reset(MessageNotificationSource.QQ);
        XFECode.Assert(tracker.Update(MessageNotificationSource.QQ, [old, updated]).Count == 0,
            "关闭再开启后,已有系统通知必须作为基线");
    }

    [SMTest]
    public static void WeChatSessionPreviewFormats()
    {
        var source = MessageNotificationSource.WeChat;
        var multiline = MessagePreviewParser.Parse(source, "项目群\n[3条] 张三: 测试内容\n10:40", "MainView.session_item_项目群", []);
        XFECode.Assert(multiline is { Conversation: "项目群", Sender: "项目群 / 张三", Content: "测试内容", UnreadCount: 3 },
            "应解析新版微信的会话名、角标、群发送者和正文");
        var inline = MessagePreviewParser.Parse(source, "测试发送者 1条未读 内容预览 10:40", "", []);
        XFECode.Assert(inline is { Sender: "测试发送者", Content: "内容预览", UnreadCount: 1 }, "应解析单行会话摘要");
        var named = MessagePreviewParser.Parse(source, "Alice Smith [2] Hello world 10:40", "session_item_Alice Smith", []);
        XFECode.Assert(named is { Sender: "Alice Smith", Content: "Hello world", UnreadCount: 2 }, "联系人名称中的空格必须保留");
        XFECode.Assert(MessagePreviewParser.Parse(source, "项目群\n[3条] 消息免打扰\n正文", "session_item_项目群", []) is null,
            "免打扰会话不能通过预览轮询触发消息提示");
    }
}