@amrshbib/react-native-pushbib 0.2.0 → 0.4.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/README.md CHANGED
@@ -429,6 +429,36 @@ const sessions = await Pushbib.LiveActivities.getSessions();
429
429
  // [{ activity_id, status, activity_token_registered, last_sequence_number, … }]
430
430
  ```
431
431
 
432
+ ## VoIP pushes — ring like a call
433
+
434
+ `POST /api/server/v1/voip/send` (server key) with `{ subscription_ids, data, ttl }` rings the
435
+ phone: a PushKit VoIP push on iOS, a high-priority data-only FCM message on Android. The SDK never
436
+ shows these — the call screen is the app's own (CallKit on iOS, a call-style notification on
437
+ Android). `data` values are strings; they reach the app as they were sent.
438
+
439
+ **iOS.** Add `voip` to `UIBackgroundModes`, register a `PKPushRegistry` in native code at launch,
440
+ and give the SDK its token:
441
+
442
+ ```js
443
+ Pushbib.VoIP.setToken(hexToken); // re-sent by itself when the device gets a new subscription
444
+ Pushbib.VoIP.clearToken(); // stop ringing this device
445
+ ```
446
+
447
+ Every VoIP push must be reported to CallKit (`reportNewIncomingCall`) before the PushKit callback
448
+ returns — iOS stops delivering VoIP pushes to an app that doesn't. The payload is the `data` you
449
+ sent plus `pushbib_voip: "1"`.
450
+
451
+ **Android.** Nothing to register: the SDK hands the message to your app as a broadcast to its own
452
+ package, which a manifest receiver gets even when the app is not running:
453
+
454
+ ```xml
455
+ <receiver android:name=".IncomingCallReceiver" android:exported="false">
456
+ <intent-filter><action android:name="com.amrshbib.pushbib.VOIP_PUSH" /></intent-filter>
457
+ </receiver>
458
+ ```
459
+
460
+ Each `data` key arrives as a string extra on the intent.
461
+
432
462
  ## Android customization (optional)
433
463
 
434
464
  `AndroidManifest.xml` meta-data, all optional:
@@ -534,6 +564,34 @@ on the dashboard's device list as **unsubscribed** — with its token, tags, lan
534
564
  count intact — so it reappears the moment `optIn()` is called. Only an explicit delete in the
535
565
  dashboard removes a device.
536
566
 
567
+ A received or clicked notification carries OneSignal's field names as well as Pushbib's own,
568
+ so one handler reads either SDK's event with no branch per provider:
569
+
570
+ | OneSignal | Pushbib's own name |
571
+ | --- | --- |
572
+ | `additionalData` | `data` |
573
+ | `launchURL` | `url` |
574
+ | `actionButtons` | `buttons` |
575
+ | `bigPicture` | `imageUrl` |
576
+ | `groupKey` | `collapseId` |
577
+ | `rawPayload` | the native payload as delivered |
578
+
579
+ `additionalData` arrives with the shape it was sent, exactly as OneSignal's does — a nested
580
+ object, a number or a boolean comes back as one, and a string the sender wrote stays a string
581
+ even when it holds JSON text:
582
+
583
+ ```js
584
+ // sent as { type: 'Messaging', queries: { featureId: 205 }, orderData: '{"Status":{"Id":3}}' }
585
+ Pushbib.Notifications.addEventListener('click', (e) => {
586
+ const { featureId } = e.notification.additionalData.queries; // 205, a number
587
+ JSON.parse(e.notification.additionalData.orderData); // still the string the sender wrote
588
+ });
589
+ ```
590
+
591
+ FCM's data map carries strings and nothing else, so the server sends the whole thing as one
592
+ JSON string and the SDK reads it back — the same trick OneSignal plays with `custom`. Nothing
593
+ about it is visible from JS.
594
+
537
595
  Two deliberate differences:
538
596
 
539
597
  - **Nothing throws on empty or odd input.** `addTags({})`, `removeTags([])`, `login('')`,
@@ -18,7 +18,7 @@ class NotificationPayload private constructor(
18
18
  val collapseId: String?,
19
19
  val url: String?,
20
20
  val buttons: List<Button>,
21
- val data: Map<String, String>,
21
+ val data: JSONObject,
22
22
  val notificationId: Int,
23
23
  val showForeground: Boolean,
24
24
  val showBackground: Boolean,
@@ -42,13 +42,10 @@ class NotificationPayload private constructor(
42
42
  putOpt("collapseId", collapseId)
43
43
  putOpt("url", url)
44
44
  put("buttons", JSONArray().apply { buttons.forEach { put(JSONObject().put("id", it.id).put("text", it.text)) } })
45
- put("data", JSONObject(data as Map<*, *>))
45
+ put("data", data)
46
46
  }
47
47
 
48
48
  companion object {
49
- private val CONTROL_KEYS =
50
- setOf("pushbib_payload", "url", "buttons", "largeIcon", "showForeground", "showBackground")
51
-
52
49
  private fun flag(raw: String?, default: Boolean = true): Boolean =
53
50
  when (raw?.trim()?.lowercase()) {
54
51
  null, "" -> default
@@ -62,8 +59,12 @@ class NotificationPayload private constructor(
62
59
  val notif = message.notification
63
60
  if (display == null && notif == null) return null
64
61
 
65
- val custom = HashMap<String, String>()
66
- for ((k, v) in data) if (k !in CONTROL_KEYS) custom[k] = v
62
+ /* The data map FCM delivers holds strings and nothing else, so what the sender
63
+ * wrote — a nested object, a number, a flag — travels whole as JSON under one
64
+ * key. Reading that back is what hands the app the shape it was sent. */
65
+ val custom = data["pushbib_data"]
66
+ ?.let { runCatching { JSONObject(it) }.getOrNull() }
67
+ ?: JSONObject()
67
68
 
68
69
  return NotificationPayload(
69
70
  title = display?.optNonEmpty("title") ?: notif?.title,
@@ -100,11 +101,7 @@ class NotificationPayload private constructor(
100
101
  collapseId = json.optNonEmpty("collapseId"),
101
102
  url = json.optNonEmpty("url"),
102
103
  buttons = parseButtons(json.optJSONArray("buttons")),
103
- data = json.optJSONObject("data")?.let { obj ->
104
- val out = HashMap<String, String>()
105
- obj.keys().forEach { k -> out[k] = obj.optString(k) }
106
- out
107
- } ?: emptyMap(),
104
+ data = json.optJSONObject("data") ?: JSONObject(),
108
105
  notificationId = json.optInt("notificationId", (System.currentTimeMillis() and 0x7FFFFFFF).toInt()),
109
106
  showForeground = json.optBoolean("showForeground", true),
110
107
  showBackground = json.optBoolean("showBackground", true),
@@ -9,6 +9,11 @@ import org.json.JSONObject
9
9
  class PushbibMessagingService : FirebaseMessagingService() {
10
10
 
11
11
  override fun onMessageReceived(message: RemoteMessage) {
12
+ if (VoipPush.isVoip(message)) {
13
+ VoipPush.forward(applicationContext, message)
14
+ return
15
+ }
16
+
12
17
  if (LiveUpdatePayload.isLiveUpdate(message)) {
13
18
  handleLiveUpdate(message)
14
19
  return
@@ -0,0 +1,32 @@
1
+ package com.amrshbib.pushbib
2
+
3
+ import android.content.Context
4
+ import android.content.Intent
5
+ import com.google.firebase.messaging.RemoteMessage
6
+
7
+ /**
8
+ * A VoIP push (`POST /api/server/v1/voip/send`): a high-priority, data-only FCM message marked
9
+ * `pushbib_voip = "1"`. The SDK never renders it — ringing is the app's own job — so it is handed
10
+ * to the app as a broadcast to its own package, which a manifest receiver gets even when the app
11
+ * is not running:
12
+ *
13
+ * <receiver android:name=".IncomingCallReceiver" android:exported="false">
14
+ * <intent-filter><action android:name="com.amrshbib.pushbib.VOIP_PUSH" /></intent-filter>
15
+ * </receiver>
16
+ *
17
+ * Every data key but the marker comes as a string extra.
18
+ */
19
+ object VoipPush {
20
+ const val ACTION = "com.amrshbib.pushbib.VOIP_PUSH"
21
+ private const val MARKER = "pushbib_voip"
22
+
23
+ fun isVoip(message: RemoteMessage): Boolean = message.data[MARKER] == "1"
24
+
25
+ fun forward(context: Context, message: RemoteMessage) {
26
+ val intent = Intent(ACTION).setPackage(context.packageName)
27
+ for ((key, value) in message.data) {
28
+ if (key != MARKER) intent.putExtra(key, value)
29
+ }
30
+ context.sendBroadcast(intent)
31
+ }
32
+ }
package/index.d.ts CHANGED
@@ -37,7 +37,7 @@ export interface NotificationButton {
37
37
 
38
38
  export interface PushbibNotification {
39
39
  /** OneSignal's name for `data`. */
40
- additionalData: Record<string, string>;
40
+ additionalData: Record<string, unknown>;
41
41
  /** OneSignal's name for `url`. */
42
42
  launchURL?: string | null;
43
43
  /** Puts the notification back on screen after preventDefault(); a no-op otherwise. */
@@ -51,7 +51,16 @@ export interface PushbibNotification {
51
51
  largeIcon?: string;
52
52
  url?: string;
53
53
  buttons?: NotificationButton[];
54
- data: Record<string, string>;
54
+ /** What the sender wrote, with its shape: a nested object, a number or a flag arrives as one. */
55
+ data: Record<string, unknown>;
56
+ /** OneSignal's name for `buttons`. */
57
+ actionButtons: NotificationButton[];
58
+ /** OneSignal's name for `imageUrl`. */
59
+ bigPicture: string | null;
60
+ /** OneSignal's name for `collapseId`. */
61
+ groupKey: string | null;
62
+ /** Everything the native side delivered, before the OneSignal names were added. */
63
+ rawPayload: Record<string, unknown>;
55
64
  }
56
65
 
57
66
  export interface NotificationClickEvent {
@@ -284,6 +293,17 @@ export interface ChannelsNamespace {
284
293
  openSettings(key?: string): Promise<boolean>;
285
294
  }
286
295
 
296
+ /**
297
+ * VoIP pushes (the server's `POST /api/server/v1/voip/send`) ring the phone like a call; the SDK
298
+ * never shows them. iOS: hand the PushKit token over with setToken (and report every VoIP push to
299
+ * CallKit at once). Android: the FCM token rings — the message comes to the app's
300
+ * `com.amrshbib.pushbib.VOIP_PUSH` broadcast receiver. Both never reject (null on failure).
301
+ */
302
+ export interface VoipNamespace {
303
+ setToken(token: string): Promise<{ subscription_id: string; voip_registered: boolean } | null>;
304
+ clearToken(): Promise<unknown>;
305
+ }
306
+
287
307
  export interface PushbibStatic {
288
308
  initialize(options: InitializeOptions): void;
289
309
  /**
@@ -312,6 +332,7 @@ export interface PushbibStatic {
312
332
  Location: LocationNamespace;
313
333
  LiveActivities: LiveActivitiesNamespace;
314
334
  Channels: ChannelsNamespace;
335
+ VoIP: VoipNamespace;
315
336
  }
316
337
 
317
338
  declare const Pushbib: PushbibStatic;
@@ -112,17 +112,33 @@ static BOOL PushbibFlag(NSDictionary *userInfo, NSString *key, BOOL fallback) {
112
112
 
113
113
  + (NSDictionary *)normalizeContent:(UNNotificationContent *)content {
114
114
  NSDictionary *userInfo = content.userInfo ?: @{};
115
- NSSet *controlKeys = [NSSet setWithArray:@[
116
- @"aps", @"url", @"imageUrl", @"largeIcon", @"buttons", @"pushbib_payload",
117
- @"showForeground", @"showBackground"
118
- ]];
119
-
120
- NSMutableDictionary *data = [NSMutableDictionary new];
121
- for (NSString *key in userInfo) {
122
- if (![key isKindOfClass:NSString.class]) continue;
123
- if ([controlKeys containsObject:key]) continue;
124
- if ([key hasPrefix:@"gcm."] || [key hasPrefix:@"google."]) continue;
125
- data[key] = userInfo[key];
115
+ /* The same message is built for a transport whose data map holds strings and nothing
116
+ * else, so what the sender wrote travels whole as JSON under one key. Reading that
117
+ * back is what hands the app the shape it was sent — a nested object, a number, a
118
+ * flag. A push written straight to APNs carries it as real JSON already. */
119
+ NSDictionary *data = @{};
120
+ id blob = userInfo[@"pushbib_data"];
121
+ if ([blob isKindOfClass:NSString.class]) {
122
+ NSData *raw = [(NSString *)blob dataUsingEncoding:NSUTF8StringEncoding];
123
+ id parsed = raw ? [NSJSONSerialization JSONObjectWithData:raw options:0 error:NULL] : nil;
124
+ if ([parsed isKindOfClass:NSDictionary.class]) data = parsed;
125
+ } else if ([blob isKindOfClass:NSDictionary.class]) {
126
+ data = blob;
127
+ } else if (blob == nil) {
128
+ /* A legacy (raw APNs token) send writes `data` straight into the payload, next to `aps`
129
+ * (services/push/apns.service.js on the server), so there is no pushbib_data to read.
130
+ * Everything at the top level that is not APNs' own or a field read below is the data. */
131
+ NSMutableDictionary *loose = [NSMutableDictionary new];
132
+ for (id key in userInfo) {
133
+ if (![key isKindOfClass:NSString.class]) continue;
134
+ NSString *name = (NSString *)key;
135
+ if ([name isEqualToString:@"aps"] || [name isEqualToString:@"url"] || [name isEqualToString:@"imageUrl"] ||
136
+ [name hasPrefix:@"gcm."] || [name hasPrefix:@"google."] || [name hasPrefix:@"pushbib_"]) {
137
+ continue;
138
+ }
139
+ loose[name] = userInfo[key];
140
+ }
141
+ data = loose;
126
142
  }
127
143
 
128
144
  NSMutableDictionary *notification = [NSMutableDictionary new];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amrshbib/react-native-pushbib",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Self-hosted push notification SDK for React Native. Pushbib-style API (login, tags, click events) with zero Firebase setup in the app \u2014 no google-services.json, no GoogleService-Info.plist.",
5
5
  "main": "src/index.js",
6
6
  "types": "index.d.ts",
package/src/api.js CHANGED
@@ -111,4 +111,11 @@ export class ApiClient {
111
111
  liveActivitySessions(subscriptionId) {
112
112
  return this.get(`/live-activity/sessions?subscription_id=${encodeURIComponent(subscriptionId)}`);
113
113
  }
114
+
115
+ registerVoip(payload) {
116
+ return this.post('/voip/register', payload);
117
+ }
118
+ removeVoip(payload) {
119
+ return this.delete('/voip', payload);
120
+ }
114
121
  }
package/src/index.js CHANGED
@@ -41,35 +41,12 @@ 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
44
  // Notification events carry OneSignal's shape as well as Pushbib's own fields: callers can read
69
45
  // additionalData / launchURL and call getNotification() and display(), so one handler fits both SDKs.
70
46
  function buildNotification(raw, display) {
71
47
  const payload = raw || {};
72
- const data = reviveData(payload.data || {});
48
+ const data = payload.data || {};
49
+ const buttons = Array.isArray(payload.buttons) ? payload.buttons : [];
73
50
  return {
74
51
  ...payload,
75
52
  notificationId: payload.notificationId ?? null,
@@ -78,10 +55,19 @@ function buildNotification(raw, display) {
78
55
  launchURL: payload.url ?? null,
79
56
  additionalData: data,
80
57
  data,
58
+ // OneSignal's names for things Pushbib calls something else, so a handler written
59
+ // against it reads straight across without a branch per provider.
60
+ actionButtons: buttons,
61
+ bigPicture: payload.imageUrl ?? null,
62
+ groupKey: payload.collapseId ?? null,
63
+ rawPayload: payload,
81
64
  display: display || (() => {}),
82
65
  };
83
66
  }
84
67
 
68
+ // A PushKit token: 32 bytes today, as hex
69
+ const VOIP_TOKEN = /^[0-9a-f]{64,200}$/i;
70
+
85
71
  const PREFS = {
86
72
  subscriptionId: 'subscription_id',
87
73
  externalId: 'external_id',
@@ -168,6 +154,8 @@ class PushbibSdk {
168
154
  language: null,
169
155
  locationShared: true,
170
156
  permissionAsked: false,
157
+ // iOS: the PushKit token VoIP pushes ring through (VoIP.setToken); never stored, the app gives it each launch
158
+ voipToken: null,
171
159
  };
172
160
  this._needsRegister = false;
173
161
  this._lastSessionPingAt = 0;
@@ -189,6 +177,7 @@ class PushbibSdk {
189
177
  this.Location = this._buildLocationNamespace();
190
178
  this.LiveActivities = this._buildLiveActivitiesNamespace();
191
179
  this.Channels = this._buildChannelsNamespace();
180
+ this.VoIP = this._buildVoipNamespace();
192
181
  }
193
182
 
194
183
  initialize(options) {
@@ -654,6 +643,59 @@ class PushbibSdk {
654
643
  return ns;
655
644
  }
656
645
 
646
+ /**
647
+ * VoIP pushes (`POST /api/server/v1/voip/send` on the server) ring the phone like a call; the SDK
648
+ * never shows them. iOS rings through its own PushKit token, which the app's PushKit delegate
649
+ * hands over with setToken (and the app must report every VoIP push to CallKit right away).
650
+ * Android rings through the normal FCM token: the SDK passes the message to the app's
651
+ * `com.amrshbib.pushbib.VOIP_PUSH` receiver (VoipPush.kt), so nothing is needed here.
652
+ *
653
+ * Both never reject: a failure is logged and resolves to null. The token is sent again whenever
654
+ * the device gets a new subscription.
655
+ */
656
+ _buildVoipNamespace() {
657
+ const sdk = this;
658
+ const quiet = (label, promise) =>
659
+ promise.catch((e) => {
660
+ log.warn(`VoIP.${label} failed:`, e.message || e);
661
+ return null;
662
+ });
663
+ return {
664
+ setToken(token) {
665
+ const value = typeof token === 'string' ? token.trim() : '';
666
+ if (!VOIP_TOKEN.test(value)) {
667
+ log.warn('VoIP.setToken needs the PushKit token as a hex string — ignored');
668
+ return Promise.resolve(null);
669
+ }
670
+ sdk._state.voipToken = value;
671
+ return quiet('setToken', sdk._sendVoipToken());
672
+ },
673
+ clearToken() {
674
+ sdk._state.voipToken = null;
675
+ return quiet('clearToken', sdk._sendVoipToken());
676
+ },
677
+ };
678
+ }
679
+
680
+ // The VoIP token as it is now (none = remove it), for the current subscription.
681
+ _sendVoipToken() {
682
+ return this._enqueue(async () => {
683
+ const subscriptionId = this._state.subscriptionId;
684
+ if (!subscriptionId) return null;
685
+ const token = this._state.voipToken;
686
+ if (token) {
687
+ const res = await this._api.registerVoip({ subscription_id: subscriptionId, token });
688
+ log.info('VoIP token registered');
689
+ return res.data;
690
+ }
691
+ const res = await this._api.removeVoip({ subscription_id: subscriptionId }).catch((e) => {
692
+ if (e instanceof ApiError && e.status === 404) return { data: null };
693
+ throw e;
694
+ });
695
+ return res.data;
696
+ });
697
+ }
698
+
657
699
  _buildNotificationsNamespace() {
658
700
  const sdk = this;
659
701
  return {
@@ -1076,6 +1118,9 @@ class PushbibSdk {
1076
1118
  this._state.registered = !this._state.optedOut;
1077
1119
  if (res.data.subscription_id !== previousId) {
1078
1120
  await this._prefsSet(PREFS.subscriptionId, res.data.subscription_id);
1121
+ if (this._state.voipToken) {
1122
+ this._sendVoipToken().catch((e) => log.warn('VoIP token not sent again:', e.message || e));
1123
+ }
1079
1124
  }
1080
1125
  log.info(`registered (subscription ${res.data.subscription_id})`);
1081
1126
  this._events.emit('pushSubscriptionChange', await this._subscriptionSnapshot());
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const SDK_VERSION = '0.2.0';
1
+ export const SDK_VERSION = '0.4.0';
2
2
  export const SDK_NAME = `pushbib-rn/${SDK_VERSION}`;