-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsNotificationListenerService.cs
More file actions
467 lines (424 loc) · 20.4 KB
/
WindowsNotificationListenerService.cs
File metadata and controls
467 lines (424 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using Windows.UI.Notifications;
using Windows.UI.Notifications.Management;
namespace NaturalCommands
{
internal sealed class WindowsNotificationListenerService
{
private Thread? _pollThread;
private readonly Dictionary<string, TickerCategory> _appCategoryMap;
private readonly HashSet<string> _ignoreApps;
public WindowsNotificationListenerService()
{
_appCategoryMap = LoadCategoryRules();
_ignoreApps = LoadIgnoreRules();
}
/// <summary>
/// Test-only constructor: injects pre-built rule maps so that WinRT is never touched.
/// </summary>
internal WindowsNotificationListenerService(
Dictionary<string, TickerCategory> appCategoryMap,
HashSet<string> ignoreApps)
{
_appCategoryMap = appCategoryMap;
_ignoreApps = ignoreApps;
}
private static Dictionary<string, TickerCategory> LoadCategoryRules()
{
var filePath = Path.Combine(AppContext.BaseDirectory, "notification-category-rules.json");
if (!File.Exists(filePath))
{
return new Dictionary<string, TickerCategory>(StringComparer.OrdinalIgnoreCase)
{
["default"] = TickerCategory.Info
};
}
try
{
var json = File.ReadAllText(filePath);
return ParseCategoryRulesJson(json);
}
catch
{
return new Dictionary<string, TickerCategory>(StringComparer.OrdinalIgnoreCase)
{
["default"] = TickerCategory.Info
};
}
}
/// <summary>
/// Parses a JSON string (array of {app, category} or {default} objects) into a category map.
/// Exposed as <c>internal</c> so unit tests can exercise the parsing logic directly.
/// </summary>
internal static Dictionary<string, TickerCategory> ParseCategoryRulesJson(string json)
{
var raw = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(json);
if (raw == null)
{
return new Dictionary<string, TickerCategory>(StringComparer.OrdinalIgnoreCase)
{
["default"] = TickerCategory.Info
};
}
var map = new Dictionary<string, TickerCategory>(StringComparer.OrdinalIgnoreCase);
foreach (var item in raw)
{
if (item.TryGetValue("app", out var app) && item.TryGetValue("category", out var categoryText))
{
if (Enum.TryParse<TickerCategory>(categoryText, true, out var category))
{
map[app] = category;
}
}
else if (item.TryGetValue("default", out var defaultCategory) && Enum.TryParse<TickerCategory>(defaultCategory, true, out var defaultCat))
{
map["default"] = defaultCat;
}
}
if (!map.ContainsKey("default"))
{
map["default"] = TickerCategory.Info;
}
return map;
}
private static HashSet<string> LoadIgnoreRules()
{
var filePath = Path.Combine(AppContext.BaseDirectory, "notification-ignore-rules.json");
if (!File.Exists(filePath))
{
return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
try
{
var json = File.ReadAllText(filePath);
return ParseIgnoreRulesJson(json);
}
catch
{
return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// Parses a JSON string (array of {app} objects) into a set of ignored app names.
/// Exposed as <c>internal</c> so unit tests can exercise the parsing logic directly.
/// </summary>
internal static HashSet<string> ParseIgnoreRulesJson(string json)
{
var raw = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(json);
if (raw == null) return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return raw
.Where(i => i.TryGetValue("app", out _))
.Select(i => i["app"])
.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
private readonly HashSet<uint> _seen = new();
private CancellationTokenSource? _pollCts;
public event Action<System.Collections.Generic.List<string>>? NotificationsReceived;
public event Action? ListenerFailed;
/// <summary>
/// Starts a dedicated STA thread that owns ALL WinRT access:
/// RequestAccess + polling. Returns true if access was granted.
/// Blocks until the access check completes (max 10 s).
/// </summary>
public bool Start()
{
_pollCts = new CancellationTokenSource();
var token = _pollCts.Token;
bool? accessResult = null;
var accessKnown = new ManualResetEventSlim(false);
var thread = new Thread(() =>
{
// --- access check on this STA thread ---
try
{
var status = UserNotificationListener.Current
.RequestAccessAsync().GetAwaiter().GetResult();
accessResult = status == UserNotificationListenerAccessStatus.Allowed;
}
catch (Exception ex)
{
if (ex is System.Runtime.InteropServices.COMException cex)
{
NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] RequestAccess failed: {cex.Message} (HR: 0x{cex.HResult:X8}). This may indicate the notification manager or COM server is unavailable.");
}
else
{
NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] RequestAccess failed: {ex.Message}");
}
accessResult = false;
}
finally
{
accessKnown.Set();
}
if (accessResult != true) return;
// --- poll loop on the same STA thread ---
var listener = UserNotificationListener.Current;
NaturalCommands.Helpers.Logger.LogInfo("[NotificationListener] Poll loop started.");
Console.WriteLine("[listen-notifications] Poll loop started.");
while (!token.IsCancellationRequested)
{
// Guard against the unlikely case where the WinRT listener proxy is null
if (listener == null)
{
try { NaturalCommands.Helpers.Logger.LogWarning("[NotificationListener] Listener proxy is null before polling; retrying shortly."); } catch { }
Thread.Sleep(1000);
continue;
}
try
{
var notifications = listener
.GetNotificationsAsync(NotificationKinds.Toast)
.GetAwaiter().GetResult();
// Collect all new notifications from this poll cycle into one batch
var newLines = new System.Collections.Generic.List<string>();
foreach (var notification in notifications)
{
if (!_seen.Add(notification.Id)) continue;
try
{
// AppInfo may be null for unpackaged/Win32 apps — guard and log for diagnostics
string appName;
try
{
if (notification.AppInfo != null)
{
appName = notification.AppInfo.DisplayInfo?.DisplayName ?? "Unknown";
}
else
{
appName = "Unknown";
NaturalCommands.Helpers.Logger.LogInfo($"[NotificationListener] AppInfo is null for id={notification.Id}");
}
}
catch (InvalidCastException icex)
{
appName = "Unknown";
NaturalCommands.Helpers.Logger.LogWarning($"[NotificationListener] AppInfo cast failed for id={notification.Id}: {icex.Message}");
}
catch (Exception ex)
{
appName = "Unknown";
NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] Failed to read AppInfo for id={notification.Id}: {ex.Message}");
}
if (_ignoreApps.Contains(appName)) continue;
var binding = notification.Notification?.Visual?.GetBinding(KnownNotificationBindings.ToastGeneric);
var title = binding?.GetTextElements()?.FirstOrDefault()?.Text ?? appName;
var body = binding?.GetTextElements()?.Skip(1).FirstOrDefault()?.Text ?? string.Empty;
var message = string.IsNullOrWhiteSpace(body) ? title : $"{title} — {body}";
NaturalCommands.Helpers.Logger.LogInfo($"[NotificationListener] id={notification.Id} app={appName} title={title} body={body} message={message}");
Console.WriteLine($"[listen-notifications] {appName}: {message}");
var category = MapAppToCategory(appName);
newLines.Add($"{category.ToString().ToLowerInvariant()}:{message}");
listener.RemoveNotification(notification.Id);
}
catch (Exception ex)
{
NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] Process id={notification.Id}: {ex}");
}
}
// Show or forward all notifications from this cycle
if (newLines.Count > 0)
{
try
{
if (NotificationsReceived != null)
{
NaturalCommands.Helpers.Logger.LogInfo($"[NotificationListener] Forwarding {newLines.Count} lines; HasForwarder=True");
NotificationsReceived.Invoke(newLines);
}
else
{
NaturalCommands.Helpers.Logger.LogInfo("[NotificationListener] No forwarder subscribed; showing local ticker.");
ShowTicker(newLines);
}
}
catch (Exception ex)
{
NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] Error forwarding notifications: {ex}");
// Fallback to local display
try { ShowTicker(newLines); } catch { }
}
}
}
catch (ObjectDisposedException ex)
{
NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] Listener disposed: {ex.ToString()} | threadId={Thread.CurrentThread.ManagedThreadId} | tokenCancelled={token.IsCancellationRequested} | seen={_seen.Count} | listenerNull={(listener==null)}");
Console.WriteLine("[listen-notifications] Listener disposed — attempting reinitialization.");
bool reinitSuccess = false;
int attempt = 0;
// Keep retrying in the background with exponential backoff; notify owner periodically
while (!token.IsCancellationRequested && !reinitSuccess)
{
attempt++;
try
{
// Probe the listener on a fresh STA helper thread
string? probeError = null;
bool probeOk = TryProbeListenerOnSta(timeoutMs: 5000, out probeError);
if (!probeOk)
{
NaturalCommands.Helpers.Logger.LogWarning($"[NotificationListener] Reinit attempt {attempt} probe failed: {probeError ?? "unknown"}");
}
else
{
// Recreate listener proxy on this STA polling thread
listener = UserNotificationListener.Current;
var check = listener.GetNotificationsAsync(NotificationKinds.Toast).GetAwaiter().GetResult();
reinitSuccess = true;
NaturalCommands.Helpers.Logger.LogInfo($"[NotificationListener] Reinitialized listener after {attempt} attempt(s).");
break;
}
}
catch (Exception rex)
{
NaturalCommands.Helpers.Logger.LogWarning($"[NotificationListener] Reinit attempt {attempt} failed: {rex.ToString()}");
}
if (attempt % 6 == 0)
{
// Periodically notify the owner that listener is struggling but still retrying
try { ListenerFailed?.Invoke(); } catch { }
}
if (token.IsCancellationRequested) break;
// Exponential backoff between 1s and 60s
int delayMs = Math.Min(1000 * (1 << Math.Min(attempt - 1, 6)), 60000);
Thread.Sleep(delayMs);
}
if (!reinitSuccess)
{
NaturalCommands.Helpers.Logger.LogError("[NotificationListener] Reinit attempts exhausted or cancelled — exiting poll loop.");
Console.WriteLine("[listen-notifications] Listener reinit failed, exiting.");
try { ListenerFailed?.Invoke(); } catch { }
break;
}
else
{
// successfully reinitialized; continue polling
continue;
}
}
catch (Exception ex)
{
NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] Poll error: {ex}");
}
Thread.Sleep(1000);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
_pollThread = thread;
thread.Start();
accessKnown.Wait(TimeSpan.FromSeconds(10));
return accessResult == true;
}
public void Stop()
{
try
{
_pollCts?.Cancel();
}
catch { }
try
{
// Wait briefly for the poll thread to exit to avoid transient COM errors in logs
if (_pollThread != null && _pollThread.IsAlive)
{
if (!_pollThread.Join(5000))
{
try { NaturalCommands.Helpers.Logger.LogWarning("[NotificationListener] Poll thread did not exit within timeout after cancel."); } catch { }
}
}
}
catch (Exception ex)
{
try { NaturalCommands.Helpers.Logger.LogWarning($"[NotificationListener] Stop join error: {ex.Message}"); } catch { }
}
finally
{
_pollThread = null;
}
}
private bool TryProbeListenerOnSta(int timeoutMs, out string? probeError)
{
probeError = null;
bool success = false;
var done = new System.Threading.ManualResetEventSlim(false);
string? localError = null;
var thread = new Thread(() =>
{
try
{
try
{
var status = UserNotificationListener.Current.RequestAccessAsync().GetAwaiter().GetResult();
if (status != UserNotificationListenerAccessStatus.Allowed)
{
localError = $"RequestAccess returned {status}";
}
else
{
var probe = UserNotificationListener.Current.GetNotificationsAsync(NotificationKinds.Toast).GetAwaiter().GetResult();
success = true;
}
}
catch (Exception ex)
{
if (ex is System.Runtime.InteropServices.COMException cex)
{
localError = $"{cex.Message} (HR: 0x{cex.HResult:X8})";
}
else
{
localError = ex.ToString();
}
}
}
finally
{
done.Set();
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
if (!done.Wait(TimeSpan.FromMilliseconds(timeoutMs)))
{
probeError = "probe timeout";
return false;
}
probeError = localError;
return success;
}
private void ShowTicker(System.Collections.Generic.List<string> lines)
{
try
{
// Delegate to centralized manager which ensures a single persistent form
TickerOverlayManager.EnsurePersistentTicker(lines, cycleSeconds: 5, maxCycles: 0, topPosition: false, hideOnDismiss: false);
}
catch (Exception ex)
{
try { NaturalCommands.Helpers.Logger.LogError($"[NotificationListener] ShowTicker failed: {ex.Message}"); } catch { }
}
}
internal TickerCategory MapAppToCategory(string? appName)
{
if (string.IsNullOrWhiteSpace(appName))
return TickerCategory.Info;
if (_appCategoryMap.TryGetValue(appName, out var cat))
return cat;
// look for app name contains rule
var match = _appCategoryMap.FirstOrDefault(kvp => kvp.Key != "default" && appName.IndexOf(kvp.Key, StringComparison.OrdinalIgnoreCase) >= 0);
if (!match.Equals(default(KeyValuePair<string, TickerCategory>)))
{
return match.Value;
}
return _appCategoryMap.TryGetValue("default", out var defaultCat) ? defaultCat : TickerCategory.Info;
}
}
}