@amrshbib/react-native-pushbib 0.0.1

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.
Files changed (31) hide show
  1. package/README.md +475 -0
  2. package/android/build.gradle +51 -0
  3. package/android/src/main/AndroidManifest.xml +15 -0
  4. package/android/src/main/java/com/amrshbib/pushbib/FirebaseBootstrap.kt +37 -0
  5. package/android/src/main/java/com/amrshbib/pushbib/LiveUpdatePayload.kt +102 -0
  6. package/android/src/main/java/com/amrshbib/pushbib/LiveUpdateRenderer.kt +294 -0
  7. package/android/src/main/java/com/amrshbib/pushbib/NotificationPayload.kt +130 -0
  8. package/android/src/main/java/com/amrshbib/pushbib/NotificationRenderer.kt +181 -0
  9. package/android/src/main/java/com/amrshbib/pushbib/PushbibChannels.kt +281 -0
  10. package/android/src/main/java/com/amrshbib/pushbib/PushbibEmitter.kt +133 -0
  11. package/android/src/main/java/com/amrshbib/pushbib/PushbibMessagingService.kt +87 -0
  12. package/android/src/main/java/com/amrshbib/pushbib/PushbibModule.kt +286 -0
  13. package/android/src/main/java/com/amrshbib/pushbib/PushbibPackage.kt +14 -0
  14. package/index.d.ts +224 -0
  15. package/ios/PushbibCenterDelegate.h +16 -0
  16. package/ios/PushbibCenterDelegate.m +138 -0
  17. package/ios/PushbibEventBus.h +34 -0
  18. package/ios/PushbibEventBus.m +88 -0
  19. package/ios/PushbibLiveActivities.h +18 -0
  20. package/ios/PushbibLiveActivities.m +46 -0
  21. package/ios/PushbibModule.h +5 -0
  22. package/ios/PushbibModule.m +260 -0
  23. package/ios/PushbibSwizzler.m +135 -0
  24. package/package.json +40 -0
  25. package/react-native-pushbib.podspec +19 -0
  26. package/src/EventManager.js +55 -0
  27. package/src/Logger.js +18 -0
  28. package/src/NativePushbib.js +36 -0
  29. package/src/api.js +108 -0
  30. package/src/index.js +753 -0
  31. package/src/version.js +2 -0
