@amrshbib/react-native-pushbib 0.0.2 → 0.2.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,51 @@ function tagItems(value) {
41
41
  return [String(value)];
42
42
  }
43
43
 
44
+ // Android carries a notification's data as strings and nothing else, so a nested value —
45
+ // queries: { featureId } — arrives as the JSON text of itself, while iOS carries the real thing.
46
+ // Reading it back here is what lets an app written once see the same shape on both.
47
+ function reviveData(value) {
48
+ if (Array.isArray(value)) return value.map(reviveData);
49
+ if (value && typeof value === 'object') {
50
+ const out = {};
51
+ for (const key of Object.keys(value)) out[key] = reviveData(value[key]);
52
+ return out;
53
+ }
54
+ if (typeof value !== 'string') return value;
55
+
56
+ const text = value.trim();
57
+ const shaped = (text.startsWith('{') && text.endsWith('}'))
58
+ || (text.startsWith('[') && text.endsWith(']'));
59
+ if (!shaped) return value;
60
+ try {
61
+ return reviveData(JSON.parse(text));
62
+ } catch (err) {
63
+ // It only looked like JSON. What the sender wrote is what the app gets.
64
+ return value;
65
+ }
66
+ }
67
+
68
+ // Notification events carry OneSignal's shape as well as Pushbib's own fields: callers can read
69
+ // additionalData / launchURL and call getNotification() and display(), so one handler fits both SDKs.
70
+ function buildNotification(raw, display) {
71
+ const payload = raw || {};
72
+ const data = reviveData(payload.data || {});
73
+ return {
74
+ ...payload,
75
+ notificationId: payload.notificationId ?? null,
76
+ title: payload.title ?? null,
77
+ body: payload.body ?? null,
78
+ launchURL: payload.url ?? null,
79
+ additionalData: data,
80
+ data,
81
+ display: display || (() => {}),
82
+ };
83
+ }
84
+
44
85
  const PREFS = {
45
86
  subscriptionId: 'subscription_id',
46
87
  externalId: 'external_id',
88
+ identityHash: 'identity_hash',
47
89
  optedOut: 'opted_out',
48
90
  tags: 'tags_cache',
49
91
  config: 'config_cache',
@@ -53,6 +95,29 @@ const PREFS = {
53
95
  showForeground: 'show_foreground',
54
96
  showBackground: 'show_background',
55
97
  showLiveUpdate: 'show_live_update',
98
+ language: 'language_override',
99
+ locationShared: 'location_shared',
100
+ permissionAsked: 'permission_asked',
101
+ };
102
+
103
+ // OneSignal's LogLevel enum, so Debug.setLogLevel(LogLevel.Verbose) reads the same on both SDKs.
104
+ export const LogLevel = {
105
+ None: 0,
106
+ Fatal: 1,
107
+ Error: 2,
108
+ Warn: 3,
109
+ Info: 4,
110
+ Debug: 5,
111
+ Verbose: 6,
112
+ };
113
+
114
+ // OneSignal's OSNotificationPermission enum, returned by Notifications.permissionNative().
115
+ export const NotificationPermission = {
116
+ NotDetermined: 0,
117
+ Denied: 1,
118
+ Authorized: 2,
119
+ Provisional: 3,
120
+ Ephemeral: 4,
56
121
  };
57
122
 
58
123
  const SESSION_PING_MIN_INTERVAL_MS = 30 * 1000;
@@ -91,11 +156,18 @@ class PushbibSdk {
91
156
  this._state = {
92
157
  subscriptionId: null,
93
158
  externalId: null,
159
+ // hex(HMAC-SHA256(app secret, externalId)), produced by your own backend. Only needed when
160
+ // the app has identity verification turned on; harmless to send when it does not.
161
+ identityHash: null,
94
162
  pushToken: null,
95
163
  optedOut: false,
96
164
  registered: false,
97
165
  tags: {},
98
166
  location: null,
167
+ // User.setLanguage() wins over the device locale reported by the native module
168
+ language: null,
169
+ locationShared: true,
170
+ permissionAsked: false,
99
171
  };
100
172
  this._needsRegister = false;
101
173
  this._lastSessionPingAt = 0;
@@ -106,6 +178,12 @@ class PushbibSdk {
106
178
  });
107
179
  this._queue = Promise.resolve();
108
180
 
181
+ // Same shape as OneSignal.Debug
182
+ this.Debug = {
183
+ setLogLevel: (level) => setLogLevel(level),
184
+ setAlertLevel: (level) => log.info(`Debug.setAlertLevel(${level}) — Pushbib has no alert log, ignored`),
185
+ };
186
+
109
187
  this.User = this._buildUserNamespace();
110
188
  this.Notifications = this._buildNotificationsNamespace();
111
189
  this.Location = this._buildLocationNamespace();
@@ -134,32 +212,66 @@ class PushbibSdk {
134
212
  this._ready.catch(() => {});
135
213
  }
136
214
 
137
- login(externalId) {
138
- if (typeof externalId !== 'string' || externalId.length === 0) {
139
- throw new Error('Pushbib.login(externalId) requires a non-empty string');
215
+ /**
216
+ * Identify the person using the app.
217
+ *
218
+ * @param {string} externalId your own id for this user
219
+ * @param {string} [identityHash]
220
+ * hex(HMAC-SHA256(secret, externalId)), computed on YOUR SERVER with the signing secret from
221
+ * the app's dashboard, and returned to the app when it signs in.
222
+ *
223
+ * Required when the app has identity verification turned on, and the reason it exists: the
224
+ * app key in this bundle can be read out of the binary by anyone who installs the app, so on
225
+ * its own it proves only that the caller has the app, never which user they are. Without a
226
+ * signature, a request could name anyone's external id and read or rewrite their tags.
227
+ *
228
+ * NEVER ship the signing secret in the app. If the secret is in the bundle, the signature
229
+ * proves nothing, because an attacker can compute it too.
230
+ */
231
+ login(externalId, identityHash) {
232
+ const id = externalId === null || externalId === undefined ? '' : String(externalId);
233
+ if (!id) {
234
+ log.warn('login(externalId) needs a non-empty id — ignoring the call');
235
+ return Promise.resolve();
236
+ }
237
+ let hash = identityHash;
238
+ if (hash !== undefined && hash !== null && typeof hash !== 'string') {
239
+ log.warn('login(externalId, identityHash) — identityHash must be a string; ignoring it');
240
+ hash = null;
140
241
  }
141
242
  return this._enqueue(async () => {
142
- this._state.externalId = externalId;
143
- await this._prefsSet(PREFS.externalId, externalId);
243
+ this._state.externalId = id;
244
+ this._state.identityHash = hash || null;
245
+ await this._prefsSet(PREFS.externalId, id);
246
+ await this._prefsSet(PREFS.identityHash, this._state.identityHash);
247
+ this._events.emit('userChange', { current: { externalId: id, subscriptionId: this._state.subscriptionId } });
144
248
  if (this._state.subscriptionId) {
145
249
  await this._api.link({
146
- external_id: externalId,
250
+ external_id: id,
147
251
  subscription_id: this._state.subscriptionId,
252
+ ...this._identity(),
148
253
  ...this._deviceHints(),
149
254
  });
150
- log.info(`logged in as "${externalId}"`);
255
+ log.info(`logged in as "${id}"`);
151
256
  }
152
257
  });
153
258
  }
154
259
 
155
260
  logout() {
156
261
  return this._enqueue(async () => {
157
- const { externalId, subscriptionId } = this._state;
262
+ const { externalId, subscriptionId, identityHash } = this._state;
158
263
  this._state.externalId = null;
264
+ this._state.identityHash = null;
159
265
  await this._prefsSet(PREFS.externalId, null);
266
+ await this._prefsSet(PREFS.identityHash, null);
267
+ this._events.emit('userChange', { current: { externalId: null, subscriptionId: subscriptionId } });
160
268
  if (externalId && subscriptionId) {
161
269
  await this._api
162
- .unlink({ external_id: externalId, subscription_id: subscriptionId })
270
+ .unlink({
271
+ external_id: externalId,
272
+ subscription_id: subscriptionId,
273
+ ...(identityHash ? { identity_hash: identityHash } : {}),
274
+ })
163
275
  .catch((e) => {
164
276
  if (!(e instanceof ApiError && e.status === 404)) throw e;
165
277
  });
@@ -171,7 +283,10 @@ class PushbibSdk {
171
283
  getMe() {
172
284
  return this._enqueue(async () => {
173
285
  if (!this._state.externalId) throw new Error('getMe() requires login() first');
174
- const res = await this._api.me({ external_id: this._state.externalId });
286
+ const res = await this._api.me({
287
+ external_id: this._state.externalId,
288
+ ...this._identity(),
289
+ });
175
290
  return res.data;
176
291
  });
177
292
  }
@@ -188,7 +303,8 @@ class PushbibSdk {
188
303
  },
189
304
  addTags(tags) {
190
305
  if (!tags || typeof tags !== 'object' || Array.isArray(tags) || Object.keys(tags).length === 0) {
191
- throw new Error('User.addTags requires a non-empty object');
306
+ log.warn('User.addTags needs a non-empty object — ignoring the call');
307
+ return Promise.resolve();
192
308
  }
193
309
  const normalized = {};
194
310
  for (const [k, v] of Object.entries(tags)) {
@@ -196,7 +312,8 @@ class PushbibSdk {
196
312
  if (value !== null) normalized[k] = value;
197
313
  }
198
314
  if (Object.keys(normalized).length === 0) {
199
- throw new Error('User.addTags requires at least one usable value');
315
+ log.warn('User.addTags got no usable value — ignoring the call');
316
+ return Promise.resolve();
200
317
  }
201
318
  return sdk._enqueue(async () => {
202
319
  for (const [k, v] of Object.entries(normalized)) sdk._state.tags[k] = v;
@@ -212,13 +329,15 @@ class PushbibSdk {
212
329
  },
213
330
  removeTag(key, items) {
214
331
  if (typeof key !== 'string' || key.length === 0) {
215
- throw new Error('User.removeTag requires a tag key');
332
+ log.warn('User.removeTag needs a tag key — ignoring the call');
333
+ return Promise.resolve();
216
334
  }
217
335
  if (items === undefined || items === null) return sdk.User.removeTags([key]);
218
336
 
219
337
  const drop = normalizeList(Array.isArray(items) ? items : [items]);
220
338
  if (drop.length === 0) {
221
- throw new Error('User.removeTag requires at least one item to remove');
339
+ log.warn('User.removeTag needs at least one item to remove — ignoring the call');
340
+ return Promise.resolve();
222
341
  }
223
342
  return sdk._enqueue(async () => {
224
343
  const current = sdk._state.tags[key];
@@ -232,18 +351,52 @@ class PushbibSdk {
232
351
  });
233
352
  },
234
353
  removeTags(keys) {
235
- if (!Array.isArray(keys) || keys.length === 0) {
236
- throw new Error('User.removeTags requires a non-empty array of keys');
354
+ const list = Array.isArray(keys) ? keys.filter(Boolean) : keys ? [keys] : [];
355
+ if (list.length === 0) {
356
+ log.warn('User.removeTags needs at least one key — ignoring the call');
357
+ return Promise.resolve();
237
358
  }
238
359
  return sdk._enqueue(async () => {
239
- for (const k of keys) delete sdk._state.tags[k];
360
+ for (const k of list) delete sdk._state.tags[k];
240
361
  await sdk._prefsSet(PREFS.tags, JSON.stringify(sdk._state.tags));
241
- await sdk._api.removeTags({ ...sdk._tagTarget(), tags: keys });
362
+ await sdk._api.removeTags({ ...sdk._tagTarget(), tags: list });
242
363
  });
243
364
  },
244
- getTags() {
365
+ // OneSignal resolves the tags from a promise; getTagsSync() keeps the old synchronous read.
366
+ async getTags() {
367
+ await sdk._ready.catch(() => {});
368
+ return { ...sdk._state.tags };
369
+ },
370
+ getTagsSync() {
245
371
  return { ...sdk._state.tags };
246
372
  },
373
+ // Overrides the device locale the native module reports, and is sent with every register/link
374
+ setLanguage(language) {
375
+ const value = language === null || language === undefined ? '' : String(language).trim().slice(0, 16);
376
+ if (!value) {
377
+ log.warn('User.setLanguage(language) needs a language code — ignoring the call');
378
+ return Promise.resolve();
379
+ }
380
+ return sdk._enqueue(async () => {
381
+ if (sdk._state.language === value) return;
382
+ sdk._state.language = value;
383
+ await sdk._prefsSet(PREFS.language, value);
384
+ if (!sdk._state.subscriptionId) return;
385
+ await sdk._api.setProfile({ subscription_id: sdk._state.subscriptionId, language: value });
386
+ log.info(`language set to "${value}"`);
387
+ });
388
+ },
389
+ async getLanguage() {
390
+ await sdk._ready.catch(() => {});
391
+ return sdk._state.language || sdk._deviceInfo?.language || null;
392
+ },
393
+ addEventListener(event, handler) {
394
+ if (event !== 'change') throw new Error('User supports only the "change" event');
395
+ sdk._events.add('userChange', handler);
396
+ },
397
+ removeEventListener(event, handler) {
398
+ sdk._events.remove('userChange', handler);
399
+ },
247
400
  async getExternalId() {
248
401
  await sdk._ready.catch(() => {});
249
402
  return sdk._state.externalId;
@@ -282,6 +435,16 @@ class PushbibSdk {
282
435
  sdk._events.emit('pushSubscriptionChange', await sdk._subscriptionSnapshot());
283
436
  });
284
437
  },
438
+ // OneSignal's names for the same three reads
439
+ getIdAsync() {
440
+ return sdk.User.pushSubscription.getId();
441
+ },
442
+ getTokenAsync() {
443
+ return sdk.User.pushSubscription.getToken();
444
+ },
445
+ getOptedInAsync() {
446
+ return sdk.User.pushSubscription.getOptedIn();
447
+ },
285
448
  addEventListener(event, handler) {
286
449
  if (event !== 'change') throw new Error('pushSubscription supports only the "change" event');
287
450
  sdk._events.add('pushSubscriptionChange', handler);
@@ -300,12 +463,18 @@ class PushbibSdk {
300
463
  const lat = Number(latitude);
301
464
  const long = Number(longitude);
302
465
  if (!Number.isFinite(lat) || !Number.isFinite(long)) {
303
- throw new Error('Pushbib.Location.setLocation(latitude, longitude) requires two numbers');
466
+ log.warn('Location.setLocation(latitude, longitude) needs two numbers — ignoring the call');
467
+ return Promise.resolve();
304
468
  }
305
469
  if (lat < -90 || lat > 90 || long < -180 || long > 180) {
306
- throw new Error(`Pushbib.Location.setLocation: coordinates out of range (${lat}, ${long})`);
470
+ log.warn(`Location.setLocation: coordinates out of range (${lat}, ${long}) — ignoring the call`);
471
+ return Promise.resolve();
307
472
  }
308
473
  return sdk._enqueue(async () => {
474
+ if (!sdk._state.locationShared) {
475
+ log.info('location collection is off (Location.setShared(false)) — not sending');
476
+ return;
477
+ }
309
478
  sdk._state.location = { lat, long };
310
479
  await sdk._prefsSet(PREFS.location, JSON.stringify(sdk._state.location));
311
480
  if (!sdk._state.subscriptionId) return;
@@ -317,6 +486,44 @@ class PushbibSdk {
317
486
  await sdk._ready.catch(() => {});
318
487
  return sdk._state.location ? { ...sdk._state.location } : null;
319
488
  },
489
+ // OneSignal.Location.setShared(false) stops location collection; here it also stops
490
+ // setLocation() from sending and drops the point from the register payload.
491
+ setShared(shared) {
492
+ const on = !!shared;
493
+ return sdk._enqueue(async () => {
494
+ if (sdk._state.locationShared === on) return;
495
+ sdk._state.locationShared = on;
496
+ await sdk._prefsSet(PREFS.locationShared, on ? null : '0');
497
+ log.info(`location sharing ${on ? 'enabled' : 'disabled'}`);
498
+ if (!on) return;
499
+ if (!sdk._state.location || !sdk._state.subscriptionId) return;
500
+ await sdk._api.setLocation({
501
+ subscription_id: sdk._state.subscriptionId,
502
+ lat: sdk._state.location.lat,
503
+ long: sdk._state.location.long,
504
+ });
505
+ });
506
+ },
507
+ async isShared() {
508
+ await sdk._ready.catch(() => {});
509
+ return sdk._state.locationShared;
510
+ },
511
+ // Asks the OS for location permission. Android only: the SDK links no CoreLocation on iOS,
512
+ // so there an app that wants coordinates asks with its own location library and calls
513
+ // setLocation(). Returns whether permission is granted.
514
+ async requestPermission() {
515
+ if (Platform.OS !== 'android') {
516
+ log.info('Location.requestPermission() is Android-only — ask with your location library on iOS');
517
+ return false;
518
+ }
519
+ try {
520
+ const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
521
+ return result === PermissionsAndroid.RESULTS.GRANTED;
522
+ } catch (e) {
523
+ log.warn('Location.requestPermission failed:', e.message || e);
524
+ return false;
525
+ }
526
+ },
320
527
  clearLocation() {
321
528
  return sdk._enqueue(async () => {
322
529
  sdk._state.location = null;
@@ -335,7 +542,7 @@ class PushbibSdk {
335
542
 
336
543
  _buildLiveActivitiesNamespace() {
337
544
  const sdk = this;
338
- return {
545
+ const ns = {
339
546
  register(options) {
340
547
  const o = options || {};
341
548
  if (!o.activityId && !o.pushToStartToken) {
@@ -401,20 +608,110 @@ class PushbibSdk {
401
608
  sdk._events.remove('liveUpdate', handler);
402
609
  },
403
610
  };
611
+
612
+ // OneSignal's names. They are fire-and-forget there, so these never reject: a failure is
613
+ // logged and resolves to null, which keeps call sites free of try/catch.
614
+ const quiet = (label, promise) =>
615
+ promise.catch((e) => {
616
+ log.warn(`LiveActivities.${label} failed:`, e.message || e);
617
+ return null;
618
+ });
619
+
620
+ ns.enter = (activityId, token, handler) =>
621
+ quiet(
622
+ `enter(${activityId})`,
623
+ ns.register({ activityId, ...(token ? { activityPushToken: token } : {}) }),
624
+ ).then((session) => {
625
+ if (typeof handler === 'function') handler(session);
626
+ return session;
627
+ });
628
+
629
+ ns.exit = (activityId, handler) =>
630
+ quiet(`exit(${activityId})`, ns.end(activityId)).then((result) => {
631
+ if (typeof handler === 'function') handler(result);
632
+ return result;
633
+ });
634
+
635
+ ns.setPushToStartToken = (activityType, token) =>
636
+ quiet(
637
+ `setPushToStartToken(${activityType})`,
638
+ ns.register({ pushToStartToken: token, ...(activityType ? { attributesType: activityType } : {}) }),
639
+ );
640
+
641
+ ns.removePushToStartToken = (activityType) =>
642
+ quiet(
643
+ `removePushToStartToken(${activityType})`,
644
+ sdk._enqueue(async () => {
645
+ if (!sdk._state.subscriptionId) return null;
646
+ const res = await sdk._api.removePushToStart({
647
+ subscription_id: sdk._state.subscriptionId,
648
+ ...(activityType ? { attributes_type: activityType } : {}),
649
+ });
650
+ return res.data;
651
+ }),
652
+ );
653
+
654
+ return ns;
404
655
  }
405
656
 
406
657
  _buildNotificationsNamespace() {
407
658
  const sdk = this;
408
659
  return {
409
- async requestPermission() {
660
+ // fallbackToSettings sends the user to the app's settings page when the OS prompt is
661
+ // spent, which is what OneSignal.Notifications.requestPermission(true) does.
662
+ async requestPermission(fallbackToSettings = false) {
410
663
  if (sdk._options) await sdk._ready.catch(() => {});
664
+ const askedBefore = sdk._state.permissionAsked;
411
665
  const granted = await PushbibNative.requestPermission();
666
+ if (!askedBefore) {
667
+ sdk._state.permissionAsked = true;
668
+ await sdk._prefsSet(PREFS.permissionAsked, '1').catch(() => {});
669
+ }
412
670
  sdk._notifyPermission(granted);
671
+ if (!granted && fallbackToSettings && askedBefore) {
672
+ Linking.openSettings().catch((e) => log.warn('openSettings failed:', e.message || e));
673
+ }
413
674
  return granted;
414
675
  },
415
676
  hasPermission() {
416
677
  return PushbibNative.hasPermission();
417
678
  },
679
+ // OneSignal's name for the same read
680
+ getPermissionAsync() {
681
+ return PushbibNative.hasPermission();
682
+ },
683
+ // True while the OS prompt can still appear — permission is not granted and we never asked.
684
+ async canRequestPermission() {
685
+ if (sdk._options) await sdk._ready.catch(() => {});
686
+ if (await PushbibNative.hasPermission()) return false;
687
+ return !sdk._state.permissionAsked;
688
+ },
689
+ // NotificationPermission enum, like OneSignal's permissionNative()
690
+ async permissionNative() {
691
+ if (typeof PushbibNative.permissionNative === 'function') {
692
+ return PushbibNative.permissionNative();
693
+ }
694
+ if (await PushbibNative.hasPermission()) return NotificationPermission.Authorized;
695
+ if (sdk._options) await sdk._ready.catch(() => {});
696
+ return sdk._state.permissionAsked ? NotificationPermission.Denied : NotificationPermission.NotDetermined;
697
+ },
698
+ // Android only, same as OneSignal. Needs a build with the current native module.
699
+ removeNotification(id) {
700
+ if (Platform.OS !== 'android') return;
701
+ if (typeof PushbibNative.removeNotification !== 'function') {
702
+ log.warn('Notifications.removeNotification needs a rebuild with the current native module');
703
+ return;
704
+ }
705
+ PushbibNative.removeNotification(Number(id));
706
+ },
707
+ removeGroupedNotifications(group) {
708
+ if (Platform.OS !== 'android') return;
709
+ if (typeof PushbibNative.removeGroupedNotifications !== 'function') {
710
+ log.warn('Notifications.removeGroupedNotifications needs a rebuild with the current native module');
711
+ return;
712
+ }
713
+ PushbibNative.removeGroupedNotifications(String(group));
714
+ },
418
715
  clearAll() {
419
716
  PushbibNative.clearAllNotifications();
420
717
  },
@@ -467,15 +764,23 @@ class PushbibSdk {
467
764
  bundleId: this._deviceInfo.bundleId,
468
765
  });
469
766
 
470
- const [sub, ext, opted, tags, location] = await Promise.all([
767
+ const [sub, ext, hash, opted, tags, location, language, locationShared, permissionAsked] = await Promise.all([
471
768
  this._prefsGet(PREFS.subscriptionId),
472
769
  this._prefsGet(PREFS.externalId),
770
+ this._prefsGet(PREFS.identityHash),
473
771
  this._prefsGet(PREFS.optedOut),
474
772
  this._prefsGet(PREFS.tags),
475
773
  this._prefsGet(PREFS.location),
774
+ this._prefsGet(PREFS.language),
775
+ this._prefsGet(PREFS.locationShared),
776
+ this._prefsGet(PREFS.permissionAsked),
476
777
  ]);
778
+ this._state.language = language || null;
779
+ this._state.locationShared = locationShared !== '0';
780
+ this._state.permissionAsked = permissionAsked === '1';
477
781
  this._state.subscriptionId = sub || null;
478
782
  this._state.externalId = ext || null;
783
+ this._state.identityHash = hash || null;
479
784
  this._state.optedOut = opted === '1';
480
785
  try {
481
786
  this._state.tags = tags ? JSON.parse(tags) : {};
@@ -515,10 +820,11 @@ class PushbibSdk {
515
820
  log.warn('No push token available:', e.message || e);
516
821
  }
517
822
 
518
- if (this._state.pushToken && !this._state.optedOut) {
823
+ if (this._state.pushToken) {
824
+ // Registers even while opted out: the device still belongs in the dashboard, listed as
825
+ // unsubscribed, the way an opted-out OneSignal subscription stays on the record. The
826
+ // payload carries subscribed: false, so the server never counts it as a push target.
519
827
  await this._registerWithRetry();
520
- } else if (this._state.optedOut) {
521
- log.info('opted out — skipping registration (User.pushSubscription.optIn() resumes)');
522
828
  }
523
829
 
524
830
  this._lastPermission = await PushbibNative.hasPermission().catch(() => null);
@@ -618,7 +924,8 @@ class PushbibSdk {
618
924
  nativeEmitter.addListener(NATIVE_EVENTS.click, (raw) => this._handleClick(raw));
619
925
 
620
926
  nativeEmitter.addListener(NATIVE_EVENTS.received, (raw) => {
621
- this._events.emit('received', { notification: raw.notification || {} });
927
+ const notification = buildNotification(raw.notification);
928
+ this._events.emit('received', { notification, getNotification: () => notification });
622
929
  });
623
930
 
624
931
  if (Platform.OS === 'android') {
@@ -642,8 +949,13 @@ class PushbibSdk {
642
949
 
643
950
  nativeEmitter.addListener(NATIVE_EVENTS.foregroundWillDisplay, (raw) => {
644
951
  let prevented = false;
952
+ // display() puts the notification back on screen after preventDefault(), as it does on OneSignal
953
+ const notification = buildNotification(raw.notification, () => {
954
+ prevented = false;
955
+ });
645
956
  const delivered = this._events.emit('foregroundWillDisplay', {
646
- notification: raw.notification,
957
+ notification,
958
+ getNotification: () => notification,
647
959
  preventDefault: () => {
648
960
  prevented = true;
649
961
  },
@@ -653,10 +965,10 @@ class PushbibSdk {
653
965
  }
654
966
 
655
967
  _handleClick(raw) {
656
- const notification = raw.notification || {};
968
+ const notification = buildNotification(raw.notification);
657
969
  const actionId = raw.actionId || null;
658
970
  const url = notification.url || null;
659
- this._events.emit('click', { notification, result: { actionId, url } });
971
+ this._events.emit('click', { notification, getNotification: () => notification, result: { actionId, url } });
660
972
  if (url && this._options?.autoOpenLaunchUrls) {
661
973
  Linking.openURL(url).catch((e) => log.warn(`could not open launch URL "${url}": ${e.message}`));
662
974
  }
@@ -673,11 +985,11 @@ class PushbibSdk {
673
985
  const granted = await PushbibNative.hasPermission().catch(() => null);
674
986
  if (granted !== null) this._notifyPermission(granted);
675
987
 
676
- if (this._state.optedOut) return;
677
- if (this._needsRegister || !this._state.registered) {
988
+ if (this._needsRegister || (!this._state.registered && !this._state.optedOut)) {
678
989
  await this._registerWithRetry(1);
679
990
  return;
680
991
  }
992
+ if (this._state.optedOut) return;
681
993
  const now = Date.now();
682
994
  if (this._state.subscriptionId && now - this._lastSessionPingAt > SESSION_PING_MIN_INTERVAL_MS) {
683
995
  this._lastSessionPingAt = now;
@@ -750,8 +1062,10 @@ class PushbibSdk {
750
1062
  device_id: this._deviceId,
751
1063
  ...(this._state.subscriptionId ? { subscription_id: this._state.subscriptionId } : {}),
752
1064
  ...(this._state.externalId ? { external_id: this._state.externalId } : {}),
1065
+ ...this._identity(),
1066
+ ...(this._state.optedOut ? { subscribed: false } : {}),
753
1067
  ...(Object.keys(this._state.tags).length > 0 ? { tags: this._state.tags } : {}),
754
- ...(this._state.location
1068
+ ...(this._state.location && this._state.locationShared
755
1069
  ? { lat: this._state.location.lat, long: this._state.location.long }
756
1070
  : {}),
757
1071
  ...this._deviceHints(),
@@ -759,7 +1073,7 @@ class PushbibSdk {
759
1073
  const res = await this._api.registerDevice(payload);
760
1074
  const previousId = this._state.subscriptionId;
761
1075
  this._state.subscriptionId = res.data.subscription_id;
762
- this._state.registered = true;
1076
+ this._state.registered = !this._state.optedOut;
763
1077
  if (res.data.subscription_id !== previousId) {
764
1078
  await this._prefsSet(PREFS.subscriptionId, res.data.subscription_id);
765
1079
  }
@@ -773,7 +1087,9 @@ class PushbibSdk {
773
1087
  ...(info.model ? { deviceModel: String(info.model).slice(0, 128) } : {}),
774
1088
  ...(info.osVersion ? { deviceOs: `${info.osName || Platform.OS} ${info.osVersion}`.slice(0, 64) } : {}),
775
1089
  ...(info.appVersion ? { appVersion: String(info.appVersion).slice(0, 32) } : {}),
776
- ...(info.language ? { language: String(info.language).slice(0, 16) } : {}),
1090
+ ...(this._state.language || info.language
1091
+ ? { language: String(this._state.language || info.language).slice(0, 16) }
1092
+ : {}),
777
1093
  ...(info.country ? { country: String(info.country).slice(0, 8) } : {}),
778
1094
  ...(info.timezone ? { timezone: String(info.timezone).slice(0, 64) } : {}),
779
1095
  };
@@ -781,10 +1097,16 @@ class PushbibSdk {
781
1097
 
782
1098
  _tagTarget() {
783
1099
  return this._state.externalId
784
- ? { external_id: this._state.externalId }
1100
+ ? { external_id: this._state.externalId, ...this._identity() }
785
1101
  : { subscription_id: this._state.subscriptionId };
786
1102
  }
787
1103
 
1104
+ // Spread into any body that names an external_id. Empty when there is no hash, so an app that
1105
+ // has not turned identity verification on sends exactly what it always sent.
1106
+ _identity() {
1107
+ return this._state.identityHash ? { identity_hash: this._state.identityHash } : {};
1108
+ }
1109
+
788
1110
  async _subscriptionSnapshot() {
789
1111
  return {
790
1112
  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.2.0';
2
2
  export const SDK_NAME = `pushbib-rn/${SDK_VERSION}`;