@windowkit/appkit 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,951 @@
1
+ // @windowkit/appkit notifications.mm — user notifications (banners, the
2
+ // Notification Center list, action buttons) through the UserNotifications
3
+ // framework, UNUserNotificationCenter. The cocoa counterpart of freedesktop's
4
+ // org.freedesktop.Notifications; NSUserNotification is the deprecated prior
5
+ // art and is not used.
6
+ //
7
+ // Mechanism only, policy stays in the renderer: what to say, when to ask for
8
+ // authorization, what to do with a refusal.
9
+ //
10
+ // notificationSettings(cb) availability + authorization + per-channel settings
11
+ // requestNotificationAuthorization(opts, cb) the system prompt; cb(granted, error)
12
+ // setNotificationCategories([...]) action sets a notification can name
13
+ // postNotification(props, cb?) -> identifier a banner; reusing an identifier replaces it
14
+ // updateNotification(id, props, cb?) = post with that identifier
15
+ // removeNotification(id | [ids]) delivered and pending
16
+ // deliveredNotifications(cb), notificationCategories(cb) readback
17
+ // events: notification-action { identifier, actionId, categoryId, userInfo }
18
+ // notification-dismissed { identifier, reason, categoryId, userInfo }
19
+ //
20
+ // The bundle-identity constraint. UNUserNotificationCenter attributes every
21
+ // banner to an app the system knows — a bundle with a CFBundleIdentifier
22
+ // that Launch Services can see — and +currentNotificationCenter raises
23
+ // NSInternalInconsistencyException ("bundleProxyForCurrentProcess is nil")
24
+ // in a process that is none, i.e. a bare `node`. So the centre is probed
25
+ // once, at module load, behind the bundle-id check and a @try; the outcome
26
+ // is a capability the renderer reads (settings.available, with the reason),
27
+ // never a silent drop: every native but notificationSettings throws in an
28
+ // unbundled process.
29
+ //
30
+ // The delegate is set at module load too, before initApp()'s finishLaunching,
31
+ // which is what the framework requires for a response that launched the
32
+ // app (a click on a banner while the app was not running) to be delivered
33
+ // at all. Its methods carry no thread guarantee, so a response crosses to
34
+ // node's loop through a thread-safe function and is then emitted through
35
+ // the same backend callback every other event takes; whatever arrives
36
+ // before setBackendEventCallback() is held and replayed, in order, at the
37
+ // start of the first pump2() with a listener.
38
+ //
39
+ // Categories are handed to the system as a whole set, and the system keeps
40
+ // none for an app it has not yet authorized — notificationCategories reads
41
+ // back empty until then — so the last set is kept here and handed over
42
+ // again when a request for authorization is granted.
43
+ //
44
+ // Dismissals. UN reports an explicit dismissal to the delegate only for a
45
+ // notification whose category carries UNNotificationCategoryOptionCustomDismissAction,
46
+ // so every category registered here carries it (opt out per category with
47
+ // customDismissAction: false), and a notification posted with no categoryId
48
+ // is filed under a bridge-owned category that has it. A banner that times
49
+ // out into Notification Center, or is removed by removeNotification, is not
50
+ // reported by the system and produces no event.
51
+ //
52
+ // userInfo is opaque: it is JSON.stringify'd on the way in, carried as one
53
+ // string under a bridge key, and JSON.parse'd on the way back — so whatever
54
+ // JSON can hold round-trips exactly, and nothing else is accepted.
55
+
56
+ #include <napi.h>
57
+ #import <Cocoa/Cocoa.h>
58
+ #import <UserNotifications/UserNotifications.h>
59
+
60
+ #include <string>
61
+ #include <vector>
62
+
63
+ // backend.mm: the one backend event callback
64
+ bool CALHasBackendCb();
65
+ void CALEmitBackendEvent(Napi::Env env, Napi::Object ev);
66
+
67
+ static NSString* const kDefaultCategory = @"appkit.default";
68
+ static NSString* const kUserInfoKey = @"appkit.userInfo";
69
+
70
+ // --- helpers (self-contained, like the other faces) ------------------------
71
+
72
+ static NSString* NToNSString(Napi::Value v) {
73
+ std::string s = v.As<Napi::String>().Utf8Value();
74
+ return [NSString stringWithUTF8String:s.c_str()];
75
+ }
76
+
77
+ static bool NThrowType(Napi::Env env, const std::string& msg) {
78
+ Napi::TypeError::New(env, msg).ThrowAsJavaScriptException();
79
+ return false;
80
+ }
81
+
82
+ // o[k] as a string into *out (nil when absent, null or undefined); a value
83
+ // of any other type is a TypeError.
84
+ static bool NOptString(Napi::Env env, Napi::Object o, const char* k,
85
+ const char* fn, NSString** out) {
86
+ *out = nil;
87
+ if (!o.Has(k)) return true;
88
+ Napi::Value v = o.Get(k);
89
+ if (v.IsUndefined() || v.IsNull()) return true;
90
+ if (!v.IsString()) {
91
+ return NThrowType(env, std::string(fn) + ": '" + k + "' must be a string");
92
+ }
93
+ *out = NToNSString(v);
94
+ return true;
95
+ }
96
+
97
+ static bool NOptBool(Napi::Env env, Napi::Object o, const char* k,
98
+ const char* fn, bool d, bool* out) {
99
+ *out = d;
100
+ if (!o.Has(k)) return true;
101
+ Napi::Value v = o.Get(k);
102
+ if (v.IsUndefined() || v.IsNull()) return true;
103
+ if (!v.IsBoolean()) {
104
+ return NThrowType(env, std::string(fn) + ": '" + k + "' must be a boolean");
105
+ }
106
+ *out = v.As<Napi::Boolean>().Value();
107
+ return true;
108
+ }
109
+
110
+ static Napi::Value JsonStringify(Napi::Env env, Napi::Value v) {
111
+ Napi::Object json = env.Global().Get("JSON").As<Napi::Object>();
112
+ return json.Get("stringify").As<Napi::Function>().Call(json, {v});
113
+ }
114
+
115
+ static Napi::Value JsonParse(Napi::Env env, NSString* s) {
116
+ Napi::Object json = env.Global().Get("JSON").As<Napi::Object>();
117
+ return json.Get("parse").As<Napi::Function>().Call(
118
+ json, {Napi::String::New(env, s.UTF8String)});
119
+ }
120
+
121
+ // The JSON string filed under the bridge key, or nil.
122
+ static NSString* UserInfoJson(NSDictionary* userInfo) {
123
+ id v = userInfo[kUserInfoKey];
124
+ return [v isKindOfClass:NSString.class] ? (NSString*)v : nil;
125
+ }
126
+
127
+ static Napi::Value StringOrNull(Napi::Env env, NSString* s) {
128
+ if (!s.length) return env.Null();
129
+ return Napi::String::New(env, s.UTF8String);
130
+ }
131
+
132
+ // --- the centre, probed once -------------------------------------------------
133
+
134
+ @class CALNotificationDelegate;
135
+
136
+ static bool gProbed = false;
137
+ static UNUserNotificationCenter* gCenter = nil;
138
+ static NSString* gUnavailable = nil; // why, when gCenter is nil
139
+ static CALNotificationDelegate* gDelegate = nil; // the centre's delegate is weak
140
+ // The category set as last handed to the system. The system keeps no
141
+ // categories for an app it has not yet authorized (the readback is empty
142
+ // until then), so a grant re-applies this set; main thread only.
143
+ static NSSet<UNNotificationCategory*>* gCategories = nil;
144
+
145
+ // A response, copied out of the framework's objects so it can travel to the
146
+ // JS thread and wait there for a listener.
147
+ struct NotifEvent {
148
+ std::string type;
149
+ std::string identifier;
150
+ std::string actionId; // notification-action: 'default' for the body click
151
+ std::string reason; // notification-dismissed
152
+ std::string categoryId; // empty: none (the bridge's own category is hidden)
153
+ bool hasUserInfo = false;
154
+ std::string userInfoJson;
155
+ bool hasUserText = false;
156
+ std::string userText;
157
+ };
158
+
159
+ static void CallJsEvent(Napi::Env env, Napi::Function, void*, NotifEvent* ev);
160
+ using EventTsfn = Napi::TypedThreadSafeFunction<void, NotifEvent, CallJsEvent>;
161
+ static EventTsfn gEvents;
162
+ static std::vector<NotifEvent*> gHeld;
163
+
164
+ static Napi::Object EventObject(Napi::Env env, const NotifEvent& ev) {
165
+ Napi::Object o = Napi::Object::New(env);
166
+ o.Set("type", ev.type);
167
+ o.Set("identifier", ev.identifier);
168
+ if (!ev.actionId.empty()) o.Set("actionId", ev.actionId);
169
+ if (!ev.reason.empty()) o.Set("reason", ev.reason);
170
+ o.Set("categoryId", ev.categoryId.empty()
171
+ ? env.Null()
172
+ : Napi::String::New(env, ev.categoryId));
173
+ if (ev.hasUserInfo) {
174
+ Napi::Value v = JsonParse(env, [NSString stringWithUTF8String:ev.userInfoJson.c_str()]);
175
+ if (env.IsExceptionPending()) {
176
+ // not our own output after all; hand it over as it is rather than fail
177
+ (void)env.GetAndClearPendingException();
178
+ v = Napi::String::New(env, ev.userInfoJson);
179
+ }
180
+ o.Set("userInfo", v);
181
+ }
182
+ if (ev.hasUserText) o.Set("userText", ev.userText);
183
+ return o;
184
+ }
185
+
186
+ static void EmitOrHold(Napi::Env env, NotifEvent* ev) {
187
+ if (!CALHasBackendCb()) {
188
+ gHeld.push_back(ev);
189
+ return;
190
+ }
191
+ Napi::HandleScope scope(env);
192
+ CALEmitBackendEvent(env, EventObject(env, *ev));
193
+ delete ev;
194
+ }
195
+
196
+ // Called at the start of pump2 (backend.mm): what arrived before a listener
197
+ // goes out ahead of that tick's input, in arrival order.
198
+ void CALNotificationsReplayHeld(Napi::Env env) {
199
+ if (gHeld.empty() || !CALHasBackendCb()) return;
200
+ std::vector<NotifEvent*> held;
201
+ held.swap(gHeld);
202
+ for (NotifEvent* ev : held) EmitOrHold(env, ev);
203
+ }
204
+
205
+ static void CallJsEvent(Napi::Env env, Napi::Function, void*, NotifEvent* ev) {
206
+ if ((napi_env)env == nullptr) { // the function is being torn down
207
+ delete ev;
208
+ return;
209
+ }
210
+ CALNotificationsReplayHeld(env); // keep order behind anything still held
211
+ EmitOrHold(env, ev);
212
+ }
213
+
214
+ // From any thread: onto node's loop, then to the listener or the held list.
215
+ static void QueueEvent(NotifEvent* ev) {
216
+ if (gEvents.NonBlockingCall(ev) != napi_ok) delete ev;
217
+ }
218
+
219
+ static void QueueResponse(UNNotificationResponse* r) {
220
+ NotifEvent* ev = new NotifEvent;
221
+ UNNotificationRequest* req = r.notification.request;
222
+ ev->identifier = req.identifier.UTF8String;
223
+ NSString* action = r.actionIdentifier;
224
+ if ([action isEqualToString:UNNotificationDismissActionIdentifier]) {
225
+ ev->type = "notification-dismissed";
226
+ ev->reason = "dismissed";
227
+ } else {
228
+ ev->type = "notification-action";
229
+ ev->actionId = [action isEqualToString:UNNotificationDefaultActionIdentifier]
230
+ ? "default"
231
+ : action.UTF8String;
232
+ }
233
+ NSString* cat = req.content.categoryIdentifier;
234
+ if (cat.length && ![cat isEqualToString:kDefaultCategory]) {
235
+ ev->categoryId = cat.UTF8String;
236
+ }
237
+ NSString* json = UserInfoJson(req.content.userInfo);
238
+ if (json) {
239
+ ev->hasUserInfo = true;
240
+ ev->userInfoJson = json.UTF8String;
241
+ }
242
+ if ([r isKindOfClass:UNTextInputNotificationResponse.class]) {
243
+ NSString* text = ((UNTextInputNotificationResponse*)r).userText;
244
+ if (text) {
245
+ ev->hasUserText = true;
246
+ ev->userText = text.UTF8String;
247
+ }
248
+ }
249
+ QueueEvent(ev);
250
+ }
251
+
252
+ @interface CALNotificationDelegate : NSObject <UNUserNotificationCenterDelegate>
253
+ @end
254
+ @implementation CALNotificationDelegate
255
+ // Also while the app is frontmost: the renderer posted it on purpose, and
256
+ // without this the system shows nothing for a foreground app.
257
+ - (void)userNotificationCenter:(UNUserNotificationCenter*)center
258
+ willPresentNotification:(UNNotification*)notification
259
+ withCompletionHandler:
260
+ (void (^)(UNNotificationPresentationOptions))completionHandler {
261
+ (void)center;
262
+ (void)notification;
263
+ completionHandler(UNNotificationPresentationOptionBanner |
264
+ UNNotificationPresentationOptionList |
265
+ UNNotificationPresentationOptionSound |
266
+ UNNotificationPresentationOptionBadge);
267
+ }
268
+ - (void)userNotificationCenter:(UNUserNotificationCenter*)center
269
+ didReceiveNotificationResponse:(UNNotificationResponse*)response
270
+ withCompletionHandler:(void (^)(void))completionHandler {
271
+ (void)center;
272
+ QueueResponse(response);
273
+ completionHandler();
274
+ }
275
+ @end
276
+
277
+ static UNNotificationCategory* DefaultCategory() {
278
+ return [UNNotificationCategory
279
+ categoryWithIdentifier:kDefaultCategory
280
+ actions:@[]
281
+ intentIdentifiers:@[]
282
+ options:UNNotificationCategoryOptionCustomDismissAction];
283
+ }
284
+
285
+ static void ProbeCenter(Napi::Env env) {
286
+ if (gProbed) return;
287
+ gProbed = true;
288
+ gEvents = EventTsfn::New(env, "appkit:notifications", 0, 1);
289
+ gEvents.Unref(env); // events never hold the loop open by themselves
290
+ @autoreleasepool {
291
+ NSBundle* main = NSBundle.mainBundle;
292
+ if (!main.bundleIdentifier) {
293
+ gUnavailable = [NSString
294
+ stringWithFormat:@"the process is not an app bundle: %@ has no "
295
+ @"CFBundleIdentifier, and UNUserNotificationCenter "
296
+ @"delivers only for a bundled, code-signed "
297
+ @"executable (see README, \"Desktop notifications\")",
298
+ main.bundleURL.path ?: @"the main bundle"];
299
+ return;
300
+ }
301
+ UNUserNotificationCenter* c = nil;
302
+ @try {
303
+ c = UNUserNotificationCenter.currentNotificationCenter;
304
+ } @catch (NSException* e) {
305
+ gUnavailable = [NSString
306
+ stringWithFormat:@"UNUserNotificationCenter is unreachable for %@: %@",
307
+ main.bundleIdentifier, e.reason ?: e.name];
308
+ return;
309
+ }
310
+ if (!c) {
311
+ gUnavailable = @"UNUserNotificationCenter.currentNotificationCenter is nil";
312
+ return;
313
+ }
314
+ gCenter = c;
315
+ gDelegate = [CALNotificationDelegate new];
316
+ gCenter.delegate = gDelegate;
317
+ gCategories = [NSSet setWithObject:DefaultCategory()];
318
+ [gCenter setNotificationCategories:gCategories];
319
+ }
320
+ }
321
+
322
+ // The centre, or a thrown Error naming why there is none.
323
+ static UNUserNotificationCenter* CenterOrThrow(Napi::Env env, const char* fn) {
324
+ if (gCenter) return gCenter;
325
+ Napi::Error::New(env, std::string(fn) + ": notifications are unavailable — " +
326
+ gUnavailable.UTF8String)
327
+ .ThrowAsJavaScriptException();
328
+ return nil;
329
+ }
330
+
331
+ // --- settings ----------------------------------------------------------------
332
+
333
+ static const char* AuthName(UNAuthorizationStatus s) {
334
+ switch (s) {
335
+ case UNAuthorizationStatusDenied: return "denied";
336
+ case UNAuthorizationStatusAuthorized: return "authorized";
337
+ case UNAuthorizationStatusProvisional: return "provisional";
338
+ case UNAuthorizationStatusNotDetermined:
339
+ default: return "notDetermined";
340
+ }
341
+ }
342
+
343
+ static const char* SettingName(UNNotificationSetting s) {
344
+ switch (s) {
345
+ case UNNotificationSettingDisabled: return "disabled";
346
+ case UNNotificationSettingEnabled: return "enabled";
347
+ case UNNotificationSettingNotSupported:
348
+ default: return "notSupported";
349
+ }
350
+ }
351
+
352
+ static const char* AlertStyleName(UNAlertStyle s) {
353
+ switch (s) {
354
+ case UNAlertStyleBanner: return "banner";
355
+ case UNAlertStyleAlert: return "alert";
356
+ case UNAlertStyleNone:
357
+ default: return "none";
358
+ }
359
+ }
360
+
361
+ static const char* PreviewsName(UNShowPreviewsSetting s) {
362
+ switch (s) {
363
+ case UNShowPreviewsSettingAlways: return "always";
364
+ case UNShowPreviewsSettingWhenAuthenticated: return "whenAuthenticated";
365
+ case UNShowPreviewsSettingNever:
366
+ default: return "never";
367
+ }
368
+ }
369
+
370
+ static Napi::Object SettingsObject(Napi::Env env, UNNotificationSettings* s) {
371
+ Napi::Object o = Napi::Object::New(env);
372
+ o.Set("available", true);
373
+ o.Set("bundleIdentifier", NSBundle.mainBundle.bundleIdentifier.UTF8String);
374
+ o.Set("authorizationStatus", AuthName(s.authorizationStatus));
375
+ o.Set("alert", SettingName(s.alertSetting));
376
+ o.Set("sound", SettingName(s.soundSetting));
377
+ o.Set("badge", SettingName(s.badgeSetting));
378
+ o.Set("notificationCenter", SettingName(s.notificationCenterSetting));
379
+ o.Set("lockScreen", SettingName(s.lockScreenSetting));
380
+ o.Set("criticalAlert", SettingName(s.criticalAlertSetting));
381
+ o.Set("alertStyle", AlertStyleName(s.alertStyle));
382
+ o.Set("showPreviews", PreviewsName(s.showPreviewsSetting));
383
+ if (@available(macOS 12.0, *)) {
384
+ o.Set("timeSensitive", SettingName(s.timeSensitiveSetting));
385
+ }
386
+ return o;
387
+ }
388
+
389
+ static Napi::Object UnavailableObject(Napi::Env env) {
390
+ Napi::Object o = Napi::Object::New(env);
391
+ o.Set("available", false);
392
+ o.Set("bundleIdentifier",
393
+ StringOrNull(env, NSBundle.mainBundle.bundleIdentifier));
394
+ o.Set("reason", gUnavailable.UTF8String);
395
+ return o;
396
+ }
397
+
398
+ static bool CallbackArg(const Napi::CallbackInfo& info, size_t at,
399
+ const char* fn, const char* shape) {
400
+ if (info.Length() > at && info[at].IsFunction()) return true;
401
+ return NThrowType(info.Env(),
402
+ std::string(fn) + ": expected a callback " + shape);
403
+ }
404
+
405
+ // notificationSettings(cb) — cb({ available, bundleIdentifier, reason }) in
406
+ // an unbundled process, else cb({ available: true, bundleIdentifier,
407
+ // authorizationStatus, alert, sound, badge, notificationCenter, lockScreen,
408
+ // criticalAlert, alertStyle, showPreviews, timeSensitive }). Never throws
409
+ // for the state of the process; once, asynchronously.
410
+ static Napi::Value NotificationSettings(const Napi::CallbackInfo& info) {
411
+ Napi::Env env = info.Env();
412
+ if (!CallbackArg(info, 0, "notificationSettings", "(cb)"))
413
+ return env.Undefined();
414
+ Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
415
+ env, info[0].As<Napi::Function>(), "appkit:notificationSettings", 0, 1);
416
+ if (!gCenter) {
417
+ tsfn.BlockingCall((void*)nullptr,
418
+ [](Napi::Env env, Napi::Function cb, void*) {
419
+ cb.Call({UnavailableObject(env)});
420
+ });
421
+ tsfn.Release();
422
+ return env.Undefined();
423
+ }
424
+ [gCenter getNotificationSettingsWithCompletionHandler:^(
425
+ UNNotificationSettings* s) {
426
+ void* p = (void*)CFBridgingRetain(s);
427
+ tsfn.BlockingCall(p, [](Napi::Env env, Napi::Function cb, void* p) {
428
+ UNNotificationSettings* s = CFBridgingRelease(p);
429
+ cb.Call({SettingsObject(env, s)});
430
+ });
431
+ tsfn.Release();
432
+ }];
433
+ return env.Undefined();
434
+ }
435
+
436
+ // --- authorization -----------------------------------------------------------
437
+
438
+ static const char* const kAuthOptionNames =
439
+ "alert, sound, badge, provisional, criticalAlert, "
440
+ "providesAppNotificationSettings";
441
+
442
+ static bool ParseAuthOptions(Napi::Env env, Napi::Value v, const char* fn,
443
+ UNAuthorizationOptions* out) {
444
+ if (!v.IsArray()) {
445
+ return NThrowType(env, std::string(fn) + ": expected an array of options (" +
446
+ kAuthOptionNames + ")");
447
+ }
448
+ Napi::Array a = v.As<Napi::Array>();
449
+ UNAuthorizationOptions opts = UNAuthorizationOptionNone;
450
+ for (uint32_t i = 0; i < a.Length(); i++) {
451
+ Napi::Value e = a.Get(i);
452
+ std::string s = e.IsString() ? e.As<Napi::String>().Utf8Value() : "";
453
+ if (s == "alert") opts |= UNAuthorizationOptionAlert;
454
+ else if (s == "sound") opts |= UNAuthorizationOptionSound;
455
+ else if (s == "badge") opts |= UNAuthorizationOptionBadge;
456
+ else if (s == "provisional") opts |= UNAuthorizationOptionProvisional;
457
+ else if (s == "criticalAlert") opts |= UNAuthorizationOptionCriticalAlert;
458
+ else if (s == "providesAppNotificationSettings")
459
+ opts |= UNAuthorizationOptionProvidesAppNotificationSettings;
460
+ else
461
+ return NThrowType(env, std::string(fn) + ": unknown option '" + s + "' (" +
462
+ kAuthOptionNames + ")");
463
+ }
464
+ *out = opts;
465
+ return true;
466
+ }
467
+
468
+ struct Outcome {
469
+ bool ok;
470
+ NSError* error; // retained by the struct's owner
471
+ };
472
+
473
+ static Napi::Value ErrorValue(Napi::Env env, NSError* e) {
474
+ if (!e) return env.Null();
475
+ Napi::Error err = Napi::Error::New(env, e.localizedDescription.UTF8String);
476
+ err.Set("code", (double)e.code);
477
+ err.Set("domain", e.domain.UTF8String);
478
+ return err.Value();
479
+ }
480
+
481
+ // requestNotificationAuthorization(options, cb) — the system prompt, once
482
+ // per app (later calls answer from the stored decision); cb(granted, error)
483
+ // once, asynchronously. options: ['alert', 'sound', 'badge'] and friends.
484
+ // A grant re-applies the category set, since the system held none for the
485
+ // app while it was unauthorized.
486
+ static Napi::Value RequestNotificationAuthorization(
487
+ const Napi::CallbackInfo& info) {
488
+ Napi::Env env = info.Env();
489
+ const char* fn = "requestNotificationAuthorization";
490
+ UNAuthorizationOptions opts;
491
+ if (info.Length() < 1 || !ParseAuthOptions(env, info[0], fn, &opts))
492
+ return env.Undefined();
493
+ if (!CallbackArg(info, 1, fn, "(options, cb)")) return env.Undefined();
494
+ UNUserNotificationCenter* center = CenterOrThrow(env, fn);
495
+ if (!center) return env.Undefined();
496
+ Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
497
+ env, info[1].As<Napi::Function>(), "appkit:requestNotificationAuthorization",
498
+ 0, 1);
499
+ [center requestAuthorizationWithOptions:opts
500
+ completionHandler:^(BOOL granted, NSError* error) {
501
+ Outcome* out = new Outcome{(bool)granted, error};
502
+ tsfn.BlockingCall(
503
+ out, [](Napi::Env env, Napi::Function cb,
504
+ Outcome* out) {
505
+ if (out->ok && gCenter && gCategories) {
506
+ [gCenter setNotificationCategories:gCategories];
507
+ }
508
+ cb.Call({Napi::Boolean::New(env, out->ok),
509
+ ErrorValue(env, out->error)});
510
+ delete out;
511
+ });
512
+ tsfn.Release();
513
+ }];
514
+ return env.Undefined();
515
+ }
516
+
517
+ // --- categories --------------------------------------------------------------
518
+
519
+ static UNNotificationAction* BuildAction(Napi::Env env, Napi::Object o,
520
+ const char* fn) {
521
+ NSString* id;
522
+ NSString* title;
523
+ if (!NOptString(env, o, "id", fn, &id)) return nil;
524
+ if (!NOptString(env, o, "title", fn, &title)) return nil;
525
+ if (!id.length || !title.length) {
526
+ NThrowType(env, std::string(fn) + ": an action needs { id, title }");
527
+ return nil;
528
+ }
529
+ bool destructive, foreground, auth;
530
+ if (!NOptBool(env, o, "destructive", fn, false, &destructive)) return nil;
531
+ if (!NOptBool(env, o, "foreground", fn, false, &foreground)) return nil;
532
+ if (!NOptBool(env, o, "authenticationRequired", fn, false, &auth)) return nil;
533
+ UNNotificationActionOptions opts = UNNotificationActionOptionNone;
534
+ if (destructive) opts |= UNNotificationActionOptionDestructive;
535
+ if (foreground) opts |= UNNotificationActionOptionForeground;
536
+ if (auth) opts |= UNNotificationActionOptionAuthenticationRequired;
537
+ return [UNNotificationAction actionWithIdentifier:id title:title options:opts];
538
+ }
539
+
540
+ static UNNotificationCategory* BuildCategory(Napi::Env env, Napi::Object o,
541
+ const char* fn) {
542
+ NSString* id;
543
+ if (!NOptString(env, o, "id", fn, &id)) return nil;
544
+ if (!id.length) {
545
+ NThrowType(env, std::string(fn) + ": a category needs an id");
546
+ return nil;
547
+ }
548
+ NSMutableArray<UNNotificationAction*>* actions = [NSMutableArray new];
549
+ if (o.Has("actions") && !o.Get("actions").IsUndefined() &&
550
+ !o.Get("actions").IsNull()) {
551
+ Napi::Value v = o.Get("actions");
552
+ if (!v.IsArray()) {
553
+ NThrowType(env, std::string(fn) + ": 'actions' must be an array");
554
+ return nil;
555
+ }
556
+ Napi::Array a = v.As<Napi::Array>();
557
+ for (uint32_t i = 0; i < a.Length(); i++) {
558
+ Napi::Value e = a.Get(i);
559
+ if (!e.IsObject()) {
560
+ NThrowType(env, std::string(fn) + ": an action must be an object");
561
+ return nil;
562
+ }
563
+ UNNotificationAction* act = BuildAction(env, e.As<Napi::Object>(), fn);
564
+ if (!act) return nil;
565
+ [actions addObject:act];
566
+ }
567
+ }
568
+ bool dismiss;
569
+ if (!NOptBool(env, o, "customDismissAction", fn, true, &dismiss)) return nil;
570
+ UNNotificationCategoryOptions opts = UNNotificationCategoryOptionNone;
571
+ if (dismiss) opts |= UNNotificationCategoryOptionCustomDismissAction;
572
+ return [UNNotificationCategory categoryWithIdentifier:id
573
+ actions:actions
574
+ intentIdentifiers:@[]
575
+ options:opts];
576
+ }
577
+
578
+ // setNotificationCategories([{ id, actions: [{ id, title, destructive?,
579
+ // foreground?, authenticationRequired? }], customDismissAction? }]) —
580
+ // replaces the app's whole set; the bridge's own category for uncategorised
581
+ // notifications is always part of it.
582
+ static Napi::Value SetNotificationCategories(const Napi::CallbackInfo& info) {
583
+ Napi::Env env = info.Env();
584
+ const char* fn = "setNotificationCategories";
585
+ if (info.Length() < 1 || !info[0].IsArray()) {
586
+ NThrowType(env, std::string(fn) + ": expected an array of categories");
587
+ return env.Undefined();
588
+ }
589
+ @autoreleasepool {
590
+ NSMutableSet<UNNotificationCategory*>* set = [NSMutableSet new];
591
+ Napi::Array a = info[0].As<Napi::Array>();
592
+ for (uint32_t i = 0; i < a.Length(); i++) {
593
+ Napi::Value e = a.Get(i);
594
+ if (!e.IsObject()) {
595
+ NThrowType(env, std::string(fn) + ": a category must be an object");
596
+ return env.Undefined();
597
+ }
598
+ UNNotificationCategory* c = BuildCategory(env, e.As<Napi::Object>(), fn);
599
+ if (!c) return env.Undefined();
600
+ [set addObject:c];
601
+ }
602
+ UNUserNotificationCenter* center = CenterOrThrow(env, fn);
603
+ if (!center) return env.Undefined();
604
+ [set addObject:DefaultCategory()];
605
+ gCategories = set;
606
+ [center setNotificationCategories:set];
607
+ }
608
+ return env.Undefined();
609
+ }
610
+
611
+ static Napi::Object CategoryObject(Napi::Env env, UNNotificationCategory* c) {
612
+ Napi::Object o = Napi::Object::New(env);
613
+ o.Set("id", c.identifier.UTF8String);
614
+ Napi::Array actions = Napi::Array::New(env);
615
+ uint32_t n = 0;
616
+ for (UNNotificationAction* a in c.actions) {
617
+ Napi::Object ao = Napi::Object::New(env);
618
+ ao.Set("id", a.identifier.UTF8String);
619
+ ao.Set("title", a.title.UTF8String);
620
+ ao.Set("destructive",
621
+ (bool)(a.options & UNNotificationActionOptionDestructive));
622
+ ao.Set("foreground",
623
+ (bool)(a.options & UNNotificationActionOptionForeground));
624
+ ao.Set("authenticationRequired",
625
+ (bool)(a.options & UNNotificationActionOptionAuthenticationRequired));
626
+ actions.Set(n++, ao);
627
+ }
628
+ o.Set("actions", actions);
629
+ o.Set("customDismissAction",
630
+ (bool)(c.options & UNNotificationCategoryOptionCustomDismissAction));
631
+ return o;
632
+ }
633
+
634
+ // notificationCategories(cb) — cb([{ id, actions, customDismissAction }]),
635
+ // the set as the system holds it, bridge category included.
636
+ static Napi::Value NotificationCategories(const Napi::CallbackInfo& info) {
637
+ Napi::Env env = info.Env();
638
+ const char* fn = "notificationCategories";
639
+ if (!CallbackArg(info, 0, fn, "(cb)")) return env.Undefined();
640
+ UNUserNotificationCenter* center = CenterOrThrow(env, fn);
641
+ if (!center) return env.Undefined();
642
+ Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
643
+ env, info[0].As<Napi::Function>(), "appkit:notificationCategories", 0, 1);
644
+ [center getNotificationCategoriesWithCompletionHandler:^(
645
+ NSSet<UNNotificationCategory*>* cats) {
646
+ void* p = (void*)CFBridgingRetain(cats);
647
+ tsfn.BlockingCall(p, [](Napi::Env env, Napi::Function cb, void* p) {
648
+ NSSet<UNNotificationCategory*>* cats = CFBridgingRelease(p);
649
+ Napi::Array out = Napi::Array::New(env);
650
+ uint32_t n = 0;
651
+ for (UNNotificationCategory* c in cats) out.Set(n++, CategoryObject(env, c));
652
+ cb.Call({out});
653
+ });
654
+ tsfn.Release();
655
+ }];
656
+ return env.Undefined();
657
+ }
658
+
659
+ // --- post / update / remove --------------------------------------------------
660
+
661
+ // { identifier?, title, subtitle?, body?, sound?: 'default' | <name> | null,
662
+ // categoryId?, userInfo?, threadId?, badge?: number | null }
663
+ static UNNotificationRequest* BuildRequest(Napi::Env env, Napi::Object o,
664
+ NSString* identifier,
665
+ const char* fn) {
666
+ NSString* title;
667
+ NSString* subtitle;
668
+ NSString* body;
669
+ NSString* sound;
670
+ NSString* categoryId;
671
+ NSString* threadId;
672
+ if (!NOptString(env, o, "title", fn, &title)) return nil;
673
+ if (!title) {
674
+ NThrowType(env, std::string(fn) + ": 'title' (a string) is required");
675
+ return nil;
676
+ }
677
+ if (!NOptString(env, o, "subtitle", fn, &subtitle)) return nil;
678
+ if (!NOptString(env, o, "body", fn, &body)) return nil;
679
+ if (!NOptString(env, o, "sound", fn, &sound)) return nil;
680
+ if (!NOptString(env, o, "categoryId", fn, &categoryId)) return nil;
681
+ if (!NOptString(env, o, "threadId", fn, &threadId)) return nil;
682
+ if (!identifier) {
683
+ if (!NOptString(env, o, "identifier", fn, &identifier)) return nil;
684
+ if (!identifier.length) identifier = NSUUID.UUID.UUIDString;
685
+ }
686
+
687
+ UNMutableNotificationContent* c = [UNMutableNotificationContent new];
688
+ c.title = title;
689
+ if (subtitle) c.subtitle = subtitle;
690
+ if (body) c.body = body;
691
+ if (sound) {
692
+ c.sound = [sound isEqualToString:@"default"]
693
+ ? UNNotificationSound.defaultSound
694
+ : [UNNotificationSound soundNamed:sound];
695
+ }
696
+ c.categoryIdentifier = categoryId.length ? categoryId : kDefaultCategory;
697
+ if (threadId) c.threadIdentifier = threadId;
698
+ if (o.Has("badge")) {
699
+ Napi::Value v = o.Get("badge");
700
+ if (v.IsNumber()) {
701
+ c.badge = @((NSInteger)v.As<Napi::Number>().Int64Value());
702
+ } else if (!v.IsUndefined() && !v.IsNull()) {
703
+ NThrowType(env, std::string(fn) + ": 'badge' must be a number or null");
704
+ return nil;
705
+ }
706
+ }
707
+ if (o.Has("userInfo")) {
708
+ Napi::Value v = o.Get("userInfo");
709
+ if (!v.IsUndefined() && !v.IsNull()) {
710
+ Napi::Value json = JsonStringify(env, v);
711
+ if (env.IsExceptionPending()) return nil;
712
+ if (!json.IsString()) {
713
+ NThrowType(env, std::string(fn) + ": 'userInfo' must be JSON-serialisable");
714
+ return nil;
715
+ }
716
+ c.userInfo = @{kUserInfoKey : NToNSString(json)};
717
+ }
718
+ }
719
+ return [UNNotificationRequest requestWithIdentifier:identifier
720
+ content:c
721
+ trigger:nil];
722
+ }
723
+
724
+ static Napi::Value Post(const Napi::CallbackInfo& info, size_t propsAt,
725
+ NSString* identifier, const char* fn) {
726
+ Napi::Env env = info.Env();
727
+ if (info.Length() <= propsAt || !info[propsAt].IsObject()) {
728
+ NThrowType(env, std::string(fn) + ": expected a props object { title, ... }");
729
+ return env.Undefined();
730
+ }
731
+ size_t cbAt = propsAt + 1;
732
+ bool hasCb = info.Length() > cbAt && info[cbAt].IsFunction();
733
+ if (info.Length() > cbAt && !hasCb && !info[cbAt].IsUndefined() &&
734
+ !info[cbAt].IsNull()) {
735
+ NThrowType(env, std::string(fn) + ": the callback must be a function");
736
+ return env.Undefined();
737
+ }
738
+ @autoreleasepool {
739
+ UNNotificationRequest* req =
740
+ BuildRequest(env, info[propsAt].As<Napi::Object>(), identifier, fn);
741
+ if (!req) return env.Undefined();
742
+ UNUserNotificationCenter* center = CenterOrThrow(env, fn);
743
+ if (!center) return env.Undefined();
744
+ if (!hasCb) {
745
+ [center addNotificationRequest:req withCompletionHandler:nil];
746
+ } else {
747
+ Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
748
+ env, info[cbAt].As<Napi::Function>(), "appkit:postNotification", 0,
749
+ 1);
750
+ [center addNotificationRequest:req
751
+ withCompletionHandler:^(NSError* error) {
752
+ Outcome* out = new Outcome{error == nil, error};
753
+ tsfn.BlockingCall(
754
+ out, [](Napi::Env env, Napi::Function cb, Outcome* out) {
755
+ cb.Call({ErrorValue(env, out->error)});
756
+ delete out;
757
+ });
758
+ tsfn.Release();
759
+ }];
760
+ }
761
+ return Napi::String::New(env, req.identifier.UTF8String);
762
+ }
763
+ }
764
+
765
+ // postNotification(props, cb?) -> identifier. cb(error | null) once the
766
+ // system has accepted or refused the request — refused, for one, while the
767
+ // app is not authorized (UNErrorCodeNotificationsNotAllowed, code 1).
768
+ static Napi::Value PostNotification(const Napi::CallbackInfo& info) {
769
+ return Post(info, 0, nil, "postNotification");
770
+ }
771
+
772
+ // updateNotification(identifier, props, cb?) -> identifier: the same request
773
+ // under the same identifier replaces the banner in place.
774
+ static Napi::Value UpdateNotification(const Napi::CallbackInfo& info) {
775
+ Napi::Env env = info.Env();
776
+ if (info.Length() < 1 || !info[0].IsString() ||
777
+ info[0].As<Napi::String>().Utf8Value().empty()) {
778
+ NThrowType(env, "updateNotification: expected (identifier, props, cb?)");
779
+ return env.Undefined();
780
+ }
781
+ return Post(info, 1, NToNSString(info[0]), "updateNotification");
782
+ }
783
+
784
+ // removeNotification(identifier | [identifiers]) — out of Notification
785
+ // Center, and off the queue if not yet delivered.
786
+ static Napi::Value RemoveNotification(const Napi::CallbackInfo& info) {
787
+ Napi::Env env = info.Env();
788
+ const char* fn = "removeNotification";
789
+ NSMutableArray<NSString*>* ids = [NSMutableArray new];
790
+ if (info.Length() >= 1 && info[0].IsString()) {
791
+ [ids addObject:NToNSString(info[0])];
792
+ } else if (info.Length() >= 1 && info[0].IsArray()) {
793
+ Napi::Array a = info[0].As<Napi::Array>();
794
+ for (uint32_t i = 0; i < a.Length(); i++) {
795
+ Napi::Value e = a.Get(i);
796
+ if (!e.IsString()) {
797
+ NThrowType(env, std::string(fn) + ": identifiers must be strings");
798
+ return env.Undefined();
799
+ }
800
+ [ids addObject:NToNSString(e)];
801
+ }
802
+ } else {
803
+ NThrowType(env, std::string(fn) + ": expected an identifier or an array of them");
804
+ return env.Undefined();
805
+ }
806
+ UNUserNotificationCenter* center = CenterOrThrow(env, fn);
807
+ if (!center) return env.Undefined();
808
+ [center removePendingNotificationRequestsWithIdentifiers:ids];
809
+ [center removeDeliveredNotificationsWithIdentifiers:ids];
810
+ return env.Undefined();
811
+ }
812
+
813
+ // deliveredNotifications(cb) — cb([{ identifier, title, subtitle, body,
814
+ // categoryId, threadId, userInfo, date }]): what is in Notification Center
815
+ // for this app right now, newest last as the system lists them.
816
+ static Napi::Value DeliveredNotifications(const Napi::CallbackInfo& info) {
817
+ Napi::Env env = info.Env();
818
+ const char* fn = "deliveredNotifications";
819
+ if (!CallbackArg(info, 0, fn, "(cb)")) return env.Undefined();
820
+ UNUserNotificationCenter* center = CenterOrThrow(env, fn);
821
+ if (!center) return env.Undefined();
822
+ Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
823
+ env, info[0].As<Napi::Function>(), "appkit:deliveredNotifications", 0, 1);
824
+ [center getDeliveredNotificationsWithCompletionHandler:^(
825
+ NSArray<UNNotification*>* list) {
826
+ void* p = (void*)CFBridgingRetain(list);
827
+ tsfn.BlockingCall(p, [](Napi::Env env, Napi::Function cb, void* p) {
828
+ NSArray<UNNotification*>* list = CFBridgingRelease(p);
829
+ Napi::Array out = Napi::Array::New(env);
830
+ uint32_t n = 0;
831
+ for (UNNotification* note in list) {
832
+ UNNotificationRequest* req = note.request;
833
+ UNNotificationContent* c = req.content;
834
+ Napi::Object o = Napi::Object::New(env);
835
+ o.Set("identifier", req.identifier.UTF8String);
836
+ o.Set("title", c.title.UTF8String);
837
+ o.Set("subtitle", c.subtitle.UTF8String);
838
+ o.Set("body", c.body.UTF8String);
839
+ NSString* cat = c.categoryIdentifier;
840
+ o.Set("categoryId",
841
+ (cat.length && ![cat isEqualToString:kDefaultCategory])
842
+ ? Napi::String::New(env, cat.UTF8String)
843
+ : env.Null());
844
+ o.Set("threadId", StringOrNull(env, c.threadIdentifier));
845
+ NSString* json = UserInfoJson(c.userInfo);
846
+ if (json) {
847
+ Napi::Value v = JsonParse(env, json);
848
+ if (env.IsExceptionPending()) {
849
+ (void)env.GetAndClearPendingException();
850
+ v = Napi::String::New(env, json.UTF8String);
851
+ }
852
+ o.Set("userInfo", v);
853
+ }
854
+ o.Set("date", note.date.timeIntervalSince1970 * 1000.0);
855
+ out.Set(n++, o);
856
+ }
857
+ cb.Call({out});
858
+ });
859
+ tsfn.Release();
860
+ }];
861
+ return env.Undefined();
862
+ }
863
+
864
+ // --- test seam ---------------------------------------------------------------
865
+
866
+ // postNotificationResponse({ identifier, actionId?, dismissed?, categoryId?,
867
+ // userInfo?, userText? }) — a response as the delegate would queue it, minus
868
+ // the delegate: the same hand-off to node's loop, the same hold-and-replay,
869
+ // the same event shape. Test-only, like postMouseEvent and postKeyEvent; it
870
+ // needs no bundle, since nothing here touches the centre.
871
+ static Napi::Value PostNotificationResponse(const Napi::CallbackInfo& info) {
872
+ Napi::Env env = info.Env();
873
+ const char* fn = "postNotificationResponse";
874
+ if (info.Length() < 1 || !info[0].IsObject()) {
875
+ NThrowType(env, std::string(fn) + ": expected { identifier, actionId?, "
876
+ "dismissed?, categoryId?, userInfo?, "
877
+ "userText? }");
878
+ return env.Undefined();
879
+ }
880
+ Napi::Object o = info[0].As<Napi::Object>();
881
+ NSString* identifier;
882
+ NSString* actionId;
883
+ NSString* categoryId;
884
+ NSString* userText;
885
+ bool dismissed;
886
+ if (!NOptString(env, o, "identifier", fn, &identifier)) return env.Undefined();
887
+ if (!identifier.length) {
888
+ NThrowType(env, std::string(fn) + ": 'identifier' (a string) is required");
889
+ return env.Undefined();
890
+ }
891
+ if (!NOptString(env, o, "actionId", fn, &actionId)) return env.Undefined();
892
+ if (!NOptString(env, o, "categoryId", fn, &categoryId)) return env.Undefined();
893
+ if (!NOptString(env, o, "userText", fn, &userText)) return env.Undefined();
894
+ if (!NOptBool(env, o, "dismissed", fn, false, &dismissed)) return env.Undefined();
895
+ NotifEvent* ev = new NotifEvent;
896
+ ev->identifier = identifier.UTF8String;
897
+ if (dismissed) {
898
+ ev->type = "notification-dismissed";
899
+ ev->reason = "dismissed";
900
+ } else {
901
+ ev->type = "notification-action";
902
+ ev->actionId = actionId.length ? actionId.UTF8String : "default";
903
+ }
904
+ if (categoryId.length && ![categoryId isEqualToString:kDefaultCategory]) {
905
+ ev->categoryId = categoryId.UTF8String;
906
+ }
907
+ if (o.Has("userInfo") && !o.Get("userInfo").IsUndefined() &&
908
+ !o.Get("userInfo").IsNull()) {
909
+ Napi::Value json = JsonStringify(env, o.Get("userInfo"));
910
+ if (env.IsExceptionPending()) {
911
+ delete ev;
912
+ return env.Undefined();
913
+ }
914
+ if (json.IsString()) {
915
+ ev->hasUserInfo = true;
916
+ ev->userInfoJson = json.As<Napi::String>().Utf8Value();
917
+ }
918
+ }
919
+ if (userText) {
920
+ ev->hasUserText = true;
921
+ ev->userText = userText.UTF8String;
922
+ }
923
+ QueueEvent(ev);
924
+ return env.Undefined();
925
+ }
926
+
927
+ // ---------------------------------------------------------------------------
928
+ // registration (called from addon.mm's Init, i.e. at require time — before
929
+ // initApp() finishes launching, which is when the delegate has to be in place)
930
+ // ---------------------------------------------------------------------------
931
+
932
+ void InitNotifications(Napi::Env env, Napi::Object exports) {
933
+ ProbeCenter(env);
934
+ exports.Set("notificationSettings",
935
+ Napi::Function::New(env, NotificationSettings));
936
+ exports.Set("requestNotificationAuthorization",
937
+ Napi::Function::New(env, RequestNotificationAuthorization));
938
+ exports.Set("setNotificationCategories",
939
+ Napi::Function::New(env, SetNotificationCategories));
940
+ exports.Set("notificationCategories",
941
+ Napi::Function::New(env, NotificationCategories));
942
+ exports.Set("postNotification", Napi::Function::New(env, PostNotification));
943
+ exports.Set("updateNotification",
944
+ Napi::Function::New(env, UpdateNotification));
945
+ exports.Set("removeNotification",
946
+ Napi::Function::New(env, RemoveNotification));
947
+ exports.Set("deliveredNotifications",
948
+ Napi::Function::New(env, DeliveredNotifications));
949
+ exports.Set("postNotificationResponse",
950
+ Napi::Function::New(env, PostNotificationResponse));
951
+ }