package/README.md ADDED
@@ -0,0 +1,475 @@
1
+ # @amrshbib/react-native-pushbib
2
+
3
+ Self-hosted push notifications for React Native — three lines of setup and
4
+ **zero Firebase configuration inside your app**:
5
+
6
+ - ❌ no `google-services.json`
7
+ - ❌ no `GoogleService-Info.plist`
8
+ - ❌ no google-services gradle plugin
9
+ - ❌ no Firebase pods on iOS (pure APNs)
10
+ - ❌ no AppDelegate / MainApplication changes
11
+
12
+ ```js
13
+ import Pushbib from '@amrshbib/react-native-pushbib';
14
+
15
+ Pushbib.initialize({
16
+ baseUrl: 'https://push.your-server.com',
17
+ appId: 'PROJECT_ID', // Dashboard → App Settings
18
+ appKey: 'nk_xxxxxxxx', // Dashboard → App Settings → Secure Keys (kind: mobile)
19
+ });
20
+
21
+ Pushbib.Notifications.requestPermission();
22
+ Pushbib.login('user-42');
23
+ Pushbib.User.addTags({ plan: 'pro', city: 'DXB' });
24
+
25
+ Pushbib.Notifications.addEventListener('click', (e) => {
26
+ console.log('clicked', e.notification, e.result.actionId, e.result.url);
27
+ });
28
+ ```
29
+
30
+ ## How it works
31
+
32
+ - **Android** — the SDK bundles `firebase-messaging` internally and calls
33
+ `FirebaseApp.initializeApp(context, options)` **at runtime** with client
34
+ options fetched from your server (`GET /api/mobile/v1/config`). Those
35
+ options are read straight out of Firebase by your server using the
36
+ service-account JSON — no `google-services.json` anywhere, not in the app
37
+ and not in the dashboard.
38
+ The backend sends **data-only** messages to SDK devices and the SDK renders
39
+ every notification natively — which is what makes action buttons, images,
40
+ foreground control and consistent click handling work.
41
+ - **iOS** — no Firebase at all. The SDK registers directly with APNs, sends
42
+ the raw hex device token to your server, and the server delivers over
43
+ HTTP/2 APNs with the `.p8` key you uploaded in the dashboard. AppDelegate
44
+ callbacks and the `UNUserNotificationCenter` delegate are hooked by
45
+ runtime swizzling (installed before `didFinishLaunching`, forwarding to any
46
+ handler your app installs) — which is also why the iOS bridge is
47
+ Objective-C: swizzling needs `+load` and the ObjC runtime.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ npm install @amrshbib/react-native-pushbib
53
+ # or from the monorepo:
54
+ npm install file:../RNPackages/@amrshbib/react-native-pushbib
55
+
56
+ cd ios && pod install
57
+ ```
58
+
59
+ > Full guide with diagrams: [`Docs/MOBILE-SDK.md`](../../../Docs/MOBILE-SDK.md)
60
+
61
+ Autolinking does the rest. **Requirements:** React Native ≥ 0.71 (old + new
62
+ architecture via interop), Android minSdk 24, iOS 13+.
63
+
64
+ ### One-time dashboard setup (per app)
65
+
66
+ 1. **FCM service account** (sending, Android): App Settings → upload the
67
+ service-account JSON.
68
+ 2. **Android client config**: App Settings → "Detect from service account".
69
+ The server reads the client identifiers from Firebase itself.
70
+ 3. **APNs key** (sending, iOS): App Settings → upload the `.p8` key with Key
71
+ ID / Team ID / Bundle ID.
72
+ 4. Create a **mobile Secure Key** (optionally locked to your bundle ids) —
73
+ that's the `appKey`.
74
+
75
+ ### The only platform config you can't avoid
76
+
77
+ - **iOS**: enable the *Push Notifications* capability (Xcode → Signing &
78
+ Capabilities). That's an entitlement Apple requires per app; no SDK can
79
+ inject it. Recommended: also enable *Background Modes → Remote
80
+ notifications*.
81
+ - **Android**: nothing.
82
+
83
+ ## API
84
+
85
+ | Call | What it does |
86
+ | --- | --- |
87
+ | `Pushbib.initialize(opts)` | Boot the SDK: fetch config, mint the push token, register the device. All other calls queue behind it. |
88
+ | `Pushbib.login(externalId)` | Bind this install to your user id (`/auth/link`). Survives token rotation. |
89
+ | `Pushbib.logout()` | Unbind (`/auth/unlink`). |
90
+ | `Pushbib.getMe()` | Server-side view of the logged-in user (all subscriptions + tags). |
91
+ | `Pushbib.User.addTag(k, v)` / `addTags({...})` | Merge tags (user-level when logged in, else this install). |
92
+ | `Pushbib.User.removeTag(k)` / `removeTags([k])` | Delete tag keys. |
93
+ | `Pushbib.User.getTags()` | Local cache of tags set through this install. |
94
+ | `Pushbib.User.getExternalId()` | Current external id (or null). |
95
+ | `Pushbib.User.pushSubscription.getId()` | Stable subscription id (treat as a secret). |
96
+ | `Pushbib.User.pushSubscription.getToken()` | Raw push token (FCM registration token / APNs hex). |
97
+ | `Pushbib.User.pushSubscription.optOut()` / `optIn()` | Server-side unsubscribe / resubscribe. |
98
+ | `Pushbib.Location.setLocation(lat, long)` | Report coordinates for radius targeting. Shown as "Location point" on the user record. |
99
+ | `Pushbib.Location.getLocation()` | Last coordinates reported from this install (or null). |
100
+ | `Pushbib.Location.clearLocation()` | Forget them — the device stops matching radius segments. |
101
+ | `Pushbib.Notifications.requestPermission()` | OS prompt (iOS, Android 13+). Resolves granted. |
102
+ | `Pushbib.Notifications.hasPermission()` | Current permission state. |
103
+ | `Pushbib.Notifications.clearAll()` | Clear delivered notifications (+ badge on iOS). |
104
+ | `Pushbib.Notifications.setForegroundDisplayEnabled(bool)` / `getForegroundDisplayEnabled()` | Device-local toggle: show pushes while the app is open. Default: true. |
105
+ | `Pushbib.Notifications.setBackgroundDisplayEnabled(bool)` / `getBackgroundDisplayEnabled()` | Device-local toggle: show pushes while the app is backgrounded (Android only). Default: true. |
106
+ | `Pushbib.Channels.sync()` | Re-read the app's channels from `/config` and apply them. Runs on start already. |
107
+ | `Pushbib.Channels.list()` | Channels on this phone with their live importance and a `blocked` flag (Android only). |
108
+ | `Pushbib.Channels.definitions()` | What the server last sent, from the local cache. |
109
+ | `Pushbib.Channels.openSettings(key)` | Open the OS settings screen for one channel. |
110
+ | `Pushbib.setLogLevel('verbose')` | none / error / warn / info / verbose. |
111
+
112
+ ### Location & radius targeting
113
+
114
+ Report where the device is and the dashboard can target it by radius —
115
+ "everyone within 5 km of the store". The coordinates land on the user record as
116
+ **Location point** (Audience → Users), and the segment builder gets a
117
+ **Location → is within radius of** filter taking latitude, longitude and a
118
+ radius in **metres**.
119
+
120
+ The SDK deliberately never reads GPS and never asks for the location
121
+ permission: your app already owns that decision (and the App Store / Play
122
+ justification for it), so it hands us a fix whenever it has one.
123
+
124
+ ```js
125
+ import Geolocation from '@react-native-community/geolocation'; // or expo-location
126
+
127
+ Geolocation.getCurrentPosition(({ coords }) => {
128
+ Pushbib.Location.setLocation(coords.latitude, coords.longitude);
129
+ });
130
+
131
+ await Pushbib.Location.getLocation(); // { lat, long } | null
132
+ await Pushbib.Location.clearLocation(); // user turned location sharing off
133
+ ```
134
+
135
+ The value is cached on-device and replayed on every re-registration, so it
136
+ survives push-token rotation and reinstalls. Call `setLocation` again whenever
137
+ you have a newer fix — only the latest one is kept, and there is no background
138
+ tracking: a device that never reports coordinates simply never matches a radius
139
+ segment.
140
+
141
+ ### Events
142
+
143
+ ```js
144
+ // Tap on a notification or an action button — fires in every app state,
145
+ // including cold start (buffered until your listener registers).
146
+ Pushbib.Notifications.addEventListener('click', (e) => {
147
+ e.notification; // { title, body, url, buttons, data, ... }
148
+ e.result.actionId; // button id, or null for a body tap
149
+ e.result.url; // data.url if the campaign set one
150
+ });
151
+
152
+ // Every incoming push, whether it was displayed or not — for logging,
153
+ // analytics, badge math. Buffered until your listener registers.
154
+ Pushbib.Notifications.addEventListener('received', (e) => {
155
+ console.log('push received', e.notification.title, e.notification.data);
156
+ });
157
+
158
+ // Decide whether a push shows while the app is foregrounded.
159
+ // Default (no listener / no preventDefault): it shows.
160
+ Pushbib.Notifications.addEventListener('foregroundWillDisplay', (e) => {
161
+ if (e.notification.data.silent === '1') e.preventDefault(); // synchronous!
162
+ });
163
+
164
+ Pushbib.Notifications.addEventListener('permissionChange', (granted) => {});
165
+ Pushbib.User.pushSubscription.addEventListener('change', ({ id, token, optedIn }) => {});
166
+ ```
167
+
168
+ `data.url` from a campaign is opened automatically on click via `Linking`
169
+ (deep links included). Disable with `initialize({ autoOpenLaunchUrls: false })`.
170
+
171
+ ### Navigate to a screen on click
172
+
173
+ The `click` event is the navigation hook — it fires when the app is in the
174
+ foreground, background, **and** on cold start (the tap that launched the app
175
+ is buffered until your listener registers, so register it early):
176
+
177
+ ```js
178
+ // e.g. with React Navigation and a navigationRef
179
+ Pushbib.Notifications.addEventListener('click', (e) => {
180
+ const { screen, ...params } = e.notification.data; // set in the campaign's data
181
+ if (screen) navigationRef.current?.navigate(screen, params);
182
+ });
183
+ ```
184
+
185
+ Send the campaign with data `{ "screen": "OrderDetails", "orderId": "42" }`
186
+ and set `autoOpenLaunchUrls: false` if you route everything yourself.
187
+
188
+ ### Per-notification display control (showForeground / showBackground)
189
+
190
+ Add these keys to the notification's **data** payload when sending; the SDK
191
+ enforces them natively (default: both `true`):
192
+
193
+ | Data | Effect |
194
+ | --- | --- |
195
+ | `"showForeground": false` | Not displayed while the app is open (`foregroundWillDisplay` is skipped entirely) — the `received` listener still fires. |
196
+ | `"showBackground": false` | Android: not displayed in background/killed — delivery is silent, `received` is buffered for the next app session. iOS: not enforceable client-side (Apple displays background alerts; needs a Notification Service Extension — planned). |
197
+ | both `false` | A silent data push: nothing shows anywhere (Android), your `received` listener gets the payload. |
198
+
199
+ The `received` event **always** fires regardless of these flags — that's the
200
+ "catch and log it" hook. On iOS it fires in the foreground only (background
201
+ alert pushes never wake the app without an NSE).
202
+
203
+ ### Device-local display toggles (foreground / background)
204
+
205
+ `showForeground` / `showBackground` above are set **per message by the sender**.
206
+ For a setting the *user* controls on their own device — "show me banners while
207
+ I'm using the app" vs. "while it's closed" — use the display toggles. They're
208
+ persisted natively and honored on every incoming push, even in a cold process:
209
+
210
+ ```js
211
+ await Pushbib.Notifications.setForegroundDisplayEnabled(false); // silent while open
212
+ await Pushbib.Notifications.setBackgroundDisplayEnabled(false); // silent while closed (Android)
213
+ await Pushbib.Notifications.getForegroundDisplayEnabled(); // → boolean
214
+ ```
215
+
216
+ The device stays **subscribed** either way (unlike `optOut()`): the server keeps
217
+ targeting it and the `received` event keeps firing — only the visible banner is
218
+ suppressed. `setBackgroundDisplayEnabled` is **Android-only**: on iOS the OS
219
+ renders background alerts before the app runs, so it can't be honored
220
+ client-side without a Notification Service Extension.
221
+
222
+ ## Live Activities (iOS) & Live Updates (Android)
223
+
224
+ The lock-screen card that tracks something in progress — a delivery, a ride, a
225
+ match score. Your **backend** drives it (`POST /api/server/v1/live-activity/…`);
226
+ the SDK's job is the device half.
227
+
228
+ **How much the SDK can do differs sharply by platform, and it's worth knowing why
229
+ before you plan the work.**
230
+
231
+ ### Android — the SDK does everything
232
+
233
+ Live updates arrive on the device's normal FCM token and the native service
234
+ renders an ongoing notification, replacing it in place on every update. Nothing to
235
+ set up.
236
+
237
+ ```js
238
+ // Optional: declare that an activity is live so the server can address it.
239
+ // You can skip this entirely and let your backend's /live-activity/start do it.
240
+ await Pushbib.LiveActivities.register({ activityId: 'order_12345' });
241
+
242
+ // Mirror the state in-app, or draw your own richer card from contentState.
243
+ // `displayed` / `outcome` tell you whether it actually reached the tray.
244
+ Pushbib.LiveActivities.addEventListener('update', ({ liveUpdate, displayed, outcome }) => {
245
+ console.log(liveUpdate.action, liveUpdate.contentState); // START | UPDATE | END
246
+ if (!displayed) console.warn('live update not shown:', outcome);
247
+ });
248
+
249
+ await Pushbib.LiveActivities.end('order_12345'); // user dismissed it locally
250
+ ```
251
+
252
+ ⚠️ **`POST_NOTIFICATIONS` must be granted, or nothing renders.** From Android 13
253
+ it is a runtime permission, and until the user grants it every live update is
254
+ dropped on arrival while your server still reports it as delivered. Call
255
+ `Pushbib.Notifications.requestPermission()` at startup. The `update` event then
256
+ reports `outcome: 'notifications-disabled'` rather than failing silently.
257
+
258
+ The ongoing notification is drawn from a small set of conventional keys, because
259
+ Android can't know how to render an app-defined struct:
260
+
261
+ | Shown | Read from |
262
+ |---|---|
263
+ | Title | `alert.title` → `contentState.title` → app name |
264
+ | Body | `alert.body` → `contentState.body` / `.message` / `.status` |
265
+ | Progress bar | `contentState.progress` (0-100), or `.indeterminate: true` |
266
+
267
+ Everything else is still available in full through the `update` event. Live
268
+ updates post to their own `pushbib_live_updates` channel (default importance, no
269
+ badge) so users can silence them separately from regular notifications — name it
270
+ with `com.amrshbib.pushbib.live_update_channel_name`.
271
+
272
+ Updates are silent unless the sender includes an `alert`, and an out-of-order
273
+ delivery is dropped natively as well as server-side — FCM makes no ordering
274
+ guarantee, so two updates sent moments apart can arrive reversed.
275
+
276
+ Out-of-order protection compares sequence numbers **within one numbering stream**
277
+ (`stream_id`: the server session, or `direct` for a session-less test send). It has
278
+ to: a session numbers its updates `1, 2, 3…` and restarts at `1` for every new
279
+ session, while a direct test send numbers by clock (`~1.78e9`). Comparing across
280
+ those would make one test send black-hole every later real update for that activity
281
+ id. A change of stream resets the mark instead of comparing against it.
282
+
283
+ #### "The dashboard says delivered but I see nothing"
284
+
285
+ Every way an update can fail to reach the screen is reported as `outcome` on the
286
+ `update` event (and logged under the `Pushbib` tag):
287
+
288
+ | `outcome` | Meaning |
289
+ |---|---|
290
+ | `shown` / `ended` | It reached the tray |
291
+ | `notifications-disabled` | `POST_NOTIFICATIONS` not granted, or the user turned notifications off — **by far the most common cause** |
292
+ | `stale-sequence` | Older than the last update shown for this activity in the same stream |
293
+ | `opted-out` | The device opted out of push entirely |
294
+ | `notify-blocked` | The OS refused the `notify()` call |
295
+ | `render-error` | Building the notification threw |
296
+
297
+ ```sh
298
+ adb logcat -s Pushbib:V # the same reasons, from a terminal
299
+ ```
300
+
301
+ ### iOS — you own the activity, the SDK owns the server contract
302
+
303
+ **The SDK cannot start or render a Live Activity, and no library can.**
304
+ `ActivityAttributes` and its SwiftUI `ActivityConfiguration` are types that must
305
+ be declared in *your* Widget Extension, and `Activity<Attributes>` is generic over
306
+ them. There is no API by which a package could do this for you.
307
+
308
+ What the SDK does own is the server contract. Your Swift observes the tokens
309
+ ActivityKit hands you and reports them; registration, retry and the HTTP call are
310
+ handled:
311
+
312
+ First make the bridge visible to Swift. With the default React Native setup
313
+ (static libraries), add to your app's Objective-C bridging header:
314
+
315
+ ```objc
316
+ #import "PushbibLiveActivities.h"
317
+ ```
318
+
319
+ With `use_frameworks!`, `import react_native_pushbib` in the Swift file instead.
320
+
321
+ ```swift
322
+ import ActivityKit
323
+
324
+ // 1. Start the activity — your attributes, your widget
325
+ let activity = try Activity<DeliveryAttributes>.request(
326
+ attributes: DeliveryAttributes(orderId: "12345"),
327
+ content: .init(state: .init(status: "Preparing", eta: 25), staleDate: nil),
328
+ pushType: .token)
329
+
330
+ // 2. Report its token. Fires again on rotation, so keep observing.
331
+ Task {
332
+ for await tokenData in activity.pushTokenUpdates {
333
+ PushbibLiveActivities.reportActivityToken(
334
+ PushbibLiveActivities.hexString(from: tokenData),
335
+ forActivity: "order_12345",
336
+ attributesType: "DeliveryAttributes")
337
+ }
338
+ }
339
+
340
+ // 3. iOS 17.2+ — report ONCE at launch so your backend can start activities
341
+ // while the app isn't running (POST /live-activity/start).
342
+ Task {
343
+ for await tokenData in Activity<DeliveryAttributes>.pushToStartTokenUpdates {
344
+ PushbibLiveActivities.reportPushToStartToken(
345
+ PushbibLiveActivities.hexString(from: tokenData),
346
+ attributesType: "DeliveryAttributes")
347
+ }
348
+ }
349
+ ```
350
+
351
+ Reports are queued until JS is ready, so a token observed during app launch is
352
+ never lost. Add `NSSupportsLiveActivities: true` to your `Info.plist`.
353
+
354
+ You don't need to call `register()` on iOS — reported tokens register themselves.
355
+ It's there if you'd rather pass a token in from JS.
356
+
357
+ There is no `update` event on iOS: ActivityKit updates the widget directly and
358
+ your app process is never woken.
359
+
360
+ ### Reconciling after a cold start
361
+
362
+ iOS can restore activities your process knows nothing about. Ask the server what
363
+ it still thinks is live, then re-report tokens or end what's stale:
364
+
365
+ ```js
366
+ const sessions = await Pushbib.LiveActivities.getSessions();
367
+ // [{ activity_id, status, activity_token_registered, last_sequence_number, … }]
368
+ ```
369
+
370
+ ## Android customization (optional)
371
+
372
+ `AndroidManifest.xml` meta-data, all optional:
373
+
374
+ ```xml
375
+ <meta-data android:name="com.amrshbib.pushbib.default_notification_icon"
376
+ android:resource="@drawable/ic_stat_notify" />
377
+ <meta-data android:name="com.amrshbib.pushbib.default_notification_color"
378
+ android:value="#2E7DF6" />
379
+ <meta-data android:name="com.amrshbib.pushbib.default_channel_name"
380
+ android:value="Notifications" />
381
+ ```
382
+
383
+ Notifications post to a high-importance `pushbib_default` channel unless the
384
+ campaign names one — see below.
385
+
386
+ ## Notification channels
387
+
388
+ Channels are defined server-side (dashboard → **App Settings → Channels**, the
389
+ third section beside Project and Team) and created on the phone by the SDK. One
390
+ channel holds the Android side (importance, sound, vibration, lights,
391
+ lock-screen visibility, badge, DND bypass, grouping) and the iOS side (sound,
392
+ interruption level, relevance score, thread id, critical alerts). An app
393
+ normally runs several at once.
394
+
395
+ `initialize()` fetches them from `/config` and creates them before the first push
396
+ can land. A channel created later still works on its first send: the definition
397
+ travels inside the push and the SDK creates the channel on the spot.
398
+
399
+ ```js
400
+ await Pushbib.Channels.sync();
401
+ const onDevice = await Pushbib.Channels.list(); // [{ id, name, importance, blocked, showBadge }]
402
+ const muted = onDevice.filter((c) => c.blocked);
403
+ await Pushbib.Channels.openSettings('orders'); // wire this to your own settings screen
404
+ ```
405
+
406
+ Importance has four rungs, and sound, vibration and lights are each **off**,
407
+ **default** or **custom**:
408
+
409
+ | Field | Values | On the phone |
410
+ | --- | --- | --- |
411
+ | `importance` | `low` | Silent, no banner (`IMPORTANCE_LOW`) |
412
+ | | `medium` | Makes a sound (`IMPORTANCE_DEFAULT`) |
413
+ | | `high` | Sound + heads-up banner (`IMPORTANCE_HIGH`) |
414
+ | | `urgent` | `IMPORTANCE_MAX` — the same threshold as `high` |
415
+ | `sound` | `{ mode: 'off' }` | No sound |
416
+ | | `{ mode: 'default' }` | The phone's default notification tone |
417
+ | | `{ mode: 'custom', name: 'order_ding' }` | `res/raw/order_ding` |
418
+ | `vibration` | `{ mode: 'off' }` | No vibration |
419
+ | | `{ mode: 'default' }` | Vibrates, OS pattern |
420
+ | | `{ mode: 'custom', pattern: [0, 250, 250, 250] }` | That pattern, in ms |
421
+ | `led` | `{ mode: 'off' }` | No light |
422
+ | | `{ mode: 'default' }` | Blinks, OS colour |
423
+ | | `{ mode: 'custom', color: '#2E7DF7' }` | Blinks in that colour |
424
+
425
+ `urgent` and `high` are indistinguishable on the device — Android clamps
426
+ `IMPORTANCE_MAX` down — so `Channels.list()` reports `4` for both.
427
+
428
+ **Sounds ship inside the app** — sound mode `custom` names a file, it never
429
+ downloads one:
430
+
431
+ | Platform | Where the file goes | What `sound.name` holds |
432
+ | --- | --- | --- |
433
+ | Android | `android/app/src/main/res/raw/order_ding.mp3` | `order_ding` — no extension, `[a-z0-9_]` |
434
+ | iOS | the app bundle, `order_ding.caf` | `order_ding.caf` — with extension, ≤ 30 s |
435
+
436
+ A name that is not bundled falls back to the default tone and logs a warning, so
437
+ a missing file never means a silent push.
438
+
439
+ Android channels are immutable after creation, so editing the sound or importance
440
+ server-side creates `nf_<key>_v<n+1>` and deletes `nf_<key>_v<n>` on the next
441
+ sync — a user who muted the old one starts hearing the new one. If your app
442
+ already creates its own channels, set **App-owned channel id** on the channel and
443
+ the SDK sends that id through without creating anything — but note that a pinned
444
+ id never changes, so a channel that carries one keeps whatever sound, importance
445
+ and vibration the phone created it with, no matter what the dashboard says.
446
+
447
+ ## Known limitations (v1)
448
+
449
+ - **iOS action buttons & rich images** need a Notification Service Extension
450
+ (an Apple constraint, not ours). Not included yet; Android
451
+ supports both natively.
452
+ - `getTags()` returns the local cache; use `getMe()` for the server truth.
453
+ - Badges on Android are channel-driven (`setBadgeCount` is iOS-only).
454
+ - `Channels.list()` and `openSettings(key)` are Android-only; on iOS they return
455
+ `[]` and open the app's own settings page, because iOS has no channels.
456
+ - iOS `time-sensitive` and `critical` need an Apple entitlement — without it APNs
457
+ accepts the push and iOS ignores the level.
458
+ - **iOS Live Activities need app-side Swift** — the `ActivityAttributes` and the
459
+ widget must live in your Widget Extension, so no library can supply them. The
460
+ SDK provides the token bridge; see the section above. Android needs nothing.
461
+ - **Android live updates can't be scheduled for removal.** An `END` with a future
462
+ `dismissal_date` leaves a dismissible card rather than auto-clearing later —
463
+ Android has no equivalent of ActivityKit's dismissal date.
464
+
465
+ ## Troubleshooting
466
+
467
+ - **`pushbib/no-android-config`** — the server has no Android push identity
468
+ for this app yet: open App Settings and run "Detect from service account".
469
+ - **`pushbib/token-timeout` on iOS** — simulators can't get APNs tokens;
470
+ use a real device and check the Push Notifications capability.
471
+ - **No pushes on iOS** — upload the APNs `.p8` key in App Settings; make sure
472
+ *sandbox* matches your build type (debug = sandbox).
473
+ - **Android background pushes delayed** — aggressive OEM battery savers
474
+ (Xiaomi/Huawei…) throttle high-priority data messages for apps the user
475
+ force-stopped; this affects every push SDK equally.
@@ -0,0 +1,51 @@
1
+ buildscript {
2
+ if (project == rootProject) {
3
+ repositories {
4
+ google()
5
+ mavenCentral()
6
+ }
7
+ dependencies {
8
+ classpath "com.android.tools.build:gradle:8.6.1"
9
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.20"
10
+ }
11
+ }
12
+ }
13
+
14
+ def safeExtGet(prop, fallback) {
15
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
16
+ }
17
+
18
+ apply plugin: 'com.android.library'
19
+ apply plugin: 'org.jetbrains.kotlin.android'
20
+
21
+ android {
22
+ namespace "com.amrshbib.pushbib"
23
+ compileSdkVersion Math.max(safeExtGet('compileSdkVersion', 36) as Integer, 36)
24
+
25
+ defaultConfig {
26
+ minSdkVersion safeExtGet('minSdkVersion', 24)
27
+ targetSdkVersion safeExtGet('targetSdkVersion', 36)
28
+ }
29
+
30
+ compileOptions {
31
+ sourceCompatibility JavaVersion.VERSION_17
32
+ targetCompatibility JavaVersion.VERSION_17
33
+ }
34
+
35
+ kotlinOptions {
36
+ jvmTarget = "17"
37
+ }
38
+ }
39
+
40
+ repositories {
41
+ google()
42
+ mavenCentral()
43
+ }
44
+
45
+ dependencies {
46
+ implementation "com.facebook.react:react-native:+"
47
+
48
+ implementation "com.google.firebase:firebase-messaging:24.1.2"
49
+
50
+ implementation "androidx.core:core-ktx:1.13.1"
51
+ }
@@ -0,0 +1,15 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+
3
+ <uses-permission android:name="android.permission.INTERNET" />
4
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
5
+
6
+ <application>
7
+ <service
8
+ android:name="com.amrshbib.pushbib.PushbibMessagingService"
9
+ android:exported="false">
10
+ <intent-filter>
11
+ <action android:name="com.google.firebase.MESSAGING_EVENT" />
12
+ </intent-filter>
13
+ </service>
14
+ </application>
15
+ </manifest>
@@ -0,0 +1,37 @@
1
+ package com.amrshbib.pushbib
2
+
3
+ import android.content.Context
4
+ import com.google.firebase.FirebaseApp
5
+ import com.google.firebase.FirebaseOptions
6
+ import com.google.firebase.messaging.FirebaseMessaging
7
+ import org.json.JSONObject
8
+
9
+ object FirebaseBootstrap {
10
+ private const val APP_NAME = "PUSHBIB"
11
+
12
+ @Synchronized
13
+ fun messaging(context: Context, config: JSONObject): FirebaseMessaging {
14
+ val options = FirebaseOptions.Builder()
15
+ .setGcmSenderId(config.getString("sender_id"))
16
+ .setApplicationId(config.getString("app_id"))
17
+ .setApiKey(config.getString("api_key"))
18
+ .apply {
19
+ config.optString("project_id").takeIf { it.isNotEmpty() }?.let { setProjectId(it) }
20
+ }
21
+ .build()
22
+
23
+ val existing = FirebaseApp.getApps(context).firstOrNull { it.name == APP_NAME }
24
+ val app = when {
25
+ existing == null -> FirebaseApp.initializeApp(context, options, APP_NAME)
26
+ sameOptions(existing.options, options) -> existing
27
+ else -> {
28
+ existing.delete()
29
+ FirebaseApp.initializeApp(context, options, APP_NAME)
30
+ }
31
+ }
32
+ return app.get(FirebaseMessaging::class.java)
33
+ }
34
+
35
+ private fun sameOptions(a: FirebaseOptions, b: FirebaseOptions): Boolean =
36
+ a.applicationId == b.applicationId && a.gcmSenderId == b.gcmSenderId && a.apiKey == b.apiKey
37
+ }
@@ -0,0 +1,102 @@
1
+ package com.amrshbib.pushbib
2
+
3
+ import com.google.firebase.messaging.RemoteMessage
4
+ import org.json.JSONObject
5
+
6
+ class LiveUpdatePayload private constructor(
7
+ val activityId: String,
8
+ val action: String,
9
+ val notificationId: Int,
10
+ val sequenceNumber: Long,
11
+ val streamId: String?,
12
+ val title: String?,
13
+ val body: String?,
14
+ val progress: Int?,
15
+ val indeterminate: Boolean,
16
+ val staleDate: Long?,
17
+ val dismissalDate: Long?,
18
+ val alerting: Boolean,
19
+ val contentState: JSONObject?,
20
+ val data: Map<String, String>,
21
+ ) {
22
+ val isEnd: Boolean get() = action == ACTION_END
23
+ val isStart: Boolean get() = action == ACTION_START
24
+
25
+ fun toJson(): JSONObject = JSONObject().apply {
26
+ put("activityId", activityId)
27
+ put("action", action)
28
+ put("notificationId", notificationId)
29
+ put("sequenceNumber", sequenceNumber)
30
+ putOpt("streamId", streamId)
31
+ put("alerting", alerting)
32
+ putOpt("title", title)
33
+ putOpt("body", body)
34
+ progress?.let { put("progress", it) }
35
+ if (indeterminate) put("indeterminate", true)
36
+ staleDate?.let { put("staleDate", it) }
37
+ dismissalDate?.let { put("dismissalDate", it) }
38
+ putOpt("contentState", contentState)
39
+ put("data", JSONObject(data as Map<*, *>))
40
+ }
41
+
42
+ companion object {
43
+ const val TYPE = "LIVE_UPDATE"
44
+ const val ACTION_START = "START"
45
+ const val ACTION_UPDATE = "UPDATE"
46
+ const val ACTION_END = "END"
47
+
48
+ private val CONTROL_KEYS = setOf(
49
+ "pushbib_type", "pushbib_live_payload", "activity_id",
50
+ "notification_id", "action", "sequence_number", "stream_id",
51
+ )
52
+
53
+ fun isLiveUpdate(message: RemoteMessage): Boolean = message.data["pushbib_type"] == TYPE
54
+
55
+ fun fromRemoteMessage(message: RemoteMessage): LiveUpdatePayload? {
56
+ val data = message.data
57
+ if (data["pushbib_type"] != TYPE) return null
58
+
59
+ val activityId = data["activity_id"]?.takeIf { it.isNotEmpty() } ?: return null
60
+ val action = data["action"]?.uppercase()?.takeIf {
61
+ it == ACTION_START || it == ACTION_UPDATE || it == ACTION_END
62
+ } ?: return null
63
+
64
+ val live = data["pushbib_live_payload"]?.let { runCatching { JSONObject(it) }.getOrNull() }
65
+ val contentState = live?.optJSONObject("contentState")
66
+ val alert = live?.optJSONObject("alert")
67
+
68
+ val notificationId = data["notification_id"]?.toIntOrNull()
69
+ ?: live?.optInt("notificationId", 0)?.takeIf { it != 0 }
70
+ ?: (activityId.hashCode() and 0x7FFFFFFF)
71
+
72
+ val progressRaw = contentState?.optInt("progress", -1) ?: -1
73
+
74
+ return LiveUpdatePayload(
75
+ activityId = activityId,
76
+ action = action,
77
+ notificationId = notificationId,
78
+ sequenceNumber = data["sequence_number"]?.toLongOrNull()
79
+ ?: live?.optLong("sequenceNumber", 0L) ?: 0L,
80
+ streamId = data["stream_id"]?.takeIf { it.isNotEmpty() }
81
+ ?: live?.optNonEmpty("streamId"),
82
+ title = alert?.optNonEmpty("title") ?: contentState?.optNonEmpty("title"),
83
+ body = alert?.optNonEmpty("body")
84
+ ?: contentState?.optNonEmpty("body")
85
+ ?: contentState?.optNonEmpty("message")
86
+ ?: contentState?.optNonEmpty("status"),
87
+ progress = progressRaw.takeIf { it in 0..100 },
88
+ indeterminate = contentState?.optBoolean("indeterminate", false) ?: false,
89
+ staleDate = live?.optLong("staleDate", 0L)?.takeIf { it > 0 },
90
+ dismissalDate = live?.optLong("dismissalDate", 0L)?.takeIf { it > 0 },
91
+ alerting = alert != null,
92
+ contentState = contentState,
93
+ data = HashMap<String, String>().apply {
94
+ for ((k, v) in data) if (k !in CONTROL_KEYS) put(k, v)
95
+ },
96
+ )
97
+ }
98
+
99
+ private fun JSONObject.optNonEmpty(key: String): String? =
100
+ optString(key, "").takeIf { it.isNotEmpty() }
101
+ }
102
+ }