@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/README.md CHANGED
@@ -50,14 +50,11 @@ Pushbib.Notifications.addEventListener('click', (e) => {
50
50
 
51
51
  ```bash
52
52
  npm install @amrshbib/react-native-pushbib
53
- # or from the monorepo:
54
- npm install file:../RNPackages/@amrshbib/react-native-pushbib
53
+ # or: yarn add @amrshbib/react-native-pushbib
55
54
 
56
55
  cd ios && pod install
57
56
  ```
58
57
 
59
- > Full guide with diagrams: [`Docs/MOBILE-SDK.md`](../../../Docs/MOBILE-SDK.md)
60
-
61
58
  Autolinking does the rest. **Requirements:** React Native ≥ 0.71 (old + new
62
59
  architecture via interop), Android minSdk 24, iOS 13+.
63
60
 
@@ -80,6 +77,44 @@ architecture via interop), Android minSdk 24, iOS 13+.
80
77
  notifications*.
81
78
  - **Android**: nothing.
82
79
 
80
+ ### Images in notifications (iOS only — Android needs nothing)
81
+
82
+ Android draws the picture itself. iOS does not: the system only attaches an image if the app
83
+ ships a *Notification Service Extension*, and Apple requires that to be its own target. The
84
+ SDK ships the whole extension — code, Info.plist and all. **Your app owns no file.**
85
+
86
+ **Xcode → File → New → Target → Notification Service Extension.** Name it
87
+ `PushbibNotificationService` and decline the "activate scheme" prompt so Run still launches
88
+ the app. Then, in the new target's Build Settings:
89
+
90
+ 1. **Delete the `NotificationService.h` / `.m` and the `Info.plist` Xcode generated** —
91
+ including from the target's *Compile Sources*. You need none of them.
92
+ 2. Set **Info.plist File** to
93
+ `$(SRCROOT)/../node_modules/@amrshbib/react-native-pushbib/ios/NotificationService/Info.plist`
94
+ 3. Drag `node_modules/@amrshbib/react-native-pushbib/ios/NotificationService/PushbibNotificationService.m`
95
+ into the target's *Compile Sources* (uncheck "Copy items if needed" — reference it in place).
96
+
97
+ There is no Podfile entry and no `pod install`: the target compiles that one file and links
98
+ `UserNotifications`, nothing else. Upgrading the SDK upgrades the extension on the next
99
+ build, because the app is pointing at the SDK rather than holding a copy.
100
+
101
+ That's it. The extension reads the image URL from `imageUrl` (a direct APNs push) or
102
+ `fcm_options.image` (one routed through FCM), downloads it, and attaches it. If the download
103
+ fails, times out, or the type is one iOS cannot attach, the notification still arrives with
104
+ its title and body — the picture is never worth losing the message over.
105
+
106
+ Two things that silently cost you the picture:
107
+
108
+ - **The URL must be `https`.** App Transport Security blocks plain `http` and reports nothing,
109
+ so an image served from `http://localhost:5001` will never appear on a real device. The
110
+ extension logs `notification image skipped, iOS only loads https` when it sees one.
111
+ - **The extension needs its own bundle id** under your app's, e.g.
112
+ `com.yourcompany.app.PushbibNotificationService`, with a matching provisioning profile.
113
+ Xcode does this for you when you create the target; it only bites on manual signing.
114
+
115
+ To change what it does, subclass `PushbibNotificationService`, override `willDeliverContent:`
116
+ or `imageURLKeys`, and name your subclass as the principal class instead.
117
+
83
118
  ## API
84
119
 
85
120
  | Call | What it does |
@@ -92,19 +127,37 @@ architecture via interop), Android minSdk 24, iOS 13+.
92
127
  | `Pushbib.User.addTag(k, [a, b])` | A tag value may be a list. |
93
128
  | `Pushbib.User.removeTag(k)` / `removeTags([k])` | Delete tag keys. |
94
129
  | `Pushbib.User.removeTag(k, [a])` | Drop items from a list, keeping the rest. |
95
- | `Pushbib.User.getTags()` | Local cache of tags set through this install. |
130
+ | `Pushbib.User.getTags()` | Local cache of tags set through this install (a promise; `getTagsSync()` is the old synchronous read). |
131
+ | `Pushbib.User.setLanguage(code)` | Override the device locale used for targeting. Sent with every register/link and pushed with `/devices/profile`. |
132
+ | `Pushbib.User.getLanguage()` | The override, or the device locale when none was set. |
96
133
  | `Pushbib.User.getExternalId()` | Current external id (or null). |
