@amrshbib/react-native-pushbib 0.0.2 → 0.1.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.
package/src/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AppState, Linking, Platform } from 'react-native';
1
+ import { AppState, Linking, PermissionsAndroid, Platform } from 'react-native';
2
2
  import { ApiClient, ApiError } from './api';
3
3
  import { EventManager } from './EventManager';
4
4
  import { log, setLogLevel } from './Logger';
@@ -41,9 +41,27 @@ function tagItems(value) {
41
41
  return [String(value)];
42
42
  }
43
43
 
44
+ // Notification events carry OneSignal's shape as well as Pushbib's own fields: callers can read
45
+ // additionalData / launchURL and call getNotification() and display(), so one handler fits both SDKs.
46
+ function buildNotification(raw, display) {
47
+ const payload = raw || {};
48
+ const data = payload.data || {};
49
+ return {
50
+ ...payload,
51
+ notificationId: payload.notificationId ?? null,
52
+ title: payload.title ?? null,
53
+ body: payload.body ?? null,
54
+ launchURL: payload.url ?? null,
55
+ additionalData: data,
56
+ data,
57
+ display: display || (() => {}),
58
+ };
59
+ }
60
+
44
61
  const PREFS = {
45
62
  subscriptionId: 'subscription_id',
46
63
  externalId: 'external_id',
64
+ identityHash: 'identity_hash',
47
65
  optedOut: 'opted_out',
48
66
  tags: 'tags_cache',
49
67
  config: 'config_cache',
@@ -53,6 +71,29 @@ const PREFS = {
53
71
  showForeground: 'show_foreground',
54
72
  showBackground: 'show_background',
55
73
  showLiveUpdate: 'show_live_update',
74
+ language: 'language_override',
75
+ locationShared: 'location_shared',
76
+ permissionAsked: 'permission_asked',
77
+ };
78
+
79
+ // OneSignal's LogLevel enum, so Debug.setLogLevel(LogLevel.Verbose) reads the same on both SDKs.
80
+ export const LogLevel = {
81
+ None: 0,
82
+ Fatal: 1,
83
+ Error: 2,
84
+ Warn: 3,
85
+ Info: 4,
86
+ Debug: 5,
87
+ Verbose: 6,
88
+ };
89
+
90
+ // OneSignal's OSNotificationPermission enum, returned by Notifications.permissionNative().
91
+ export const NotificationPermission = {
92
+ NotDetermined: 0,
93
+ Denied: 1,
94
+ Authorized: 2,
95
+ Provisional: 3,
96
+ Ephemeral: 4,
56
97
  };
57
98
 
58
99
  const SESSION_PING_MIN_INTERVAL_MS = 30 * 1000;
@@ -91,11 +132,18 @@ class PushbibSdk {
91
132
  this._state = {
92
133
  subscriptionId: null,
93
134
  externalId: null,
135
+ // hex(HMAC-SHA256(app secret, externalId)), produced by your own backend. Only needed when
136
+ // the app has identity verification turned on; harmless to send when it does not.
137
+ identityHash: null,
94
138
  pushToken: null,
95
139
  optedOut: false,
96
140
  registered: false,
97
141
  tags: {},
98
142
  location: null,
143
+ // User.setLanguage() wins over the device locale reported by the native module
144
+ language: null,
145
+ locationShared: true,
146
+ permissionAsked: false,
99
147
  };
100
148
  this._needsRegister = false;
101
149
  this._lastSessionPingAt = 0;
@@ -106,6 +154,12 @@ class PushbibSdk {
106
154
  });
107
155
  this._queue = Promise.resolve();
108
156
 
157
+ // Same shape as OneSignal.Debug
158
+ this.Debug = {
159
+ setLogLevel: (level) => setLogLevel(level),
160
+ setAlertLevel: (level) => log.info(`Debug.setAlertLevel(${level}) — Pushbib has no alert log, ignored`),
161
+ };
162
+
109
163
  this.User = this._buildUserNamespace();
110
164
  this.Notifications = this._buildNotificationsNamespace();
111
165
  this.Location = this._buildLocationNamespace();
@@ -134,32 +188,66 @@ class PushbibSdk {
134
188
  this._ready.catch(() => {});
135
189
  }
136
190
 
137
- login(externalId) {
138
- if (typeof externalId !== 'string' || externalId.length === 0) {
139
- throw new Error('Pushbib.login(externalId) requires a non-empty string');
191
+ /**
192
+ * Identify the person using the app.
193
+ *
194
+ * @param {string} externalId your own id for this user
195
+ * @param {string} [identityHash]
196
+ * hex(HMAC-SHA256(secret, externalId)), computed on YOUR SERVER with the signing secret from
197
+ * the app's dashboard, and returned to the app when it signs in.
198
+ *
199
+ * Required when the app has identity verification turned on, and the reason it exists: the
200
+ * app key in this bundle can be read out of the binary by anyone who installs the app, so on
201
+ * its own it proves only that the caller has the app, never which user they are. Without a
202
+ * signature, a request could name anyone's external id and read or rewrite their tags.
203
+ *
204
+ * NEVER ship the signing secret in the app. If the secret is in the bundle, the signature
205
+ * proves nothing, because an attacker can compute it too.
206
+ */
207
+ login(externalId, identityHash) {
208
+ const id = externalId === null || externalId === undefined ? '' : String(externalId);
209
+ if (!id) {
210
+ log.warn('login(externalId) needs a non-empty id — ignoring the call');
211
+ return Promise.resolve();
212
+ }
213
+ let hash = identityHash;
214
+ if (hash !== undefined && hash !== null && typeof hash !== 'string') {
215
+ log.warn('login(externalId, identityHash) — identityHash must be a string; ignoring it');
216
+ hash = null;
140
217
  }
141
218
  return this._enqueue(async () => {
142
- this._state.externalId = externalId;
143
- await this._prefsSet(PREFS.externalId, externalId);
219
+ this._state.externalId = id;
220
+ this._state.identityHash = hash || null;
221
+ await this._prefsSet(PREFS.externalId, id);
222
+ await this._prefsSet(PREFS.identityHash, this._state.identityHash);
223
+ this._events.emit('userChange', { current: { externalId: id, subscriptionId: this._state.subscriptionId } });
144
224
  if (this._state.subscriptionId) {
145
225
  await this._api.link({
146
- external_id: externalId,
226
+ external_id: id,
147
227
  subscription_id: this._state.subscriptionId,
228
+ ...this._identity(),
148
229
  ...this._deviceHints(),
149
230
  });
150
- log.info(`logged in as "${externalId}"`);
231
+ log.info(`logged in as "${id}"`);
151
232
  }
152
233
  });
153
234
  }
154
235
 
155
236
  logout() {
156
237
  return this._enqueue(async () => {
157
- const { externalId, subscriptionId } = this._state;
238
+ const { externalId, subscriptionId, identityHash } = this._state;
158
239
  this._state.externalId = null;
240
+ this._state.identityHash = null;
159
241
  await this._prefsSet(PREFS.externalId, null);
242
+ await this._prefsSet(PREFS.identityHash, null);
243
+ this._events.emit('userChange', { current: { externalId: null, subscriptionId: subscriptionId } });
160
244
  if (externalId && subscriptionId) {
161
245
  await this._api
162
- .unlink({ external_id: externalId, subscription_id: subscriptionId })
246
+ .unlink({
247
+ external_id: externalId,
248
+ subscription_id: subscriptionId,
249
+ ...(identityHash ? { identity_hash: identityHash } : {}),
250
+ })
163
251
  .catch((e) => {
164
252
  if (!(e instanceof ApiError && e.status === 404)) throw e;
165
253
  });
@@ -171,7 +259,10 @@ class PushbibSdk {
171
259
  getMe() {
172
260
  return this._enqueue(async () => {
173
261
  if (!this._state.externalId) throw new Error('getMe() requires login() first');
174
- const res = await this._api.me({ external_id: this._state.externalId });
262
+ const res = await this._api.me({
263
+ external_id: this._state.externalId,
264
+ ...this._identity(),
265
+ });
175
266
  return res.data;
176
267
  });
177
268
  }
@@ -188,7 +279,8 @@ class PushbibSdk {
188
279
  },
189
280
  addTags(tags) {
190
281
  if (!tags || typeof tags !== 'object' || Array.isArray(tags) || Object.keys(tags).length === 0) {
191
- throw new Error('User.addTags requires a non-empty object');
282
+ log.warn('User.addTags needs a non-empty object — ignoring the call');
283
+ return Promise.resolve();
192
284
  }
193
285
  const normalized = {};
194
286
  for (const [k, v] of Object.entries(tags)) {
@@ -196,7 +288,8 @@ class PushbibSdk {
196
288
  if (value !== null) normalized[k] = value;
197
289
  }
198
290
  if (Object.keys(normalized).length === 0) {
199
- throw new Error('User.addTags requires at least one usable value');
291
+ log.warn('User.addTags got no usable value — ignoring the call');
292
+ return Promise.resolve();
200
293
  }
201
294
  return sdk._enqueue(async () => {
202
295
  for (const [k, v] of Object.entries(normalized)) sdk._state.tags[k] = v;
@@ -212,13 +305,15 @@ class PushbibSdk {
212
305
  },
213
306
  removeTag(key, items) {
214
307
  if (typeof key !== 'string' || key.length === 0) {
215
- throw new Error('User.removeTag requires a tag key');
308
+ log.warn('User.removeTag needs a tag key — ignoring the call');
309
+ return Promise.resolve();
216
310
  }
217
311
  if (items === undefined || items === null) return sdk.User.removeTags([key]);
218
312
 
219
313
  const drop = normalizeList(Array.isArray(items) ? items : [items]);
220
314
  if (drop.length === 0) {
221
- throw new Error('User.removeTag requires at least one item to remove');
315
+ log.warn('User.removeTag needs at least one item to remove — ignoring the call');
316
+ return Promise.resolve();
222
317
  }
223
318
  return sdk._enqueue(async () => {
224
319
  const current = sdk._state.tags[key];
@@ -232,18 +327,52 @@ class PushbibSdk {
232
327
  });
233
328
  },
234
329
  removeTags(keys) {
235
- if (!Array.isArray(keys) || keys.length === 0) {
236
- throw new Error('User.removeTags requires a non-empty array of keys');
330
+ const list = Array.isArray(keys) ? keys.filter(Boolean) : keys ? [keys] : [];
331
+ if (list.length === 0) {
332
+ log.warn('User.removeTags needs at least one key — ignoring the call');
333
+ return Promise.resolve();
237
334
  }
238
335
  return sdk._enqueue(async () => {
239
- for (const k of keys) delete sdk._state.tags[k];
336
+ for (const k of list) delete sdk._state.tags[k];
240
337
  await sdk._prefsSet(PREFS.tags, JSON.stringify(sdk._state.tags));
241
- await sdk._api.removeTags({ ...sdk._tagTarget(), tags: keys });
338
+ await sdk._api.removeTags({ ...sdk._tagTarget(), tags: list });
242
339
  });
243
340
  },
244
- getTags() {
341
+ // OneSignal resolves the tags from a promise; getTagsSync() keeps the old synchronous read.
342
+ async getTags() {
343
+ await sdk._ready.catch(() => {});
344
+ return { ...sdk._state.tags };
345
+ },
346
+ getTagsSync() {
245
347
  return { ...sdk._state.tags };
246
348
  },
349
+ // Overrides the device locale the native module reports, and is sent with every register/link
350
+ setLanguage(language) {
351
+ const value = language === null || language === undefined ? '' : String(language).trim().slice(0, 16);
352
+ if (!value) {
353
+ log.warn('User.setLanguage(language) needs a language code — ignoring the call');
354
+ return Promise.resolve();
355
+ }
356
+ return sdk._enqueue(async () => {
357
+ if (sdk._state.language === value) return;
358
+ sdk._state.language = value;
359
+ await sdk._prefsSet(PREFS.language, value);
360
+ if (!sdk._state.subscriptionId) return;
361
+ await sdk._api.setProfile({ subscription_id: sdk._state.subscriptionId, language: value });
362
+ log.info(`language set to "${value}"`);
363
+ });
364
+ },
365
+ async getLanguage() {
366
+ await sdk._ready.catch(() => {});
367
+ return sdk._state.language || sdk._deviceInfo?.language || null;
368
+ },
369
+ addEventListener(event, handler) {
370
+ if (event !== 'change') throw new Error('User supports only the "change" event');
371
+ sdk._events.add('userChange', handler);
372
+ },
373
+ removeEventListener(event, handler) {
374
+ sdk._events.remove('userChange', handler);
375
+ },
247
376
  async getExternalId() {
248
377
  await sdk._ready.catch(() => {});
249
378
  return sdk._state.externalId;
@@ -282,6 +411,16 @@ class PushbibSdk {
282
411
  sdk._events.emit('pushSubscriptionChange', await sdk._subscriptionSnapshot());
283
412
  });
284
413
  },
414
+ // OneSignal's names for the same three reads
415
+ getIdAsync() {
416
+ return sdk.User.pushSubscription.getId();
417
+ },
418
+ getTokenAsync() {
419
+ return sdk.User.pushSubscription.getToken();
420
+ },
421
+ getOptedInAsync() {
422
+ return sdk.User.pushSubscription.getOptedIn();
423
+ },
285
424
  addEventListener(event, handler) {
286
425
  if (event !== 'change') throw new Error('pushSubscription supports only the "change" event');
287
426
  sdk._events.add('pushSubscriptionChange', handler);
@@ -300,12 +439,18 @@ class PushbibSdk {
300
439
  const lat = Number(latitude);
301
440
  const long = Number(longitude);
302
441
  if (!Number.isFinite(lat) || !Number.isFinite(long)) {
303
- throw new Error('Pushbib.Location.setLocation(latitude, longitude) requires two numbers');
442
+ log.warn('Location.setLocation(latitude, longitude) needs two numbers — ignoring the call');
443
+ return Promise.resolve();
304
444
  }
305
445
  if (lat < -90 || lat > 90 || long < -180 || long > 180) {
306
- throw new Error(`Pushbib.Location.setLocation: coordinates out of range (${lat}, ${long})`);
446
+ log.warn(`Location.setLocation: coordinates out of range (${lat}, ${long}) — ignoring the call`);
447
+ return Promise.resolve();
307
448
  }
308
449
  return sdk._enqueue(async () => {
450
+ if (!sdk._state.locationShared) {
451
+ log.info('location collection is off (Location.setShared(false)) — not sending');
452
+ return;
453
+ }
309
454
  sdk._state.location = { lat, long };
310
455
  await sdk._prefsSet(PREFS.location, JSON.stringify(sdk._state.location));
311
456
  if (!sdk._state.subscriptionId) return;
@@ -317,6 +462,44 @@ class PushbibSdk {
317
462
  await sdk._ready.catch(() => {});
318
463
  return sdk._state.location ? { ...sdk._state.location } : null;
319
464
  },
465
+ // OneSignal.Location.setShared(false) stops location collection; here it also stops
466
+ // setLocation() from sending and drops the point from the register payload.
467
+ setShared(shared) {
468
+ const on = !!shared;
469
+ return sdk._enqueue(async () => {
470
+ if (sdk._state.locationShared === on) return;
471
+ sdk._state.locationShared = on;
472
+ await sdk._prefsSet(PREFS.locationShared, on ? null : '0');
473
+ log.info(`location sharing ${on ? 'enabled' : 'disabled'}`);
474
+ if (!on) return;
475
+ if (!sdk._state.location || !sdk._state.subscriptionId) return;
476
+ await sdk._api.setLocation({
477
+ subscription_id: sdk._state.subscriptionId,
478
+ lat: sdk._state.location.lat,
479
+ long: sdk._state.location.long,
480
+ });
481
+ });
482
+ },
483
+ async isShared() {
484
+ await sdk._ready.catch(() => {});
485
+ return sdk._state.locationShared;
486
+ },
487
+ // Asks the OS for location permission. Android only: the SDK links no CoreLocation on iOS,
488
+ // so there an app that wants coordinates asks with its own location library and calls
489
+ // setLocation(). Returns whether permission is granted.
490
+ async requestPermission() {
491
+ if (Platform.OS !== 'android') {
492
+ log.info('Location.requestPermission() is Android-only — ask with your location library on iOS');
493
+ return false;
494
+ }
495
+ try {
496
+ const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
497
+ return result === PermissionsAndroid.RESULTS.GRANTED;
498
+ } catch (e) {
499
+ log.warn('Location.requestPermission failed:', e.message || e);
500
+ return false;
501
+ }
502
+ },
320
503
  clearLocation() {
321
504
  return sdk._enqueue(async () => {
322
505
  sdk._state.location = null;
@@ -335,7 +518,7 @@ class PushbibSdk {
335
518
 
336
519
  _buildLiveActivitiesNamespace() {
337
520
  const sdk = this;
338
- return {
521
+ const ns = {
339
522
  register(options) {
340
523
  const o = options || {};
341
524
  if (!o.activityId && !o.pushToStartToken) {
@@ -401,20 +584,110 @@ class PushbibSdk {
401
584
  sdk._events.remove('liveUpdate', handler);
402
585
  },
403
586
  };
587
+
588
+ // OneSignal's names. They are fire-and-forget there, so these never reject: a failure is
589
+ // logged and resolves to null, which keeps call sites free of try/catch.
590
+ const quiet = (label, promise) =>
591
+ promise.catch((e) => {
592
+ log.warn(`LiveActivities.${label} failed:`, e.message || e);
593
+ return null;
594
+ });
595
+
596
+ ns.enter = (activityId, token, handler) =>
597
+ quiet(
598
+ `enter(${activityId})`,
599
+ ns.register({ activityId, ...(token ? { activityPushToken: token } : {}) }),
600
+ ).then((session) => {
601
+ if (typeof handler === 'function') handler(session);
602
+ return session;
603
+ });
604
+
605
+ ns.exit = (activityId, handler) =>
606
+ quiet(`exit(${activityId})`, ns.end(activityId)).then((result) => {
607
+ if (typeof handler === 'function') handler(result);
608
+ return result;
609
+ });
610
+
611
+ ns.setPushToStartToken = (activityType, token) =>
612
+ quiet(
613
+ `setPushToStartToken(${activityType})`,
614
+ ns.register({ pushToStartToken: token, ...(activityType ? { attributesType: activityType } : {}) }),
615
+ );
616
+
617
+ ns.removePushToStartToken = (activityType) =>
618
+ quiet(
619
+ `removePushToStartToken(${activityType})`,
620
+ sdk._enqueue(async () => {
621
+ if (!sdk._state.subscriptionId) return null;
622
+ const res = await sdk._api.removePushToStart({
623
+ subscription_id: sdk._state.subscriptionId,
624
+ ...(activityType ? { attributes_type: activityType } : {}),
625
+ });
626
+ return res.data;
627
+ }),
628
+ );
629
+
630
+ return ns;
404
631
  }
405
632
 
406
633
  _buildNotificationsNamespace() {
407
634
  const sdk = this;
408
635
  return {
409
- async requestPermission() {
636
+ // fallbackToSettings sends the user to the app's settings page when the OS prompt is
637
+ // spent, which is what OneSignal.Notifications.requestPermission(true) does.
638
+ async requestPermission(fallbackToSettings = false) {
410
639
  if (sdk._options) await sdk._ready.catch(() => {});
640
+ const askedBefore = sdk._state.permissionAsked;
411
641
  const granted = await PushbibNative.requestPermission();
642
+ if (!askedBefore) {
643
+ sdk._state.permissionAsked = true;
644
+ await sdk._prefsSet(PREFS.permissionAsked, '1').catch(() => {});
645
+ }
412
646
  sdk._notifyPermission(granted);
647
+ if (!granted && fallbackToSettings && askedBefore) {
648
+ Linking.openSettings().catch((e) => log.warn('openSettings failed:', e.message || e));
649
+ }
413
650
  return granted;
414
651
  },
415
652
  hasPermission() {
416
653
  return PushbibNative.hasPermission();
417
654
  },
655
+ // OneSignal's name for the same read
656
+ getPermissionAsync() {
657
+ return PushbibNative.hasPermission();
658
+ },
659
+ // True while the OS prompt can still appear — permission is not granted and we never asked.
660
+ async canRequestPermission() {
661
+ if (sdk._options) await sdk._ready.catch(() => {});
662
+ if (await PushbibNative.hasPermission()) return false;
663
+ return !sdk._state.permissionAsked;
664
+ },
665
+ // NotificationPermission enum, like OneSignal's permissionNative()
666
+ async permissionNative() {
667
+ if (typeof PushbibNative.permissionNative === 'function') {
668
+ return PushbibNative.permissionNative();
669
+ }
670
+ if (await PushbibNative.hasPermission()) return NotificationPermission.Authorized;
671
+ if (sdk._options) await sdk._ready.catch(() => {});
672
+ return sdk._state.permissionAsked ? NotificationPermission.Denied : NotificationPermission.NotDetermined;
673
+ },
674
+ // Android only, same as OneSignal. Needs a build with the current native module.
675
+ removeNotification(id) {
676
+ if (Platform.OS !== 'android') return;
677
+ if (typeof PushbibNative.removeNotification !== 'function') {
678
+ log.warn('Notifications.removeNotification needs a rebuild with the current native module');
679
+ return;
680
+ }
681
+ PushbibNative.removeNotification(Number(id));
682
+ },
683
+ removeGroupedNotifications(group) {
684
+ if (Platform.OS !== 'android') return;
685
+ if (typeof PushbibNative.removeGroupedNotifications !== 'function') {
686
+ log.warn('Notifications.removeGroupedNotifications needs a rebuild with the current native module');
687
+ return;
688
+ }
689
+ PushbibNative.removeGroupedNotifications(String(group));
690
+ },
418
691
  clearAll() {
419
692
  PushbibNative.clearAllNotifications();
420
693
  },
@@ -467,15 +740,23 @@ class PushbibSdk {
467
740
  bundleId: this._deviceInfo.bundleId,
468
741
  });
469
742
 
470
- const [sub, ext, opted, tags, location] = await Promise.all([
743
+ const [sub, ext, hash, opted, tags, location, language, locationShared, permissionAsked] = await Promise.all([
471
744
  this._prefsGet(PREFS.subscriptionId),
472
745
  this._prefsGet(PREFS.externalId),
746
+ this._prefsGet(PREFS.identityHash),
473
747
  this._prefsGet(PREFS.optedOut),
474
748
  this._prefsGet(PREFS.tags),
475
749
  this._prefsGet(PREFS.location),
750
+ this._prefsGet(PREFS.language),
751
+ this._prefsGet(PREFS.locationShared),
752
+ this._prefsGet(PREFS.permissionAsked),
476
753
  ]);
754
+ this._state.language = language || null;
755
+ this._state.locationShared = locationShared !== '0';
756
+ this._state.permissionAsked = permissionAsked === '1';
477
757
  this._state.subscriptionId = sub || null;
478
758
  this._state.externalId = ext || null;
759
+ this._state.identityHash = hash || null;
479
760
  this._state.optedOut = opted === '1';
480
761
  try {
481
762
  this._state.tags = tags ? JSON.parse(tags) : {};
@@ -515,10 +796,11 @@ class PushbibSdk {
515
796
  log.warn('No push token available:', e.message || e);
516
797
  }
517
798
 
518
- if (this._state.pushToken && !this._state.optedOut) {
799
+ if (this._state.pushToken) {
800
+ // Registers even while opted out: the device still belongs in the dashboard, listed as
801
+ // unsubscribed, the way an opted-out OneSignal subscription stays on the record. The
802
+ // payload carries subscribed: false, so the server never counts it as a push target.
519
803
  await this._registerWithRetry();
520
- } else if (this._state.optedOut) {
521
- log.info('opted out — skipping registration (User.pushSubscription.optIn() resumes)');
522
804
  }
523
805
 
524
806
  this._lastPermission = await PushbibNative.hasPermission().catch(() => null);
@@ -618,7 +900,8 @@ class PushbibSdk {
618
900
  nativeEmitter.addListener(NATIVE_EVENTS.click, (raw) => this._handleClick(raw));
619
901
 
620
902
  nativeEmitter.addListener(NATIVE_EVENTS.received, (raw) => {
621
- this._events.emit('received', { notification: raw.notification || {} });
903
+ const notification = buildNotification(raw.notification);
904
+ this._events.emit('received', { notification, getNotification: () => notification });
622
905
  });
623
906
 
624
907
  if (Platform.OS === 'android') {
@@ -642,8 +925,13 @@ class PushbibSdk {
642
925
 
643
926
  nativeEmitter.addListener(NATIVE_EVENTS.foregroundWillDisplay, (raw) => {
644
927
  let prevented = false;
928
+ // display() puts the notification back on screen after preventDefault(), as it does on OneSignal
929
+ const notification = buildNotification(raw.notification, () => {
930
+ prevented = false;
931
+ });
645
932
  const delivered = this._events.emit('foregroundWillDisplay', {
646
- notification: raw.notification,
933
+ notification,
934
+ getNotification: () => notification,
647
935
  preventDefault: () => {
648
936
  prevented = true;
649
937
  },
@@ -653,10 +941,10 @@ class PushbibSdk {
653
941
  }
654
942
 
655
943
  _handleClick(raw) {
656
- const notification = raw.notification || {};
944
+ const notification = buildNotification(raw.notification);
657
945
  const actionId = raw.actionId || null;
658
946
  const url = notification.url || null;
659
- this._events.emit('click', { notification, result: { actionId, url } });
947
+ this._events.emit('click', { notification, getNotification: () => notification, result: { actionId, url } });
660
948
  if (url && this._options?.autoOpenLaunchUrls) {
661
949
  Linking.openURL(url).catch((e) => log.warn(`could not open launch URL "${url}": ${e.message}`));
662
950
  }
@@ -673,11 +961,11 @@ class PushbibSdk {
673
961
  const granted = await PushbibNative.hasPermission().catch(() => null);
674
962
  if (granted !== null) this._notifyPermission(granted);
675
963
 
676
- if (this._state.optedOut) return;
677
- if (this._needsRegister || !this._state.registered) {
964
+ if (this._needsRegister || (!this._state.registered && !this._state.optedOut)) {
678
965
  await this._registerWithRetry(1);
679
966
  return;
680
967
  }
968
+ if (this._state.optedOut) return;
681
969
  const now = Date.now();
682
970
  if (this._state.subscriptionId && now - this._lastSessionPingAt > SESSION_PING_MIN_INTERVAL_MS) {
683
971
  this._lastSessionPingAt = now;
@@ -750,8 +1038,10 @@ class PushbibSdk {
750
1038
  device_id: this._deviceId,
751
1039
  ...(this._state.subscriptionId ? { subscription_id: this._state.subscriptionId } : {}),
752
1040
  ...(this._state.externalId ? { external_id: this._state.externalId } : {}),
1041
+ ...this._identity(),
1042
+ ...(this._state.optedOut ? { subscribed: false } : {}),
753
1043
  ...(Object.keys(this._state.tags).length > 0 ? { tags: this._state.tags } : {}),
754
- ...(this._state.location
1044
+ ...(this._state.location && this._state.locationShared
755
1045
  ? { lat: this._state.location.lat, long: this._state.location.long }
756
1046
  : {}),
757
1047
  ...this._deviceHints(),
@@ -759,7 +1049,7 @@ class PushbibSdk {
759
1049
  const res = await this._api.registerDevice(payload);
760
1050
  const previousId = this._state.subscriptionId;
761
1051
  this._state.subscriptionId = res.data.subscription_id;
762
- this._state.registered = true;
1052
+ this._state.registered = !this._state.optedOut;
763
1053
  if (res.data.subscription_id !== previousId) {
764
1054
  await this._prefsSet(PREFS.subscriptionId, res.data.subscription_id);
765
1055
  }
@@ -773,7 +1063,9 @@ class PushbibSdk {
773
1063
  ...(info.model ? { deviceModel: String(info.model).slice(0, 128) } : {}),
774
1064
  ...(info.osVersion ? { deviceOs: `${info.osName || Platform.OS} ${info.osVersion}`.slice(0, 64) } : {}),
775
1065
  ...(info.appVersion ? { appVersion: String(info.appVersion).slice(0, 32) } : {}),
776
- ...(info.language ? { language: String(info.language).slice(0, 16) } : {}),
1066
+ ...(this._state.language || info.language
1067
+ ? { language: String(this._state.language || info.language).slice(0, 16) }
1068
+ : {}),
777
1069
  ...(info.country ? { country: String(info.country).slice(0, 8) } : {}),
778
1070
  ...(info.timezone ? { timezone: String(info.timezone).slice(0, 64) } : {}),
779
1071
  };
@@ -781,10 +1073,16 @@ class PushbibSdk {
781
1073
 
782
1074
  _tagTarget() {
783
1075
  return this._state.externalId
784
- ? { external_id: this._state.externalId }
1076
+ ? { external_id: this._state.externalId, ...this._identity() }
785
1077
  : { subscription_id: this._state.subscriptionId };
786
1078
  }
787
1079
 
1080
+ // Spread into any body that names an external_id. Empty when there is no hash, so an app that
1081
+ // has not turned identity verification on sends exactly what it always sent.
1082
+ _identity() {
1083
+ return this._state.identityHash ? { identity_hash: this._state.identityHash } : {};
1084
+ }
1085
+
788
1086
  async _subscriptionSnapshot() {
789
1087
  return {
790
1088
  id: this._state.subscriptionId,
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const SDK_VERSION = '0.0.2';
1
+ export const SDK_VERSION = '0.1.0';
2
2
  export const SDK_NAME = `pushbib-rn/${SDK_VERSION}`;