using HaloPixelToolBox.Core.Models.Notifications;
using System.Text.RegularExpressions;
namespace HaloPixelToolBox.Core.Utilities;
/// 解析通知卡片的文本;输入仅包含通知窗口,不包含聊天记录。
public static partial class MessageNotificationTextParser
{
private static readonly HashSet chrome = new(StringComparer.OrdinalIgnoreCase)
{
"微信", "WeChat", "Weixin", "QQ", "QQ NT", "企业微信", "WeCom", "WXWork",
"关闭", "关闭通知", "打开", "查看", "查看消息", "忽略", "更多", "回复", "标记为已读",
"通知", "新消息通知", "Close", "Open", "Reply", "Dismiss", "Mark as read"
};
public static MessageNotification Parse(MessageNotificationSource source, IEnumerable texts)
{
var lines = texts.SelectMany(text => text.Replace('\r', '\n').Split('\n'))
.Select(text => Spaces().Replace(text, " ").Trim())
.Where(text => text.Length > 0 && !chrome.Contains(text) && !Metadata().IsMatch(text))
.ToList();
// 同一控件有时同时通过 Name 和 Value 暴露相同文字。
for (var i = lines.Count - 1; i > 0; i--)
if (lines[i] == lines[i - 1])
lines.RemoveAt(i);
if (lines.Count == 0)
return new(source);
if (lines.Count == 1)
{
var match = SenderAndContent().Match(lines[0]);
if (match.Success && !lines[0].Contains("://", StringComparison.Ordinal))
return new(source, match.Groups[1].Value.Trim(), Details(match.Groups[2].Value));
return new(source, Content: Details(lines[0]));
}
return new(source, lines[0], Details(string.Join(" ", lines.Skip(1))));
}
private static string Details(string text) => GenericMessage().IsMatch(text) ? "" : text;
[GeneratedRegex(@"[\t\p{Zs}]+")]
private static partial Regex Spaces();
[GeneratedRegex(@"^(?:\d{1,2}:\d{2}(?::\d{2})?|\d{1,2}月\d{1,2}日|刚刚|现在|\d+\s*(?:秒|分钟)前|\[?\d+\+?\]?|[×✕]|\d+\s*条(?:新|未读)?消息)$")]
private static partial Regex Metadata();
[GeneratedRegex(@"^(.{1,60}?)[::]\s*(.+)$")]
private static partial Regex SenderAndContent();
[GeneratedRegex(@"^(?:(?:你|您)?(?:收到|有)(?:了)?(?:一|\d+)?(?:条|个)?新消息|新消息|New message)$", RegexOptions.IgnoreCase)]
private static partial Regex GenericMessage();
}