97
- | `Pushbib.User.pushSubscription.getId()` | Stable subscription id (treat as a secret). |
134
+ | `Pushbib.User.pushSubscription.getId()` | Stable subscription id (treat as a secret). `getIdAsync()` is the same call. |
98
135
  | `Pushbib.User.pushSubscription.getToken()` | Raw push token (FCM registration token / APNs hex). |
136
+ | `Pushbib.User.pushSubscription.getOptedIn()` | Whether this device is subscribed. `getOptedInAsync()` is the same call. |
99
137
  | `Pushbib.User.pushSubscription.optOut()` / `optIn()` | Server-side unsubscribe / resubscribe. |
138
+ | `Pushbib.User.pushSubscription.addEventListener('change', fn)` | Fires with `{ id, token, optedIn }` on register, token rotation and opt in/out. |
139
+ | `Pushbib.User.addEventListener('change', fn)` | Fires with `{ current: { externalId, subscriptionId } }` on login / logout. |
100
140
  | `Pushbib.Location.setLocation(lat, long)` | Report coordinates for radius targeting. Shown as "Location point" on the user record. |
101
141
  | `Pushbib.Location.getLocation()` | Last coordinates reported from this install (or null). |
102
142
  | `Pushbib.Location.clearLocation()` | Forget them — the device stops matching radius segments. |
103
- | `Pushbib.Notifications.requestPermission()` | OS prompt (iOS, Android 13+). Resolves granted. |
104
- | `Pushbib.Notifications.hasPermission()` | Current permission state. |
143
+ | `Pushbib.Location.setShared(bool)` / `isShared()` | Off stops `setLocation()` from sending and drops the point from the register payload. |
144
+ | `Pushbib.Location.requestPermission()` | Android only: ask the OS for location permission. |
145
+ | `Pushbib.Notifications.requestPermission(fallbackToSettings?)` | OS prompt (iOS, Android 13+). Resolves granted. With `true`, a second call opens the app's settings page, because the OS prompt only ever shows once. |
146
+ | `Pushbib.Notifications.hasPermission()` / `getPermissionAsync()` | Current permission state. |
147
+ | `Pushbib.Notifications.canRequestPermission()` | Whether the OS prompt can still appear. |
148
+ | `Pushbib.Notifications.permissionNative()` | Native permission state as a number: 0 not determined, 1 denied, 2 authorized, 3 provisional, 4 ephemeral. |
149
+ | `Pushbib.Notifications.removeNotification(id)` / `removeGroupedNotifications(group)` | Clear one notification, or a whole group. |
105
150
  | `Pushbib.Notifications.clearAll()` | Clear delivered notifications (+ badge on iOS). |
106
151
  | `Pushbib.Notifications.setForegroundDisplayEnabled(bool)` / `getForegroundDisplayEnabled()` | Device-local toggle: show pushes while the app is open. Default: true. |
107
152
  | `Pushbib.Notifications.setBackgroundDisplayEnabled(bool)` / `getBackgroundDisplayEnabled()` | Device-local toggle: show pushes while the app is backgrounded (Android only). Default: true. |
153
+ | `Pushbib.Notifications.setLiveUpdateDisplayEnabled(bool)` / `getLiveUpdateDisplayEnabled()` | Device-local toggle: render live updates (Android only). Off reports `outcome: 'local-display-off'`. Default: true. |
154
+ | `Pushbib.Debug.setLogLevel(level)` | `'verbose'` or OneSignal's `LogLevel.Verbose`. `setAlertLevel` is accepted and ignored. |
155
+ | `Pushbib.LiveActivities.register({ activityId })` | Declare an activity live so the server can address it. On iOS also takes `activityPushToken` / `pushToStartToken` / `attributesType`. |
156
+ | `Pushbib.LiveActivities.end(activityId?)` | End one activity, or every live one for this device when called with no id. |
157
+ | `Pushbib.LiveActivities.getSessions()` | What the server still thinks is live for this device. |
158
+ | `Pushbib.LiveActivities.addEventListener('update', fn)` | Android only: every live update, with `displayed` and `outcome`. |
159
+ | `Pushbib.LiveActivities.enter(id, token?)` / `exit(id)` | OneSignal's names for `register` / `end`. These resolve to `null` on failure instead of rejecting. |
160
+ | `Pushbib.LiveActivities.setPushToStartToken(type, token)` / `removePushToStartToken(type)` | OneSignal's names for the push-to-start token calls. |
108
161
  | `Pushbib.Channels.sync()` | Re-read the app's channels from `/config` and apply them. Runs on start already. |
