@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.
- package/README.md +475 -0
- package/android/build.gradle +51 -0
- package/android/src/main/AndroidManifest.xml +15 -0
- package/android/src/main/java/com/amrshbib/pushbib/FirebaseBootstrap.kt +37 -0
- package/android/src/main/java/com/amrshbib/pushbib/LiveUpdatePayload.kt +102 -0
- package/android/src/main/java/com/amrshbib/pushbib/LiveUpdateRenderer.kt +294 -0
- package/android/src/main/java/com/amrshbib/pushbib/NotificationPayload.kt +130 -0
- package/android/src/main/java/com/amrshbib/pushbib/NotificationRenderer.kt +181 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibChannels.kt +281 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibEmitter.kt +133 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibMessagingService.kt +87 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibModule.kt +286 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibPackage.kt +14 -0
- package/index.d.ts +224 -0
- package/ios/PushbibCenterDelegate.h +16 -0
- package/ios/PushbibCenterDelegate.m +138 -0
- package/ios/PushbibEventBus.h +34 -0
- package/ios/PushbibEventBus.m +88 -0
- package/ios/PushbibLiveActivities.h +18 -0
- package/ios/PushbibLiveActivities.m +46 -0
- package/ios/PushbibModule.h +5 -0
- package/ios/PushbibModule.m +260 -0
- package/ios/PushbibSwizzler.m +135 -0
- package/package.json +40 -0
- package/react-native-pushbib.podspec +19 -0
- package/src/EventManager.js +55 -0
- package/src/Logger.js +18 -0
- package/src/NativePushbib.js +36 -0
- package/src/api.js +108 -0
- package/src/index.js +753 -0
- package/src/version.js +2 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
import { AppState, Linking, Platform } from 'react-native';
|
|
2
|
+
import { ApiClient, ApiError } from './api';
|
|
3
|
+
import { EventManager } from './EventManager';
|
|
4
|
+
import { log, setLogLevel } from './Logger';
|
|
5
|
+
import { NATIVE_EVENTS, PushbibNative, isNativeAvailable, nativeEmitter } from './NativePushbib';
|
|
6
|
+
import { SDK_NAME, SDK_VERSION } from './version';
|
|
7
|
+
|
|
8
|
+
const PREFS = {
|
|
9
|
+
subscriptionId: 'subscription_id',
|
|
10
|
+
externalId: 'external_id',
|
|
11
|
+
optedOut: 'opted_out',
|
|
12
|
+
tags: 'tags_cache',
|
|
13
|
+
config: 'config_cache',
|
|
14
|
+
channels: 'channels_cache',
|
|
15
|
+
location: 'location_point',
|
|
16
|
+
deviceId: 'device_id',
|
|
17
|
+
showForeground: 'show_foreground',
|
|
18
|
+
showBackground: 'show_background',
|
|
19
|
+
showLiveUpdate: 'show_live_update',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const SESSION_PING_MIN_INTERVAL_MS = 30 * 1000;
|
|
23
|
+
const REGISTER_RETRY_DELAYS_MS = [2000, 5000, 15000, 30000];
|
|
24
|
+
|
|
25
|
+
const BAD_DEVICE_IDS = new Set(['', '0', '0000000000000000', '9774d56d682e549c', 'unknown', 'null', 'undefined']);
|
|
26
|
+
|
|
27
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
28
|
+
|
|
29
|
+
function uuidv4() {
|
|
30
|
+
const bytes = new Uint8Array(16);
|
|
31
|
+
const g = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
32
|
+
if (g && typeof g.getRandomValues === 'function') {
|
|
33
|
+
g.getRandomValues(bytes);
|
|
34
|
+
} else {
|
|
35
|
+
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
36
|
+
}
|
|
37
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
38
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
39
|
+
const hex = [];
|
|
40
|
+
for (let i = 0; i < 16; i++) hex.push(bytes[i].toString(16).padStart(2, '0'));
|
|
41
|
+
return (
|
|
42
|
+
hex.slice(0, 4).join('') + '-' + hex.slice(4, 6).join('') + '-' +
|
|
43
|
+
hex.slice(6, 8).join('') + '-' + hex.slice(8, 10).join('') + '-' +
|
|
44
|
+
hex.slice(10, 16).join('')
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
class PushbibSdk {
|
|
49
|
+
constructor() {
|
|
50
|
+
this._events = new EventManager();
|
|
51
|
+
this._api = new ApiClient();
|
|
52
|
+
this._options = null;
|
|
53
|
+
this._deviceInfo = null;
|
|
54
|
+
this._deviceId = null;
|
|
55
|
+
this._state = {
|
|
56
|
+
subscriptionId: null,
|
|
57
|
+
externalId: null,
|
|
58
|
+
pushToken: null,
|
|
59
|
+
optedOut: false,
|
|
60
|
+
registered: false,
|
|
61
|
+
tags: {},
|
|
62
|
+
location: null,
|
|
63
|
+
};
|
|
64
|
+
this._needsRegister = false;
|
|
65
|
+
this._lastSessionPingAt = 0;
|
|
66
|
+
this._lastPermission = null;
|
|
67
|
+
this._ready = new Promise((resolve, reject) => {
|
|
68
|
+
this._readyResolve = resolve;
|
|
69
|
+
this._readyReject = reject;
|
|
70
|
+
});
|
|
71
|
+
this._queue = Promise.resolve();
|
|
72
|
+
|
|
73
|
+
this.User = this._buildUserNamespace();
|
|
74
|
+
this.Notifications = this._buildNotificationsNamespace();
|
|
75
|
+
this.Location = this._buildLocationNamespace();
|
|
76
|
+
this.LiveActivities = this._buildLiveActivitiesNamespace();
|
|
77
|
+
this.Channels = this._buildChannelsNamespace();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
initialize(options) {
|
|
81
|
+
if (this._options) {
|
|
82
|
+
log.warn('initialize() called twice — ignoring the second call.');
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const { baseUrl, appId, appKey } = options || {};
|
|
86
|
+
if (!baseUrl || !appId || !appKey) {
|
|
87
|
+
throw new Error('Pushbib.initialize requires { baseUrl, appId, appKey }');
|
|
88
|
+
}
|
|
89
|
+
if (options.logLevel) setLogLevel(options.logLevel);
|
|
90
|
+
this._options = { autoOpenLaunchUrls: true, ...options };
|
|
91
|
+
|
|
92
|
+
this._start()
|
|
93
|
+
.then(() => this._readyResolve())
|
|
94
|
+
.catch((e) => {
|
|
95
|
+
log.error('initialize failed:', e.message || e);
|
|
96
|
+
this._readyReject(e);
|
|
97
|
+
});
|
|
98
|
+
this._ready.catch(() => {});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
login(externalId) {
|
|
102
|
+
if (typeof externalId !== 'string' || externalId.length === 0) {
|
|
103
|
+
throw new Error('Pushbib.login(externalId) requires a non-empty string');
|
|
104
|
+
}
|
|
105
|
+
return this._enqueue(async () => {
|
|
106
|
+
this._state.externalId = externalId;
|
|
107
|
+
await this._prefsSet(PREFS.externalId, externalId);
|
|
108
|
+
if (this._state.subscriptionId) {
|
|
109
|
+
await this._api.link({
|
|
110
|
+
external_id: externalId,
|
|
111
|
+
subscription_id: this._state.subscriptionId,
|
|
112
|
+
...this._deviceHints(),
|
|
113
|
+
});
|
|
114
|
+
log.info(`logged in as "${externalId}"`);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
logout() {
|
|
120
|
+
return this._enqueue(async () => {
|
|
121
|
+
const { externalId, subscriptionId } = this._state;
|
|
122
|
+
this._state.externalId = null;
|
|
123
|
+
await this._prefsSet(PREFS.externalId, null);
|
|
124
|
+
if (externalId && subscriptionId) {
|
|
125
|
+
await this._api
|
|
126
|
+
.unlink({ external_id: externalId, subscription_id: subscriptionId })
|
|
127
|
+
.catch((e) => {
|
|
128
|
+
if (!(e instanceof ApiError && e.status === 404)) throw e;
|
|
129
|
+
});
|
|
130
|
+
log.info(`logged out "${externalId}"`);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
getMe() {
|
|
136
|
+
return this._enqueue(async () => {
|
|
137
|
+
if (!this._state.externalId) throw new Error('getMe() requires login() first');
|
|
138
|
+
const res = await this._api.me({ external_id: this._state.externalId });
|
|
139
|
+
return res.data;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
setLogLevel(level) {
|
|
144
|
+
setLogLevel(level);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
_buildUserNamespace() {
|
|
148
|
+
const sdk = this;
|
|
149
|
+
return {
|
|
150
|
+
addTag(key, value) {
|
|
151
|
+
return sdk.User.addTags({ [key]: value });
|
|
152
|
+
},
|
|
153
|
+
addTags(tags) {
|
|
154
|
+
if (!tags || typeof tags !== 'object' || Object.keys(tags).length === 0) {
|
|
155
|
+
throw new Error('User.addTags requires a non-empty object');
|
|
156
|
+
}
|
|
157
|
+
return sdk._enqueue(async () => {
|
|
158
|
+
for (const [k, v] of Object.entries(tags)) sdk._state.tags[k] = String(v);
|
|
159
|
+
await sdk._prefsSet(PREFS.tags, JSON.stringify(sdk._state.tags));
|
|
160
|
+
await sdk._api.addTags({ ...sdk._tagTarget(), tags });
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
removeTag(key) {
|
|
164
|
+
return sdk.User.removeTags([key]);
|
|
165
|
+
},
|
|
166
|
+
removeTags(keys) {
|
|
167
|
+
if (!Array.isArray(keys) || keys.length === 0) {
|
|
168
|
+
throw new Error('User.removeTags requires a non-empty array of keys');
|
|
169
|
+
}
|
|
170
|
+
return sdk._enqueue(async () => {
|
|
171
|
+
for (const k of keys) delete sdk._state.tags[k];
|
|
172
|
+
await sdk._prefsSet(PREFS.tags, JSON.stringify(sdk._state.tags));
|
|
173
|
+
await sdk._api.removeTags({ ...sdk._tagTarget(), tags: keys });
|
|
174
|
+
});
|
|
175
|
+
},
|
|
176
|
+
getTags() {
|
|
177
|
+
return { ...sdk._state.tags };
|
|
178
|
+
},
|
|
179
|
+
async getExternalId() {
|
|
180
|
+
await sdk._ready.catch(() => {});
|
|
181
|
+
return sdk._state.externalId;
|
|
182
|
+
},
|
|
183
|
+
pushSubscription: {
|
|
184
|
+
async getId() {
|
|
185
|
+
await sdk._ready.catch(() => {});
|
|
186
|
+
return sdk._state.subscriptionId;
|
|
187
|
+
},
|
|
188
|
+
async getToken() {
|
|
189
|
+
await sdk._ready.catch(() => {});
|
|
190
|
+
return sdk._state.pushToken;
|
|
191
|
+
},
|
|
192
|
+
async getOptedIn() {
|
|
193
|
+
await sdk._ready.catch(() => {});
|
|
194
|
+
return !sdk._state.optedOut && sdk._state.registered;
|
|
195
|
+
},
|
|
196
|
+
optIn() {
|
|
197
|
+
return sdk._enqueue(async () => {
|
|
198
|
+
sdk._state.optedOut = false;
|
|
199
|
+
await sdk._prefsSet(PREFS.optedOut, null);
|
|
200
|
+
await sdk._registerWithRetry();
|
|
201
|
+
sdk._events.emit('pushSubscriptionChange', await sdk._subscriptionSnapshot());
|
|
202
|
+
});
|
|
203
|
+
},
|
|
204
|
+
optOut() {
|
|
205
|
+
return sdk._enqueue(async () => {
|
|
206
|
+
sdk._state.optedOut = true;
|
|
207
|
+
await sdk._prefsSet(PREFS.optedOut, '1');
|
|
208
|
+
if (sdk._state.subscriptionId) {
|
|
209
|
+
await sdk._api
|
|
210
|
+
.unregisterDevice({ subscription_id: sdk._state.subscriptionId })
|
|
211
|
+
.catch((e) => log.warn('optOut sync failed (will stay opted-out locally):', e.message));
|
|
212
|
+
}
|
|
213
|
+
sdk._state.registered = false;
|
|
214
|
+
sdk._events.emit('pushSubscriptionChange', await sdk._subscriptionSnapshot());
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
addEventListener(event, handler) {
|
|
218
|
+
if (event !== 'change') throw new Error('pushSubscription supports only the "change" event');
|
|
219
|
+
sdk._events.add('pushSubscriptionChange', handler);
|
|
220
|
+
},
|
|
221
|
+
removeEventListener(event, handler) {
|
|
222
|
+
sdk._events.remove('pushSubscriptionChange', handler);
|
|
223
|
+
},
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
_buildLocationNamespace() {
|
|
229
|
+
const sdk = this;
|
|
230
|
+
return {
|
|
231
|
+
setLocation(latitude, longitude) {
|
|
232
|
+
const lat = Number(latitude);
|
|
233
|
+
const long = Number(longitude);
|
|
234
|
+
if (!Number.isFinite(lat) || !Number.isFinite(long)) {
|
|
235
|
+
throw new Error('Pushbib.Location.setLocation(latitude, longitude) requires two numbers');
|
|
236
|
+
}
|
|
237
|
+
if (lat < -90 || lat > 90 || long < -180 || long > 180) {
|
|
238
|
+
throw new Error(`Pushbib.Location.setLocation: coordinates out of range (${lat}, ${long})`);
|
|
239
|
+
}
|
|
240
|
+
return sdk._enqueue(async () => {
|
|
241
|
+
sdk._state.location = { lat, long };
|
|
242
|
+
await sdk._prefsSet(PREFS.location, JSON.stringify(sdk._state.location));
|
|
243
|
+
if (!sdk._state.subscriptionId) return;
|
|
244
|
+
await sdk._api.setLocation({ subscription_id: sdk._state.subscriptionId, lat, long });
|
|
245
|
+
log.info(`location set (${lat}, ${long})`);
|
|
246
|
+
});
|
|
247
|
+
},
|
|
248
|
+
async getLocation() {
|
|
249
|
+
await sdk._ready.catch(() => {});
|
|
250
|
+
return sdk._state.location ? { ...sdk._state.location } : null;
|
|
251
|
+
},
|
|
252
|
+
clearLocation() {
|
|
253
|
+
return sdk._enqueue(async () => {
|
|
254
|
+
sdk._state.location = null;
|
|
255
|
+
await sdk._prefsSet(PREFS.location, null);
|
|
256
|
+
if (!sdk._state.subscriptionId) return;
|
|
257
|
+
await sdk._api
|
|
258
|
+
.clearLocation({ subscription_id: sdk._state.subscriptionId })
|
|
259
|
+
.catch((e) => {
|
|
260
|
+
if (!(e instanceof ApiError && e.status === 404)) throw e;
|
|
261
|
+
});
|
|
262
|
+
log.info('location cleared');
|
|
263
|
+
});
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
_buildLiveActivitiesNamespace() {
|
|
269
|
+
const sdk = this;
|
|
270
|
+
return {
|
|
271
|
+
register(options) {
|
|
272
|
+
const o = options || {};
|
|
273
|
+
if (!o.activityId && !o.pushToStartToken) {
|
|
274
|
+
throw new Error(
|
|
275
|
+
'Pushbib.LiveActivities.register requires activityId, or a pushToStartToken to store for later remote start',
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
return sdk._enqueue(async () => {
|
|
279
|
+
if (!sdk._state.subscriptionId) {
|
|
280
|
+
throw new Error('LiveActivities.register requires a registered device — no subscription yet');
|
|
281
|
+
}
|
|
282
|
+
const res = await sdk._api.registerLiveActivity({
|
|
283
|
+
subscription_id: sdk._state.subscriptionId,
|
|
284
|
+
platform: Platform.OS,
|
|
285
|
+
...(o.activityId ? { activity_id: o.activityId } : {}),
|
|
286
|
+
...(o.activityPushToken ? { activity_push_token: o.activityPushToken } : {}),
|
|
287
|
+
...(o.pushToStartToken ? { push_to_start_token: o.pushToStartToken } : {}),
|
|
288
|
+
...(o.attributesType ? { attributes_type: o.attributesType } : {}),
|
|
289
|
+
...(Number.isInteger(o.notificationId) ? { notification_id: o.notificationId } : {}),
|
|
290
|
+
...(Number.isFinite(o.expiresIn) ? { expires_in: Math.floor(o.expiresIn) } : {}),
|
|
291
|
+
...(sdk._state.externalId ? { external_id: sdk._state.externalId } : {}),
|
|
292
|
+
});
|
|
293
|
+
log.info(
|
|
294
|
+
o.activityId
|
|
295
|
+
? `live activity registered (${o.activityId})`
|
|
296
|
+
: `push-to-start token registered (${o.attributesType || 'default'})`,
|
|
297
|
+
);
|
|
298
|
+
return res.data;
|
|
299
|
+
});
|
|
300
|
+
},
|
|
301
|
+
|
|
302
|
+
end(activityId) {
|
|
303
|
+
return sdk._enqueue(async () => {
|
|
304
|
+
if (!sdk._state.subscriptionId) return { ended_count: 0 };
|
|
305
|
+
const res = await sdk._api
|
|
306
|
+
.endLiveActivity({
|
|
307
|
+
subscription_id: sdk._state.subscriptionId,
|
|
308
|
+
...(activityId ? { activity_id: activityId } : {}),
|
|
309
|
+
})
|
|
310
|
+
.catch((e) => {
|
|
311
|
+
if (e instanceof ApiError && e.status === 404) return { data: { ended_count: 0 } };
|
|
312
|
+
throw e;
|
|
313
|
+
});
|
|
314
|
+
return res.data;
|
|
315
|
+
});
|
|
316
|
+
},
|
|
317
|
+
|
|
318
|
+
getSessions() {
|
|
319
|
+
return sdk._enqueue(async () => {
|
|
320
|
+
if (!sdk._state.subscriptionId) return [];
|
|
321
|
+
const res = await sdk._api.liveActivitySessions(sdk._state.subscriptionId);
|
|
322
|
+
return res.data?.sessions || [];
|
|
323
|
+
});
|
|
324
|
+
},
|
|
325
|
+
|
|
326
|
+
addEventListener(event, handler) {
|
|
327
|
+
if (event !== 'update') {
|
|
328
|
+
throw new Error('LiveActivities supports only the "update" event');
|
|
329
|
+
}
|
|
330
|
+
sdk._events.add('liveUpdate', handler);
|
|
331
|
+
},
|
|
332
|
+
removeEventListener(event, handler) {
|
|
333
|
+
sdk._events.remove('liveUpdate', handler);
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
_buildNotificationsNamespace() {
|
|
339
|
+
const sdk = this;
|
|
340
|
+
return {
|
|
341
|
+
async requestPermission() {
|
|
342
|
+
if (sdk._options) await sdk._ready.catch(() => {});
|
|
343
|
+
const granted = await PushbibNative.requestPermission();
|
|
344
|
+
sdk._notifyPermission(granted);
|
|
345
|
+
return granted;
|
|
346
|
+
},
|
|
347
|
+
hasPermission() {
|
|
348
|
+
return PushbibNative.hasPermission();
|
|
349
|
+
},
|
|
350
|
+
clearAll() {
|
|
351
|
+
PushbibNative.clearAllNotifications();
|
|
352
|
+
},
|
|
353
|
+
async setForegroundDisplayEnabled(enabled) {
|
|
354
|
+
if (sdk._options) await sdk._ready.catch(() => {});
|
|
355
|
+
await sdk._prefsSet(PREFS.showForeground, enabled ? null : '0');
|
|
356
|
+
},
|
|
357
|
+
async getForegroundDisplayEnabled() {
|
|
358
|
+
if (sdk._options) await sdk._ready.catch(() => {});
|
|
359
|
+
return (await sdk._prefsGet(PREFS.showForeground)) !== '0';
|
|
360
|
+
},
|
|
361
|
+
async setBackgroundDisplayEnabled(enabled) {
|
|
362
|
+
if (sdk._options) await sdk._ready.catch(() => {});
|
|
363
|
+
await sdk._prefsSet(PREFS.showBackground, enabled ? null : '0');
|
|
364
|
+
},
|
|
365
|
+
async getBackgroundDisplayEnabled() {
|
|
366
|
+
if (sdk._options) await sdk._ready.catch(() => {});
|
|
367
|
+
return (await sdk._prefsGet(PREFS.showBackground)) !== '0';
|
|
368
|
+
},
|
|
369
|
+
async setLiveUpdateDisplayEnabled(enabled) {
|
|
370
|
+
if (sdk._options) await sdk._ready.catch(() => {});
|
|
371
|
+
await sdk._prefsSet(PREFS.showLiveUpdate, enabled ? null : '0');
|
|
372
|
+
},
|
|
373
|
+
async getLiveUpdateDisplayEnabled() {
|
|
374
|
+
if (sdk._options) await sdk._ready.catch(() => {});
|
|
375
|
+
return (await sdk._prefsGet(PREFS.showLiveUpdate)) !== '0';
|
|
376
|
+
},
|
|
377
|
+
addEventListener(event, handler) {
|
|
378
|
+
sdk._events.add(event, handler);
|
|
379
|
+
if (event === 'foregroundWillDisplay' && isNativeAvailable) {
|
|
380
|
+
PushbibNative.setForegroundHandling(true);
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
removeEventListener(event, handler) {
|
|
384
|
+
sdk._events.remove(event, handler);
|
|
385
|
+
if (event === 'foregroundWillDisplay' && isNativeAvailable && sdk._events.count(event) === 0) {
|
|
386
|
+
PushbibNative.setForegroundHandling(false);
|
|
387
|
+
}
|
|
388
|
+
},
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async _start() {
|
|
393
|
+
this._deviceInfo = await PushbibNative.getDeviceInfo();
|
|
394
|
+
this._deviceId = await this._resolveDeviceId();
|
|
395
|
+
this._api.configure({
|
|
396
|
+
baseUrl: this._options.baseUrl,
|
|
397
|
+
appId: this._options.appId,
|
|
398
|
+
appKey: this._options.appKey,
|
|
399
|
+
bundleId: this._deviceInfo.bundleId,
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
const [sub, ext, opted, tags, location] = await Promise.all([
|
|
403
|
+
this._prefsGet(PREFS.subscriptionId),
|
|
404
|
+
this._prefsGet(PREFS.externalId),
|
|
405
|
+
this._prefsGet(PREFS.optedOut),
|
|
406
|
+
this._prefsGet(PREFS.tags),
|
|
407
|
+
this._prefsGet(PREFS.location),
|
|
408
|
+
]);
|
|
409
|
+
this._state.subscriptionId = sub || null;
|
|
410
|
+
this._state.externalId = ext || null;
|
|
411
|
+
this._state.optedOut = opted === '1';
|
|
412
|
+
try {
|
|
413
|
+
this._state.tags = tags ? JSON.parse(tags) : {};
|
|
414
|
+
} catch (e) {
|
|
415
|
+
this._state.tags = {};
|
|
416
|
+
}
|
|
417
|
+
try {
|
|
418
|
+
const parsed = location ? JSON.parse(location) : null;
|
|
419
|
+
this._state.location =
|
|
420
|
+
parsed && Number.isFinite(parsed.lat) && Number.isFinite(parsed.long) ? parsed : null;
|
|
421
|
+
} catch (e) {
|
|
422
|
+
this._state.location = null;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
this._attachNativeListeners();
|
|
426
|
+
|
|
427
|
+
const initialClick = await PushbibNative.getInitialClickEvent().catch(() => null);
|
|
428
|
+
if (initialClick) this._handleClick(typeof initialClick === 'string' ? JSON.parse(initialClick) : initialClick);
|
|
429
|
+
|
|
430
|
+
const config = await this._loadConfig();
|
|
431
|
+
await this._syncChannels(config);
|
|
432
|
+
|
|
433
|
+
let androidConfigJson = null;
|
|
434
|
+
if (Platform.OS === 'android') {
|
|
435
|
+
if (!config || !config.android) {
|
|
436
|
+
throw new Error(
|
|
437
|
+
'The server returned no Android push identity for this app — open App Settings in the dashboard ' +
|
|
438
|
+
'and run "Detect from service account". No file is needed here or in the app.',
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
androidConfigJson = JSON.stringify(config.android);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
try {
|
|
445
|
+
this._state.pushToken = await PushbibNative.getPushToken(androidConfigJson);
|
|
446
|
+
} catch (e) {
|
|
447
|
+
log.warn('No push token available:', e.message || e);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (this._state.pushToken && !this._state.optedOut) {
|
|
451
|
+
await this._registerWithRetry();
|
|
452
|
+
} else if (this._state.optedOut) {
|
|
453
|
+
log.info('opted out — skipping registration (User.pushSubscription.optIn() resumes)');
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
this._lastPermission = await PushbibNative.hasPermission().catch(() => null);
|
|
457
|
+
|
|
458
|
+
this._watchAppState();
|
|
459
|
+
log.info(`ready (sdk ${SDK_VERSION}, platform ${Platform.OS})`);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async _loadConfig() {
|
|
463
|
+
try {
|
|
464
|
+
const res = await this._api.getConfig();
|
|
465
|
+
await this._prefsSet(PREFS.config, JSON.stringify(res.data));
|
|
466
|
+
return res.data;
|
|
467
|
+
} catch (e) {
|
|
468
|
+
const cached = await this._prefsGet(PREFS.config);
|
|
469
|
+
if (cached) {
|
|
470
|
+
log.warn(`GET /config failed (${e.message}) — using cached config`);
|
|
471
|
+
try {
|
|
472
|
+
return JSON.parse(cached);
|
|
473
|
+
} catch (parseErr) {
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
throw e;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async _syncChannels(config) {
|
|
482
|
+
if (Platform.OS !== 'android') return 0;
|
|
483
|
+
const channels = config && Array.isArray(config.channels) ? config.channels : null;
|
|
484
|
+
if (!channels || channels.length === 0) return 0;
|
|
485
|
+
const version = (config && config.channels_version) || null;
|
|
486
|
+
try {
|
|
487
|
+
const created = await PushbibNative.syncChannels(JSON.stringify(channels), version);
|
|
488
|
+
await this._prefsSet(PREFS.channels, JSON.stringify({ version, channels }));
|
|
489
|
+
if (created > 0) log.info(`synced ${created} notification channel(s)`);
|
|
490
|
+
return created;
|
|
491
|
+
} catch (e) {
|
|
492
|
+
log.warn(`channel sync failed (${e.message || e}) — the default channel still works`);
|
|
493
|
+
return 0;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
_buildChannelsNamespace() {
|
|
498
|
+
const sdk = this;
|
|
499
|
+
return {
|
|
500
|
+
async sync() {
|
|
501
|
+
await sdk._ready.catch(() => {});
|
|
502
|
+
const config = await sdk._loadConfig().catch(() => null);
|
|
503
|
+
return sdk._syncChannels(config);
|
|
504
|
+
},
|
|
505
|
+
async list() {
|
|
506
|
+
await sdk._ready.catch(() => {});
|
|
507
|
+
if (Platform.OS !== 'android') return [];
|
|
508
|
+
try {
|
|
509
|
+
return JSON.parse(await PushbibNative.listChannels());
|
|
510
|
+
} catch (e) {
|
|
511
|
+
return [];
|
|
512
|
+
}
|
|
513
|
+
},
|
|
514
|
+
async definitions() {
|
|
515
|
+
await sdk._ready.catch(() => {});
|
|
516
|
+
const cached = await sdk._prefsGet(PREFS.channels);
|
|
517
|
+
if (!cached) return [];
|
|
518
|
+
try {
|
|
519
|
+
return JSON.parse(cached).channels || [];
|
|
520
|
+
} catch (e) {
|
|
521
|
+
return [];
|
|
522
|
+
}
|
|
523
|
+
},
|
|
524
|
+
async openSettings(key) {
|
|
525
|
+
await sdk._ready.catch(() => {});
|
|
526
|
+
const wanted = key ? String(key) : null;
|
|
527
|
+
let channelId = wanted;
|
|
528
|
+
if (wanted && Platform.OS === 'android') {
|
|
529
|
+
const known = await this.definitions();
|
|
530
|
+
const match = known.find((c) => c.key === wanted || c.runtime_id === wanted || c.runtimeId === wanted);
|
|
531
|
+
if (match) channelId = match.runtime_id || match.runtimeId || match.native_id || match.nativeId;
|
|
532
|
+
}
|
|
533
|
+
return PushbibNative.openChannelSettings(channelId);
|
|
534
|
+
},
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
_attachNativeListeners() {
|
|
539
|
+
if (!nativeEmitter) return;
|
|
540
|
+
|
|
541
|
+
nativeEmitter.addListener(NATIVE_EVENTS.pushToken, ({ token }) => {
|
|
542
|
+
if (!token || token === this._state.pushToken) return;
|
|
543
|
+
log.info('push token rotated — re-registering');
|
|
544
|
+
this._state.pushToken = token;
|
|
545
|
+
if (!this._state.optedOut) {
|
|
546
|
+
this._enqueue(() => this._registerWithRetry()).catch(() => {});
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
nativeEmitter.addListener(NATIVE_EVENTS.click, (raw) => this._handleClick(raw));
|
|
551
|
+
|
|
552
|
+
nativeEmitter.addListener(NATIVE_EVENTS.received, (raw) => {
|
|
553
|
+
this._events.emit('received', { notification: raw.notification || {} });
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
if (Platform.OS === 'android') {
|
|
557
|
+
nativeEmitter.addListener(NATIVE_EVENTS.liveUpdate, (raw) => {
|
|
558
|
+
this._events.emit('liveUpdate', { liveUpdate: raw.liveUpdate || {} });
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (Platform.OS === 'ios') {
|
|
563
|
+
nativeEmitter.addListener(NATIVE_EVENTS.liveActivityToken, (raw) => {
|
|
564
|
+
const { token, activityId, attributesType, kind } = raw || {};
|
|
565
|
+
if (!token) return;
|
|
566
|
+
const isPushToStart = kind === 'pushToStart';
|
|
567
|
+
this.LiveActivities.register({
|
|
568
|
+
...(activityId ? { activityId } : {}),
|
|
569
|
+
...(attributesType ? { attributesType } : {}),
|
|
570
|
+
...(isPushToStart ? { pushToStartToken: token } : { activityPushToken: token }),
|
|
571
|
+
}).catch((e) => log.warn(`live activity token registration failed: ${e.message}`));
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
nativeEmitter.addListener(NATIVE_EVENTS.foregroundWillDisplay, (raw) => {
|
|
576
|
+
let prevented = false;
|
|
577
|
+
const delivered = this._events.emit('foregroundWillDisplay', {
|
|
578
|
+
notification: raw.notification,
|
|
579
|
+
preventDefault: () => {
|
|
580
|
+
prevented = true;
|
|
581
|
+
},
|
|
582
|
+
});
|
|
583
|
+
PushbibNative.completeNotificationDisplay(raw.completionId, !(delivered && prevented));
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
_handleClick(raw) {
|
|
588
|
+
const notification = raw.notification || {};
|
|
589
|
+
const actionId = raw.actionId || null;
|
|
590
|
+
const url = notification.url || null;
|
|
591
|
+
this._events.emit('click', { notification, result: { actionId, url } });
|
|
592
|
+
if (url && this._options?.autoOpenLaunchUrls) {
|
|
593
|
+
Linking.openURL(url).catch((e) => log.warn(`could not open launch URL "${url}": ${e.message}`));
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
_watchAppState() {
|
|
598
|
+
AppState.addEventListener('change', (state) => {
|
|
599
|
+
if (state !== 'active') return;
|
|
600
|
+
this._onForeground().catch((e) => log.verbose('foreground hook error:', e.message));
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async _onForeground() {
|
|
605
|
+
const granted = await PushbibNative.hasPermission().catch(() => null);
|
|
606
|
+
if (granted !== null) this._notifyPermission(granted);
|
|
607
|
+
|
|
608
|
+
if (this._state.optedOut) return;
|
|
609
|
+
if (this._needsRegister || !this._state.registered) {
|
|
610
|
+
await this._registerWithRetry(1);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
const now = Date.now();
|
|
614
|
+
if (this._state.subscriptionId && now - this._lastSessionPingAt > SESSION_PING_MIN_INTERVAL_MS) {
|
|
615
|
+
this._lastSessionPingAt = now;
|
|
616
|
+
await this._api
|
|
617
|
+
.pingSession({ subscription_id: this._state.subscriptionId })
|
|
618
|
+
.catch((e) => log.verbose('session ping failed:', e.message));
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
async _registerWithRetry(maxAttempts = REGISTER_RETRY_DELAYS_MS.length + 1) {
|
|
623
|
+
if (!this._state.pushToken) {
|
|
624
|
+
try {
|
|
625
|
+
this._state.pushToken = await PushbibNative.getPushToken(null);
|
|
626
|
+
} catch (e) {
|
|
627
|
+
this._needsRegister = true;
|
|
628
|
+
log.warn('register skipped — still no push token:', e.message || e);
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
633
|
+
try {
|
|
634
|
+
await this._register();
|
|
635
|
+
this._needsRegister = false;
|
|
636
|
+
return;
|
|
637
|
+
} catch (e) {
|
|
638
|
+
const retriable = e instanceof ApiError && (e.status === 0 || e.status >= 500 || e.status === 429);
|
|
639
|
+
log.warn(`register attempt ${attempt + 1} failed: ${e.message}`);
|
|
640
|
+
if (!retriable || attempt === maxAttempts - 1) {
|
|
641
|
+
this._needsRegister = true;
|
|
642
|
+
if (!retriable) throw e;
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
await sleep(REGISTER_RETRY_DELAYS_MS[attempt]);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
async _resolveDeviceId() {
|
|
651
|
+
const stored = await this._prefsGet(PREFS.deviceId);
|
|
652
|
+
if (stored) return stored;
|
|
653
|
+
|
|
654
|
+
let nativeId = null;
|
|
655
|
+
if (isNativeAvailable && typeof PushbibNative.getStableDeviceId === 'function') {
|
|
656
|
+
try {
|
|
657
|
+
nativeId = await PushbibNative.getStableDeviceId();
|
|
658
|
+
} catch (e) {
|
|
659
|
+
log.verbose('getStableDeviceId failed, falling back:', e.message || e);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (nativeId) {
|
|
663
|
+
await this._prefsSet(PREFS.deviceId, nativeId);
|
|
664
|
+
log.info('device id resolved (native stable)');
|
|
665
|
+
return nativeId;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const hw = this._deviceInfo?.deviceId;
|
|
669
|
+
const usableHw = hw && !BAD_DEVICE_IDS.has(String(hw).trim().toLowerCase());
|
|
670
|
+
const chosen = usableHw ? String(hw).trim().slice(0, 128) : `nfd-${uuidv4()}`;
|
|
671
|
+
await this._prefsSet(PREFS.deviceId, chosen);
|
|
672
|
+
log.info(`device id resolved (${usableHw ? 'hardware' : 'generated'})`);
|
|
673
|
+
return chosen;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
async _register() {
|
|
677
|
+
if (!this._deviceId) this._deviceId = await this._resolveDeviceId();
|
|
678
|
+
const payload = {
|
|
679
|
+
token: this._state.pushToken,
|
|
680
|
+
platform: Platform.OS,
|
|
681
|
+
sdk: SDK_NAME,
|
|
682
|
+
device_id: this._deviceId,
|
|
683
|
+
...(this._state.subscriptionId ? { subscription_id: this._state.subscriptionId } : {}),
|
|
684
|
+
...(this._state.externalId ? { external_id: this._state.externalId } : {}),
|
|
685
|
+
...(Object.keys(this._state.tags).length > 0 ? { tags: this._state.tags } : {}),
|
|
686
|
+
...(this._state.location
|
|
687
|
+
? { lat: this._state.location.lat, long: this._state.location.long }
|
|
688
|
+
: {}),
|
|
689
|
+
...this._deviceHints(),
|
|
690
|
+
};
|
|
691
|
+
const res = await this._api.registerDevice(payload);
|
|
692
|
+
const previousId = this._state.subscriptionId;
|
|
693
|
+
this._state.subscriptionId = res.data.subscription_id;
|
|
694
|
+
this._state.registered = true;
|
|
695
|
+
if (res.data.subscription_id !== previousId) {
|
|
696
|
+
await this._prefsSet(PREFS.subscriptionId, res.data.subscription_id);
|
|
697
|
+
}
|
|
698
|
+
log.info(`registered (subscription ${res.data.subscription_id})`);
|
|
699
|
+
this._events.emit('pushSubscriptionChange', await this._subscriptionSnapshot());
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
_deviceHints() {
|
|
703
|
+
const info = this._deviceInfo || {};
|
|
704
|
+
return {
|
|
705
|
+
...(info.model ? { deviceModel: String(info.model).slice(0, 128) } : {}),
|
|
706
|
+
...(info.osVersion ? { deviceOs: `${info.osName || Platform.OS} ${info.osVersion}`.slice(0, 64) } : {}),
|
|
707
|
+
...(info.appVersion ? { appVersion: String(info.appVersion).slice(0, 32) } : {}),
|
|
708
|
+
...(info.language ? { language: String(info.language).slice(0, 16) } : {}),
|
|
709
|
+
...(info.country ? { country: String(info.country).slice(0, 8) } : {}),
|
|
710
|
+
...(info.timezone ? { timezone: String(info.timezone).slice(0, 64) } : {}),
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
_tagTarget() {
|
|
715
|
+
return this._state.externalId
|
|
716
|
+
? { external_id: this._state.externalId }
|
|
717
|
+
: { subscription_id: this._state.subscriptionId };
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
async _subscriptionSnapshot() {
|
|
721
|
+
return {
|
|
722
|
+
id: this._state.subscriptionId,
|
|
723
|
+
token: this._state.pushToken,
|
|
724
|
+
optedIn: !this._state.optedOut && this._state.registered,
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
_notifyPermission(granted) {
|
|
729
|
+
if (this._lastPermission === granted) return;
|
|
730
|
+
this._lastPermission = granted;
|
|
731
|
+
this._events.emit('permissionChange', granted);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
_enqueue(op) {
|
|
735
|
+
if (!this._options) {
|
|
736
|
+
log.warn('Pushbib.initialize() has not been called yet — the call is queued and will run after it.');
|
|
737
|
+
}
|
|
738
|
+
const run = this._queue.then(() => this._ready).then(op);
|
|
739
|
+
this._queue = run.catch(() => {});
|
|
740
|
+
return run;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
_prefsGet(key) {
|
|
744
|
+
return PushbibNative.prefsGet(key);
|
|
745
|
+
}
|
|
746
|
+
_prefsSet(key, value) {
|
|
747
|
+
return PushbibNative.prefsSet(key, value === undefined ? null : value);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
const Pushbib = new PushbibSdk();
|
|
752
|
+
export default Pushbib;
|
|
753
|
+
export { SDK_VERSION };
|