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