109
162
  | `Pushbib.Channels.list()` | Channels on this phone with their live importance and a `blocked` flag (Android only). |
110
163
  | `Pushbib.Channels.definitions()` | What the server last sent, from the local cache. |
@@ -212,9 +265,15 @@ persisted natively and honored on every incoming push, even in a cold process:
212
265
  ```js
213
266
  await Pushbib.Notifications.setForegroundDisplayEnabled(false); // silent while open
214
267
  await Pushbib.Notifications.setBackgroundDisplayEnabled(false); // silent while closed (Android)
268
+ await Pushbib.Notifications.setLiveUpdateDisplayEnabled(false); // no live-update cards (Android)
215
269
  await Pushbib.Notifications.getForegroundDisplayEnabled(); // → boolean
216
270
  ```
217
271
 
272
+ There is a third toggle for the lock-screen cards: `setLiveUpdateDisplayEnabled(false)`
273
+ stops live updates from rendering while ordinary notifications keep showing — worth
274
+ its own switch, since a delivery tracker is the kind of thing a user mutes on its own.
275
+ The `update` event still fires, reporting `outcome: 'local-display-off'`.
276
+
218
277
  The device stays **subscribed** either way (unlike `optOut()`): the server keeps
219
278
  targeting it and the `received` event keeps firing — only the visible banner is
220
279
  suppressed. `setBackgroundDisplayEnabled` is **Android-only**: on iOS the OS
@@ -293,6 +352,7 @@ Every way an update can fail to reach the screen is reported as `outcome` on the
293
352
  | `notifications-disabled` | `POST_NOTIFICATIONS` not granted, or the user turned notifications off — **by far the most common cause** |
294
353
  | `stale-sequence` | Older than the last update shown for this activity in the same stream |
295
354
  | `opted-out` | The device opted out of push entirely |
355
+ | `local-display-off` | `setLiveUpdateDisplayEnabled(false)` on this device |
296
356
  | `notify-blocked` | The OS refused the `notify()` call |
297
357
  | `render-error` | Building the notification threw |
298
358
 
@@ -446,13 +506,62 @@ the SDK sends that id through without creating anything — but note that a pinn
446
506
  id never changes, so a channel that carries one keeps whatever sound, importance
447
507
  and vibration the phone created it with, no matter what the dashboard says.
448
508
 
449
- ## Known limitations (v1)
509
+ ## Drop-in beside OneSignal
510
+
511
+ The call names match `react-native-onesignal`, so one wrapper can drive both SDKs with no
512
+ per-provider branches:
450
513
 
