using HaloPixelToolBox.Core.Models.Notifications; using HaloPixelToolBox.Core.Utilities; using System.Collections.Concurrent; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Windows.Automation; namespace HaloPixelToolBox.Client.Utilities; /// 只读通知窗口和会话列表预览;不激活窗口、不打开会话、不读取历史数据库。 internal sealed class DesktopMessageReader(Func>? popupTextReader = null) { private readonly ConcurrentDictionary<(MessageNotificationSource Source, bool Popup), SemaphoreSlim> readers = new(); private readonly Func> readPopupText = popupTextReader ?? ReadPopupText; public async Task ReadAsync(MessageNotificationSource source, IReadOnlyList signals, CancellationToken token) { // QQ 的详情由 Windows 标准通知接口提供,不能向 QQ 请求 UIA。 if (source == MessageNotificationSource.QQ) return new(source); var result = await RunAsync(source, popup: true, async () => { var popups = signals.Where(signal => signal.IsPopup).Select(signal => signal.Window).ToList(); foreach (var signal in signals) { GetWindowThreadProcessId(signal.Window, out var pid); popups.AddRange(FindWindows(source, pid, popupOnly: true)); } foreach (var window in popups.Distinct()) { if (!IsWindowVisible(window)) continue; IEnumerable text = []; try { text = readPopupText(window); } catch (ElementNotAvailableException) { } catch (COMException) { } var notification = MessageNotificationTextParser.Parse(source, text); if (notification.Sender.Length > 0 && notification.Content.Length > 0) return notification; if (notification.HasDetails) return notification; } // 无弹窗时,只接受唯一的未读会话,避免猜错多个历史未读消息的发送者。 var unread = (await ReadSessionsAsync(source, token) ?? []).Where(item => item.UnreadCount > 0 && item.Content.Length > 0).ToArray(); return unread.Length == 1 ? new(source, unread[0].Sender, unread[0].Content) : new MessageNotification(source); }, token); return result ?? new(source); } public async Task?> ReadPreviewsAsync(MessageNotificationSource source, CancellationToken token) => await RunAsync>(source, popup: false, () => ReadSessionsAsync(source, token), token); // UIA 放在后台线程;超时的提供程序不会阻塞 UI,也不会不断创建新的挂起调用。 private async Task RunAsync(MessageNotificationSource source, bool popup, Func> read, CancellationToken token) where T : class { var reading = readers.GetOrAdd((source, popup), _ => new(1)); if (!await reading.WaitAsync(100, token)) return null; var task = Task.Run(async () => { try { return await read(); } catch (Exception ex) when (ex is not OperationCanceledException) { Console.WriteLine($"[WARN]消息预览读取失败:{ex.GetType().Name}"); return null; } finally { reading.Release(); } }); try { return await task.WaitAsync(TimeSpan.FromSeconds(popup ? 3 : 4), token); } catch (TimeoutException) { return null; } } private static async Task?> ReadSessionsAsync(MessageNotificationSource source, CancellationToken token) { var previews = new List(); var foundList = false; var windows = FindWindows(source, 0, popupOnly: false).ToArray(); if (source is MessageNotificationSource.QQ or MessageNotificationSource.WeCom) return null; foreach (var window in windows) { var root = AutomationElement.FromHandle(window); if (root is null) continue; // 明确定位会话列表,不能把聊天正文里的 ListItem 当成通知预览。 var lists = root.FindAll(TreeScope.Descendants, new OrCondition( new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.List), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataGrid))); foreach (AutomationElement list in lists) { var info = list.Current; var identity = $"{info.AutomationId} {info.ClassName}"; if (info.Name is not ("会话" or "会话列表" or "最近会话" or "Chats" or "Conversations") && !Regex.IsMatch(identity, @"session[_ .]?(?:list|view)|conversation[_ .]?(?:list|view)|chat[_ .]?list", RegexOptions.IgnoreCase)) continue; foundList = true; var items = list.FindAll(TreeScope.Children, new OrCondition( new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem))); foreach (AutomationElement item in items) { if (MessagePreviewParser.Parse(source, item.Current.Name, item.Current.AutomationId, ReadText(item)) is { } preview) previews.Add(preview); } } } return foundList ? previews : null; } private static IEnumerable ReadPopupText(nint window) { var root = AutomationElement.FromHandle(window); if (root is null) return []; var texts = ReadText(root).ToList(); if (texts.Count == 0) { var caption = new StringBuilder(512); GetWindowText(window, caption, caption.Capacity); texts.Add(caption.ToString()); } return texts; } private static IEnumerable ReadText(AutomationElement root) { var cache = new CacheRequest { TreeScope = TreeScope.Element }; cache.Add(AutomationElement.NameProperty); cache.Add(AutomationElement.BoundingRectangleProperty); using (cache.Activate()) { var elements = root.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text)); return elements.Cast().Take(80) .Select(element => (element.Cached.Name, element.Cached.BoundingRectangle)) .Where(item => !string.IsNullOrWhiteSpace(item.Name)) .OrderBy(item => item.BoundingRectangle.Top).ThenBy(item => item.BoundingRectangle.Left) .Select(item => item.Name).ToArray(); } } private static IEnumerable FindWindows(MessageNotificationSource source, uint targetPid, bool popupOnly) { var windows = new List(); var names = source switch { MessageNotificationSource.WeChat => new[] { "WeChat", "Weixin" }, MessageNotificationSource.QQ => ["QQ"], MessageNotificationSource.WeCom => ["WXWork"], _ => [] }; var targetProcesses = new HashSet(); foreach (var processName in names) foreach (var process in Process.GetProcessesByName(processName)) using (process) if (targetPid == 0 || process.Id == targetPid) targetProcesses.Add((uint)process.Id); EnumWindows((window, _) => { GetWindowThreadProcessId(window, out var pid); if (!targetProcesses.Contains(pid)) return true; if (!GetWindowRect(window, out var bounds)) return true; var name = new StringBuilder(256); GetClassName(window, name, name.Capacity); var popup = MessageNotificationClassifier.IsNotificationPopup(name.ToString(), bounds.Right - bounds.Left, bounds.Bottom - bounds.Top, (GetWindowLong(window, -20) & 8) != 0); var title = new StringBuilder(256); GetWindowText(window, title, title.Capacity); var main = IsMainWindowClass(name.ToString(), title.ToString(), source) || (IsWindowVisible(window) && bounds.Right - bounds.Left >= 700 && bounds.Bottom - bounds.Top >= 400); if (popupOnly ? popup && IsWindowVisible(window) : !popup && main) windows.Add(window); return true; }, 0); return windows; } private static bool IsMainWindowClass(string name, string title, MessageNotificationSource source) => source switch { MessageNotificationSource.WeChat => name is "WeChatMainWndForPC" or "mmui::MainWindow" || Regex.IsMatch(title, @"^(?:微信|Weixin|WeChat)(?:\(\d+\))?$"), MessageNotificationSource.WeCom => name.StartsWith("WeWorkWindow", StringComparison.Ordinal) || name.StartsWith("WXWorkWindow", StringComparison.Ordinal) || title == "企业微信", MessageNotificationSource.QQ => name == "Chrome_WidgetWin_1" || name == "TXGuiFoundation", _ => false }; [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left, Top, Right, Bottom; } private delegate bool EnumWindowCallback(nint window, nint parameter); [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowCallback callback, nint parameter); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(nint window, out uint processId); [DllImport("user32.dll")] private static extern bool IsWindowVisible(nint window); [DllImport("user32.dll")] private static extern bool GetWindowRect(nint window, out Rect bounds); [DllImport("user32.dll", EntryPoint = "GetWindowLongW")] private static extern int GetWindowLong(nint window, int index); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(nint window, StringBuilder name, int maxCount); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetWindowText(nint window, StringBuilder text, int maxCount); }