using HaloPixelToolBox.Core.Models.Notifications; namespace HaloPixelToolBox.Core.Utilities; /// 以应用身份及通知 ID 计算新增 / 更新通知,首次快照不重放历史。 public sealed class WindowsNotificationTracker { private readonly Dictionary> snapshots = []; public IReadOnlyList Update(MessageNotificationSource source, IEnumerable notifications) { var current = notifications.Where(notification => notification.Message.Source == source) .GroupBy(notification => (notification.AppId, notification.Id)) .ToDictionary(group => group.Key, group => group.OrderByDescending(item => item.CreatedAt).First()); var messages = new List(); if (snapshots.TryGetValue(source, out var previous)) { foreach (var notification in current.Values.OrderBy(item => item.CreatedAt)) { var key = (notification.AppId, notification.Id); if (!previous.TryGetValue(key, out var old) || notification != old) messages.Add(notification.Message); previous[key] = notification; } // 短暂空快照或移除通知不会使旧通知再次成为新消息;限制已见 ID 的内存占用。 foreach (var key in previous.OrderByDescending(pair => pair.Value.CreatedAt).Skip(1024).Select(pair => pair.Key).ToArray()) previous.Remove(key); } else snapshots[source] = current.OrderByDescending(pair => pair.Value.CreatedAt).Take(1024) .ToDictionary(pair => pair.Key, pair => pair.Value); return messages; } public void Reset(MessageNotificationSource source) => snapshots.Remove(source); }