451
- - **iOS action buttons & rich images** need a Notification Service Extension
452
- (an Apple constraint, not ours). Not included yet; Android
453
- supports both natively.
514
+ | OneSignal | Pushbib |
515
+ | --- | --- |
516
+ | `OneSignal.initialize(appId)` | `Pushbib.initialize({ baseUrl, appId, appKey })` — self-hosted, so it needs the server and the key |
517
+ | `OneSignal.login(id)` / `logout()` | same |
518
+ | `OneSignal.Debug.setLogLevel(LogLevel.Verbose)` | same, and `'verbose'` also works |
519
+ | `OneSignal.User.addTag(s)` / `removeTag(s)` / `getTags()` | same |
520
+ | `OneSignal.User.setLanguage(code)` | same |
521
+ | `OneSignal.User.addEventListener('change', fn)` | same (`{ current: { externalId, subscriptionId } }`) |
522
+ | `OneSignal.User.pushSubscription.getIdAsync()` / `getTokenAsync()` / `getOptedInAsync()` / `optIn()` / `optOut()` | same |
523
+ | `OneSignal.Notifications.requestPermission(fallbackToSettings)` | same |
524
+ | `OneSignal.Notifications.getPermissionAsync()` / `canRequestPermission()` / `permissionNative()` | same |
525
+ | `OneSignal.Notifications.clearAll()` / `removeNotification(id)` / `removeGroupedNotifications(g)` | same |
526
+ | `OneSignal.Notifications.addEventListener('click' \| 'foregroundWillDisplay' \| 'permissionChange')` | same, plus `'received'` |
527
+ | `OneSignal.Location.setShared(bool)` / `isShared()` / `requestPermission()` | same (`requestPermission` is Android-only here) |
528
+ | `OneSignal.LiveActivities.enter(id, token)` / `exit(id)` | same, over `register()` / `end()` |
529
+ | `OneSignal.LiveActivities.setPushToStartToken(type, token)` / `removePushToStartToken(type)` | same |
530
+
531
+ `optIn()` / `optOut()` match OneSignal's meaning exactly: they turn push on and off for this
532
+ device without removing anything. An opted-out device still registers on every launch and stays
533
+ on the dashboard's device list as **unsubscribed** — with its token, tags, language and session
534
+ count intact — so it reappears the moment `optIn()` is called. Only an explicit delete in the
535
+ dashboard removes a device.
536
+
537
+ Two deliberate differences:
538
+
539
+ - **Nothing throws on empty or odd input.** `addTags({})`, `removeTags([])`, `login('')`,
540
+ `setLocation(NaN)` log a warning and resolve, the way OneSignal ignores them, so call sites
541
+ need no guards. The Pushbib-specific calls that return data (`register`, `getMe`) still reject
542
+ on a real failure, while the OneSignal-named `enter` / `exit` resolve to `null` instead.
543
+ - **`initialize` still throws** when `baseUrl`, `appId` or `appKey` is missing, because that is a
544
+ setup mistake worth failing loudly at boot.
545
+
546
+ Not implemented, because they need product decisions rather than a shim: aliases
547
+ (`addAlias`), email and SMS subscriptions (`addEmail`, `addSms`), outcomes
548
+ (`Session.addOutcome`), `User.trackEvent`, in-app messages, consent gating
549
+ (`setConsentRequired` / `setConsentGiven`), iOS provisional authorization, and
550
+ `LiveActivities.setupDefault` / `startDefault` (they own ActivityKit from inside the SDK).
551
+
552
+ ## Known limitations
553
+
554
+ - **iOS action buttons** are not implemented — the SDK does not register
555
+ `UNNotificationCategory`, so buttons sent to an iOS device are ignored.
556
+ Android renders them natively.
557
+ - **iOS rich images** need the Notification Service Extension target described
558
+ in [Images in notifications](#images-in-notifications-ios-only--android-needs-nothing)
559
+ (an Apple constraint, not ours). Android needs nothing.
454
560
  - `getTags()` returns the local cache; use `getMe()` for the server truth.
455
- - Badges on Android are channel-driven (`setBadgeCount` is iOS-only).
561
+ - **No badge API from JS.** Badges on Android are channel-driven (`showBadge` on the
562
+ channel). The native module exports `setBadgeCount`, but nothing in the JS surface
563
+ calls it and the Android implementation is an empty stub, so it is iOS-only and
564
+ unreachable today.
456
565
  - `Channels.list()` and `openSettings(key)` are Android-only; on iOS they return
457
566
  `[]` and open the app's own settings page, because iOS has no channels.
458
567
  - iOS `time-sensitive` and `critical` need an Apple entitlement — without it APNs
@@ -26,6 +26,9 @@ object NotificationRenderer {
26
26
  private const val META_DEFAULT_COLOR = "com.amrshbib.pushbib.default_notification_color"
27
27
  private const val META_DEFAULT_CHANNEL_NAME = "com.amrshbib.pushbib.default_channel_name"
28
28
  private const val IMAGE_TIMEOUT_MS = 8000
29
+ private const val MAX_REDIRECTS = 5
30
+ private const val MAX_IMAGE_BYTES = 10 * 1024 * 1024
31
+ private const val MAX_IMAGE_EDGE_PX = 1024
29
32
 
30
33
  private val executor = Executors.newSingleThreadExecutor()
31
34
 
@@ -152,13 +155,78 @@ object NotificationRenderer {
152
155
 
153
156
  private fun fetchBitmap(url: String?): Bitmap? {
154
157
  if (url.isNullOrEmpty()) return null
158
+ val bytes = download(url) ?: return null
159
+ return decodeScaled(bytes, url)
160
+ }
161
+
162
+ // HttpURLConnection drops a redirect that changes scheme, so an http URL that
163
+ // answers 301 to https hands back the redirect body instead of the picture and
164
+ // the decode fails with nothing useful in the log. Follow the hops ourselves.
165
+ private fun download(url: String): ByteArray? {
166
+ var target = url
167
+ repeat(MAX_REDIRECTS) {
168
+ var conn: HttpURLConnection? = null
169
+ try {
170
+ conn = (URL(target).openConnection() as HttpURLConnection).apply {
171
+ connectTimeout = IMAGE_TIMEOUT_MS
172
+ readTimeout = IMAGE_TIMEOUT_MS
173
+ instanceFollowRedirects = false
174
+ setRequestProperty("Accept", "image/*")
175
+ }
176
+ val code = conn.responseCode
177
+ if (code in 300..399) {
178
+ val next = conn.getHeaderField("Location")
179
+ if (next.isNullOrEmpty()) {
180
+ android.util.Log.w("Pushbib", "image redirect with no Location ($target)")
181
+ return null
182
+ }
183
+ target = URL(URL(target), next).toString()
184
+ return@repeat
185
+ }
186
+ if (code !in 200..299) {
187
+ android.util.Log.w("Pushbib", "image fetch got HTTP $code ($target)")
188
+ return null
189
+ }
190
+ val bytes = conn.inputStream.use { it.readBytes() }
191
+ if (bytes.size > MAX_IMAGE_BYTES) {
192
+ android.util.Log.w("Pushbib", "image is ${bytes.size} bytes, over the ${MAX_IMAGE_BYTES} cap ($target)")
193
+ return null
194
+ }
195
+ return bytes
196
+ } catch (e: Exception) {
197
+ android.util.Log.w("Pushbib", "image fetch failed ($target): ${e.message}")
198
+ return null
199
+ } finally {
200
+ conn?.disconnect()
201
+ }
202
+ }
203
+ android.util.Log.w("Pushbib", "image fetch gave up after $MAX_REDIRECTS redirects ($url)")
204
+ return null
205
+ }
206
+
207
+ // A full-size photo decoded as-is is several megabytes, and the notification
208
+ // travels to the system over Binder, which drops anything that large — the push
209
+ // then arrives with no picture at all. Decode it down first.
210
+ private fun decodeScaled(bytes: ByteArray, url: String): Bitmap? {
155
211
  return try {
156
- val conn = URL(url).openConnection() as HttpURLConnection
157
- conn.connectTimeout = IMAGE_TIMEOUT_MS
158
- conn.readTimeout = IMAGE_TIMEOUT_MS
159
- conn.inputStream.use { BitmapFactory.decodeStream(it) }
160
- } catch (e: Exception) {
161
- android.util.Log.w("Pushbib", "image fetch failed ($url): ${e.message}")
212
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
213
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
214
+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
215
+ android.util.Log.w("Pushbib", "image is not a picture we can decode ($url)")
216
+ return null
217
+ }
218
+ var sample = 1
219
+ while (bounds.outWidth / sample > MAX_IMAGE_EDGE_PX || bounds.outHeight / sample > MAX_IMAGE_EDGE_PX) {
220
+ sample *= 2
221
+ }
222
+ val opts = BitmapFactory.Options().apply { inSampleSize = sample }
223
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
224
+ ?: run {
225
+ android.util.Log.w("Pushbib", "image could not be decoded ($url)")
226
+ null
227
+ }
228
+ } catch (e: OutOfMemoryError) {
229
+ android.util.Log.w("Pushbib", "image too large to decode ($url): ${e.message}")
162
230
  null
163
231
  }
164
232
  }
@@ -1,6 +1,7 @@
1
1
  package com.amrshbib.pushbib
2
2
 
3
3
  import android.Manifest
4
+ import android.app.NotificationManager
4
5
  import android.content.Context
5
6
  import android.content.Intent
6
7
  import android.content.pm.PackageManager
@@ -243,6 +244,44 @@ class PushbibModule(private val context: ReactApplicationContext) :
243
244
  NotificationManagerCompat.from(context).cancelAll()
244
245
  }
245
246
 
247
+ @ReactMethod
248
+ fun removeNotification(id: Double) {
249
+ NotificationManagerCompat.from(context).cancel(id.toInt())
250
+ }
251
+
252
+ @ReactMethod
253
+ fun removeGroupedNotifications(group: String) {
254
+ val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
255
+ val active = if (Build.VERSION.SDK_INT >= 23) manager?.activeNotifications else null
256
+ if (active == null) {
257
+ // No way to enumerate what is showing on this API level — the group id doubles as a
258
+ // notification id for single-notification groups, so cancel by tag as a best effort.
259
+ NotificationManagerCompat.from(context).cancel(group, 0)
260
+ return
261
+ }
262
+ for (notification in active) {
263
+ if (notification.notification?.group == group) {
264
+ NotificationManagerCompat.from(context).cancel(notification.tag, notification.id)
265
+ }
266
+ }
267
+ }
268
+
269
+ // OneSignal's OSNotificationPermission: 0 not determined, 1 denied, 2 authorized
270
+ @ReactMethod
271
+ fun permissionNative(promise: Promise) {
272
+ if (NotificationManagerCompat.from(context).areNotificationsEnabled()) {
273
+ promise.resolve(2)
274
+ return
275
+ }
276
+ if (Build.VERSION.SDK_INT >= 33 &&
277
+ context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
278
+ ) {
279
+ promise.resolve(1)
280
+ return
281
+ }
282
+ promise.resolve(if (Build.VERSION.SDK_INT >= 33) 0 else 1)
283
+ }
284
+
246
285
  @ReactMethod
247
286
  fun setBadgeCount(count: Double) {
248
287
  }
package/index.d.ts CHANGED
@@ -1,4 +1,26 @@
1
- export type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'verbose';
1
+ export type LogLevelName = 'none' | 'error' | 'warn' | 'info' | 'verbose';
2
+
3
+ /** OneSignal's LogLevel enum; both the names above and these numbers are accepted. */
4
+ export declare const LogLevel: {
5
+ None: 0;
6
+ Fatal: 1;
7
+ Error: 2;
8
+ Warn: 3;
9
+ Info: 4;
10
+ Debug: 5;
11
+ Verbose: 6;
12
+ };
13
+
14
+ /** OneSignal's OSNotificationPermission enum, returned by Notifications.permissionNative(). */
15
+ export declare const NotificationPermission: {
16
+ NotDetermined: 0;
17
+ Denied: 1;
18
+ Authorized: 2;
19
+ Provisional: 3;
20
+ Ephemeral: 4;
21
+ };
22
+
23
+ export type LogLevel = LogLevelName | number;
2
24
 
3
25
  export interface InitializeOptions {
4
26
  baseUrl: string;
@@ -14,6 +36,12 @@ export interface NotificationButton {
14
36
  }
15
37
 
16
38
  export interface PushbibNotification {
39
+ /** OneSignal's name for `data`. */
40
+ additionalData: Record<string, string>;
41
+ /** OneSignal's name for `url`. */
42
+ launchURL?: string | null;
43
+ /** Puts the notification back on screen after preventDefault(); a no-op otherwise. */
44
+ display(): void;
17
45
  notificationId?: string;
18
46
  channelId?: string;
19
47
  title?: string;
@@ -28,6 +56,8 @@ export interface PushbibNotification {
28
56
 
29
57
  export interface NotificationClickEvent {
30
58
  notification: PushbibNotification;
59
+ /** OneSignal's accessor for the same object. */
60
+ getNotification(): PushbibNotification;
31
61
  result: {
32
62
  actionId: string | null;
33
63
  url: string | null;
@@ -36,11 +66,15 @@ export interface NotificationClickEvent {
36
66
 
37
67
  export interface NotificationWillDisplayEvent {
38
68
  notification: PushbibNotification;
69
+ /** OneSignal's accessor for the same object. */
70
+ getNotification(): PushbibNotification;
39
71
  preventDefault(): void;
40
72
  }
41
73
 
42
74
  export interface NotificationReceivedEvent {
43
75
  notification: PushbibNotification;
76
+ /** OneSignal's accessor for the same object. */
77
+ getNotification(): PushbibNotification;
44
78
  }
45
79
 
46
80
  export interface PushSubscriptionSnapshot {
@@ -64,9 +98,20 @@ export interface MeResult {
64
98
  export type NotificationEventName = 'click' | 'received' | 'foregroundWillDisplay' | 'permissionChange';
65
99
 
66
100
  export interface NotificationsNamespace {
67
- requestPermission(): Promise<boolean>;
101
+ /** fallbackToSettings opens the app's settings page once the OS prompt is spent. */
102
+ requestPermission(fallbackToSettings?: boolean): Promise<boolean>;
68
103
  hasPermission(): Promise<boolean>;
104
+ /** OneSignal's name for hasPermission(). */
105
+ getPermissionAsync(): Promise<boolean>;
106
+ /** True while the OS prompt can still appear: not granted yet and never asked. */
107
+ canRequestPermission(): Promise<boolean>;
108
+ /** The device's native permission state as a NotificationPermission value. */
109
+ permissionNative(): Promise<number>;
69
110
  clearAll(): void;
111
+ /** Android: cancels one notification by its integer id. */
112
+ removeNotification(id: number): void;
113
+ /** Android: cancels every notification in a group. */
114
+ removeGroupedNotifications(group: string): void;
70
115
  setForegroundDisplayEnabled(enabled: boolean): Promise<void>;
71
116
  getForegroundDisplayEnabled(): Promise<boolean>;
72
117
  setBackgroundDisplayEnabled(enabled: boolean): Promise<void>;
@@ -82,6 +127,10 @@ export interface PushSubscriptionNamespace {
82
127
  getId(): Promise<string | null>;
83
128
  getToken(): Promise<string | null>;
84
129
  getOptedIn(): Promise<boolean>;
130
+ /** OneSignal's names for the three reads above. */
131
+ getIdAsync(): Promise<string | null>;
132
+ getTokenAsync(): Promise<string | null>;
133
+ getOptedInAsync(): Promise<boolean>;
85
134
  optIn(): Promise<void>;
86
135
  optOut(): Promise<void>;
87
136
  addEventListener(event: 'change', listener: (snapshot: PushSubscriptionSnapshot) => void): void;
@@ -97,6 +146,11 @@ export interface LocationNamespace {
97
146
  setLocation(latitude: number, longitude: number): Promise<void>;
98
147
  getLocation(): Promise<LocationPoint | null>;
99
148
  clearLocation(): Promise<void>;
149
+ /** Off stops setLocation() from sending and drops the point from the register payload. */
150
+ setShared(shared: boolean): Promise<void>;
151
+ isShared(): Promise<boolean>;
152
+ /** Android only: asks the OS for location permission. */
153
+ requestPermission(): Promise<boolean>;
100
154
  }
101
155
 
102
156
  export type TagScalar = string | number | boolean;
@@ -108,12 +162,23 @@ export interface UserNamespace {
108
162
  sendTag(key: string, value: TagValue): Promise<void>;
109
163
  sendTags(tags: Record<string, TagValue>): Promise<void>;
110
164
  removeTag(key: string, items?: TagScalar | TagScalar[]): Promise<void>;
111
- removeTags(keys: string[]): Promise<void>;
112
- getTags(): Record<string, string | string[]>;
165
+ removeTags(keys: string[] | string): Promise<void>;
166
+ getTags(): Promise<Record<string, string | string[]>>;
167
+ /** The synchronous read getTags() used to be. */
168
+ getTagsSync(): Record<string, string | string[]>;
169
+ /** Overrides the device locale for targeting; sent with every register/link. */
170
+ setLanguage(language: string): Promise<void>;
171
+ getLanguage(): Promise<string | null>;
113
172
  getExternalId(): Promise<string | null>;
173
+ addEventListener(event: 'change', listener: (event: UserChangedState) => void): void;
174
+ removeEventListener(event: 'change', listener: (event: UserChangedState) => void): void;
114
175
  pushSubscription: PushSubscriptionNamespace;
115
176
  }
116
177
 
178
+ export interface UserChangedState {
179
+ current: { externalId: string | null; subscriptionId: string | null };
180
+ }
181
+
117
182
  export interface LiveActivityRegisterOptions {
118
183
  activityId?: string;
119
184
  activityPushToken?: string;
@@ -167,6 +232,14 @@ export interface LiveUpdateEvent {
167
232
  export interface LiveActivitiesNamespace {
168
233
  register(options: LiveActivityRegisterOptions): Promise<LiveActivitySession>;
169
234
  end(activityId?: string): Promise<{ ended_count: number }>;
235
+ /**
236
+ * OneSignal's names. Fire-and-forget like theirs: a failure is logged and resolves to null
237
+ * instead of rejecting.
238
+ */
239
+ enter(activityId: string, token?: string, handler?: (session: LiveActivitySession | null) => void): Promise<LiveActivitySession | null>;
240
+ exit(activityId?: string, handler?: (result: { ended_count: number } | null) => void): Promise<{ ended_count: number } | null>;
241
+ setPushToStartToken(activityType: string, token: string): Promise<LiveActivitySession | null>;
242
+ removePushToStartToken(activityType?: string): Promise<{ subscription_id: string; attributes_type: string } | null>;
170
243
  getSessions(): Promise<LiveActivitySession[]>;
171
244
  addEventListener(event: 'update', handler: (event: LiveUpdateEvent) => void): void;
172
245
  removeEventListener(event: 'update', handler: (event: LiveUpdateEvent) => void): void;
@@ -213,10 +286,27 @@ export interface ChannelsNamespace {
213
286
 
214
287
  export interface PushbibStatic {
215
288
  initialize(options: InitializeOptions): void;
216
- login(externalId: string): Promise<void>;
289
+ /**
290
+ * Identify the person using the app.
291
+ *
292
+ * `identityHash` is hex(HMAC-SHA256(secret, externalId)), computed on YOUR SERVER with the
293
+ * signing secret from the app's dashboard. Required once the app has identity verification
294
+ * turned on: the app key in this bundle is readable by anyone who installs the app, so on its
295
+ * own it proves the caller has the app, not which user they are.
296
+ *
297
+ * Never ship the signing secret in the app — a signature an attacker can compute proves
298
+ * nothing.
299
+ */
300
+ login(externalId: string, identityHash?: string): Promise<void>;
217
301
  logout(): Promise<void>;
218
302
  getMe(): Promise<MeResult>;
219
303
  setLogLevel(level: LogLevel): void;
304
+ /** Same shape as OneSignal.Debug. */
305
+ Debug: {
306
+ setLogLevel(level: LogLevel): void;
307
+ /** Accepted for parity; Pushbib has no alert log. */
308
+ setAlertLevel(level: LogLevel): void;
309
+ };
220
310
  User: UserNamespace;
221
311
  Notifications: NotificationsNamespace;
222
312
  Location: LocationNamespace;
@@ -0,0 +1,40 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <!--
4
+ The Info.plist for the app's Notification Service Extension target. It lives here, in the
5
+ SDK, so an app owns no file at all: the target's INFOPLIST_FILE points straight at this
6
+ path, and an SDK upgrade carries the extension with it.
7
+
8
+ One file serves every app because every identifying value is a build setting Xcode expands
9
+ per target at build time — the bundle id, name and version all come from the app's own
10
+ target, not from here.
11
+ -->
12
+ <plist version="1.0">
13
+ <dict>
14
+ <key>CFBundleDevelopmentRegion</key>
15
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
16
+ <key>CFBundleDisplayName</key>
17
+ <string>$(PRODUCT_NAME)</string>
18
+ <key>CFBundleExecutable</key>
19
+ <string>$(EXECUTABLE_NAME)</string>
20
+ <key>CFBundleIdentifier</key>
21
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
22
+ <key>CFBundleInfoDictionaryVersion</key>
23
+ <string>6.0</string>
24
+ <key>CFBundleName</key>
25
+ <string>$(PRODUCT_NAME)</string>
26
+ <key>CFBundlePackageType</key>
27
+ <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
28
+ <key>CFBundleShortVersionString</key>
29
+ <string>$(MARKETING_VERSION)</string>
30
+ <key>CFBundleVersion</key>
31
+ <string>$(CURRENT_PROJECT_VERSION)</string>
32
+ <key>NSExtension</key>
33
+ <dict>
34
+ <key>NSExtensionPointIdentifier</key>
35
+ <string>com.apple.usernotifications.service</string>
36
+ <key>NSExtensionPrincipalClass</key>
37
+ <string>PushbibNotificationService</string>
38
+ </dict>
39
+ </dict>
40
+ </plist>
@@ -0,0 +1,36 @@
1
+ #import <UserNotifications/UserNotifications.h>
2
+
3
+ NS_ASSUME_NONNULL_BEGIN
4
+
5
+ /// The whole iOS half of notification images, ready to use.
6
+ ///
7
+ /// iOS only puts a picture in a notification if the app ships a Notification Service
8
+ /// Extension that downloads the URL and attaches it — there is no server-side way to do it.
9
+ /// This class IS that extension: point the target's Info.plist at it and write no code.
10
+ ///
11
+ /// <key>NSExtension</key>
12
+ /// <dict>
13
+ /// <key>NSExtensionPointIdentifier</key>
14
+ /// <string>com.apple.usernotifications.service</string>
15
+ /// <key>NSExtensionPrincipalClass</key>
16
+ /// <string>PushbibNotificationService</string>
17
+ /// </dict>
18
+ ///
19
+ /// The URL is read from whichever key the send went out on: `imageUrl` for a direct APNs
20
+ /// push, `fcm_options.image` for one routed through FCM.
21
+ ///
22
+ /// Subclass it only to change something — override `willDeliverContent:` to edit the
23
+ /// notification just before it is shown, or `imageURLKeys` to read your own key — and then
24
+ /// name the subclass as the principal class instead.
25
+ @interface PushbibNotificationService : UNNotificationServiceExtension
26
+
27
+ /// Where to look for the picture, in order. Override to add your own key.
28
+ + (NSArray<NSString *> *)imageURLKeys;
29
+
30
+ /// Called once the content is final, just before it is handed to iOS. Override to add your
31
+ /// own changes; the default does nothing.
32
+ - (void)willDeliverContent:(UNMutableNotificationContent *)content;
33
+
34
+ @end
35
+
36
+ NS_ASSUME_NONNULL_END