@amrshbib/react-native-pushbib 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +475 -0
  2. package/android/build.gradle +51 -0
  3. package/android/src/main/AndroidManifest.xml +15 -0
  4. package/android/src/main/java/com/amrshbib/pushbib/FirebaseBootstrap.kt +37 -0
  5. package/android/src/main/java/com/amrshbib/pushbib/LiveUpdatePayload.kt +102 -0
  6. package/android/src/main/java/com/amrshbib/pushbib/LiveUpdateRenderer.kt +294 -0
  7. package/android/src/main/java/com/amrshbib/pushbib/NotificationPayload.kt +130 -0
  8. package/android/src/main/java/com/amrshbib/pushbib/NotificationRenderer.kt +181 -0
  9. package/android/src/main/java/com/amrshbib/pushbib/PushbibChannels.kt +281 -0
  10. package/android/src/main/java/com/amrshbib/pushbib/PushbibEmitter.kt +133 -0
  11. package/android/src/main/java/com/amrshbib/pushbib/PushbibMessagingService.kt +87 -0
  12. package/android/src/main/java/com/amrshbib/pushbib/PushbibModule.kt +286 -0
  13. package/android/src/main/java/com/amrshbib/pushbib/PushbibPackage.kt +14 -0
  14. package/index.d.ts +224 -0
  15. package/ios/PushbibCenterDelegate.h +16 -0
  16. package/ios/PushbibCenterDelegate.m +138 -0
  17. package/ios/PushbibEventBus.h +34 -0
  18. package/ios/PushbibEventBus.m +88 -0
  19. package/ios/PushbibLiveActivities.h +18 -0
  20. package/ios/PushbibLiveActivities.m +46 -0
  21. package/ios/PushbibModule.h +5 -0
  22. package/ios/PushbibModule.m +260 -0
  23. package/ios/PushbibSwizzler.m +135 -0
  24. package/package.json +40 -0
  25. package/react-native-pushbib.podspec +19 -0
  26. package/src/EventManager.js +55 -0
  27. package/src/Logger.js +18 -0
  28. package/src/NativePushbib.js +36 -0
  29. package/src/api.js +108 -0
  30. package/src/index.js +753 -0
  31. package/src/version.js +2 -0
@@ -0,0 +1,286 @@
1
+ package com.amrshbib.pushbib
2
+
3
+ import android.Manifest
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import android.content.pm.PackageManager
7
+ import android.os.Build
8
+ import android.provider.Settings
9
+ import androidx.core.app.NotificationManagerCompat
10
+ import com.facebook.react.bridge.ActivityEventListener
11
+ import com.facebook.react.bridge.Arguments
12
+ import com.facebook.react.bridge.LifecycleEventListener
13
+ import com.facebook.react.bridge.Promise
14
+ import com.facebook.react.bridge.ReactApplicationContext
15
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
16
+ import com.facebook.react.bridge.ReactMethod
17
+ import com.facebook.react.modules.core.PermissionAwareActivity
18
+ import com.facebook.react.modules.core.PermissionListener
19
+ import org.json.JSONObject
20
+ import java.util.Locale
21
+ import java.util.TimeZone
22
+
23
+ class PushbibModule(private val context: ReactApplicationContext) :
24
+ ReactContextBaseJavaModule(context), ActivityEventListener, LifecycleEventListener, PermissionListener {
25
+
26
+ companion object {
27
+ const val NAME = "Pushbib"
28
+ private const val PREFS_FILE = "pushbib_sdk"
29
+ private const val PERMISSION_REQUEST_CODE = 4471
30
+ }
31
+
32
+ private var permissionPromise: Promise? = null
33
+
34
+ init {
35
+ PushbibEmitter.reactContext = context
36
+ context.addActivityEventListener(this)
37
+ context.addLifecycleEventListener(this)
38
+ }
39
+
40
+ override fun getName() = NAME
41
+
42
+ override fun invalidate() {
43
+ context.removeActivityEventListener(this)
44
+ context.removeLifecycleEventListener(this)
45
+ PushbibEmitter.onReactContextGone(context)
46
+ super.invalidate()
47
+ }
48
+
49
+ @ReactMethod
50
+ fun addListener(eventName: String?) {
51
+ PushbibEmitter.jsListening = true
52
+ PushbibEmitter.flushQueue()
53
+ }
54
+
55
+ @ReactMethod
56
+ fun removeListeners(count: Double) {
57
+ }
58
+
59
+ @ReactMethod
60
+ fun getDeviceInfo(promise: Promise) {
61
+ val pkg = context.packageName
62
+ val appVersion = try {
63
+ context.packageManager.getPackageInfo(pkg, 0).versionName
64
+ } catch (e: Exception) {
65
+ null
66
+ }
67
+ val locale = Locale.getDefault()
68
+ val language = if (locale.country.isNullOrEmpty()) locale.language else "${locale.language}-${locale.country}"
69
+ val deviceId = try {
70
+ Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
71
+ } catch (e: Exception) {
72
+ null
73
+ }
74
+ promise.resolve(Arguments.createMap().apply {
75
+ putString("platform", "android")
76
+ putString("deviceId", deviceId)
77
+ putString("osName", "Android")
78
+ putString("osVersion", Build.VERSION.RELEASE)
79
+ putString("model", Build.MODEL)
80
+ putString("bundleId", pkg)
81
+ putString("appVersion", appVersion)
82
+ putString("language", language)
83
+ putString("country", locale.country)
84
+ putString("timezone", TimeZone.getDefault().id)
85
+ })
86
+ }
87
+
88
+ @ReactMethod
89
+ fun getStableDeviceId(promise: Promise) {
90
+ try {
91
+ val prefs = prefs()
92
+ val cached = prefs.getString("stable_device_id", null)
93
+ if (!cached.isNullOrEmpty()) {
94
+ promise.resolve(cached)
95
+ return
96
+ }
97
+ val androidId = try {
98
+ Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
99
+ } catch (e: Exception) {
100
+ null
101
+ }
102
+ val bad = setOf("", "0", "0000000000000000", "9774d56d682e549c", "unknown", "null", "undefined")
103
+ val chosen =
104
+ if (!androidId.isNullOrEmpty() && !bad.contains(androidId.lowercase(Locale.ROOT))) androidId
105
+ else "nfd-" + java.util.UUID.randomUUID().toString()
106
+ prefs.edit().putString("stable_device_id", chosen).apply()
107
+ promise.resolve(chosen)
108
+ } catch (e: Exception) {
109
+ promise.resolve(null)
110
+ }
111
+ }
112
+
113
+ @ReactMethod
114
+ fun prefsGet(key: String, promise: Promise) {
115
+ promise.resolve(prefs().getString(key, null))
116
+ }
117
+
118
+ @ReactMethod
119
+ fun prefsSet(key: String, value: String?, promise: Promise) {
120
+ prefs().edit().apply {
121
+ if (value == null) remove(key) else putString(key, value)
122
+ }.apply()
123
+ promise.resolve(null)
124
+ }
125
+
126
+ @ReactMethod
127
+ fun getPushToken(configJson: String?, promise: Promise) {
128
+ val raw = configJson
129
+ ?: prefs().getString("config_cache", null)?.let { cached ->
130
+ runCatching { JSONObject(cached).optJSONObject("android")?.toString() }.getOrNull()
131
+ }
132
+ if (raw.isNullOrEmpty()) {
133
+ promise.reject(
134
+ "pushbib/no-android-config",
135
+ "Android Firebase client config missing — upload the Firebase service-account JSON in the dashboard (App Settings).",
136
+ )
137
+ return
138
+ }
139
+ try {
140
+ val messaging = FirebaseBootstrap.messaging(context.applicationContext, JSONObject(raw))
141
+ messaging.token.addOnCompleteListener { task ->
142
+ if (task.isSuccessful && !task.result.isNullOrEmpty()) {
143
+ promise.resolve(task.result)
144
+ } else {
145
+ promise.reject(
146
+ "pushbib/token-failed",
147
+ task.exception?.message ?: "FCM getToken returned no token (is Google Play services available?)",
148
+ task.exception,
149
+ )
150
+ }
151
+ }
152
+ } catch (e: Exception) {
153
+ promise.reject("pushbib/firebase-init-failed", e.message, e)
154
+ }
155
+ }
156
+
157
+ @ReactMethod
158
+ fun syncChannels(channelsJson: String?, version: String?, promise: Promise) {
159
+ try {
160
+ promise.resolve(PushbibChannels.sync(context.applicationContext, channelsJson, version))
161
+ } catch (e: Exception) {
162
+ android.util.Log.w("Pushbib", "channel sync failed: ${e.message}")
163
+ promise.resolve(0)
164
+ }
165
+ }
166
+
167
+ @ReactMethod
168
+ fun listChannels(promise: Promise) {
169
+ try {
170
+ promise.resolve(PushbibChannels.listChannels(context.applicationContext).toString())
171
+ } catch (e: Exception) {
172
+ promise.resolve("[]")
173
+ }
174
+ }
175
+
176
+ @ReactMethod
177
+ fun openChannelSettings(channelId: String?, promise: Promise) {
178
+ try {
179
+ val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !channelId.isNullOrEmpty()) {
180
+ Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
181
+ .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
182
+ .putExtra(Settings.EXTRA_CHANNEL_ID, channelId)
183
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
184
+ Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
185
+ .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
186
+ } else {
187
+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
188
+ .setData(android.net.Uri.parse("package:${context.packageName}"))
189
+ }
190
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
191
+ (context.currentActivity ?: context).startActivity(intent)
192
+ promise.resolve(true)
193
+ } catch (e: Exception) {
194
+ promise.resolve(false)
195
+ }
196
+ }
197
+
198
+ @ReactMethod
199
+ fun hasPermission(promise: Promise) {
200
+ promise.resolve(NotificationManagerCompat.from(context).areNotificationsEnabled())
201
+ }
202
+
203
+ @ReactMethod
204
+ fun requestPermission(promise: Promise) {
205
+ if (Build.VERSION.SDK_INT < 33) {
206
+ promise.resolve(NotificationManagerCompat.from(context).areNotificationsEnabled())
207
+ return
208
+ }
209
+ if (context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
210
+ promise.resolve(true)
211
+ return
212
+ }
213
+ val activity = context.currentActivity as? PermissionAwareActivity
214
+ if (activity == null) {
215
+ promise.resolve(false)
216
+ return
217
+ }
218
+ permissionPromise = promise
219
+ activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), PERMISSION_REQUEST_CODE, this)
220
+ }
221
+
222
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray): Boolean {
223
+ if (requestCode != PERMISSION_REQUEST_CODE) return false
224
+ permissionPromise?.resolve(
225
+ grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED,
226
+ )
227
+ permissionPromise = null
228
+ return true
229
+ }
230
+
231
+ @ReactMethod
232
+ fun setForegroundHandling(enabled: Boolean) {
233
+ PushbibEmitter.foregroundHandling = enabled
234
+ }
235
+
236
+ @ReactMethod
237
+ fun completeNotificationDisplay(completionId: String, display: Boolean) {
238
+ PushbibEmitter.completeDisplay(completionId, display)
239
+ }
240
+
241
+ @ReactMethod
242
+ fun clearAllNotifications() {
243
+ NotificationManagerCompat.from(context).cancelAll()
244
+ }
245
+
246
+ @ReactMethod
247
+ fun setBadgeCount(count: Double) {
248
+ }
249
+
250
+ @ReactMethod
251
+ fun getInitialClickEvent(promise: Promise) {
252
+ promise.resolve(consumeClickFromIntent(context.currentActivity?.intent))
253
+ }
254
+
255
+ override fun onNewIntent(intent: Intent) {
256
+ val raw = consumeClickFromIntent(intent) ?: return
257
+ runCatching { PushbibEmitter.emitOrQueue(PushbibEmitter.EVENT_CLICK, JSONObject(raw)) }
258
+ }
259
+
260
+ override fun onHostResume() {
261
+ val raw = consumeClickFromIntent(context.currentActivity?.intent) ?: return
262
+ runCatching { PushbibEmitter.emitOrQueue(PushbibEmitter.EVENT_CLICK, JSONObject(raw)) }
263
+ }
264
+
265
+ override fun onHostPause() {}
266
+ override fun onHostDestroy() {}
267
+
268
+ override fun onActivityResult(activity: android.app.Activity, requestCode: Int, resultCode: Int, data: Intent?) {}
269
+
270
+ @Synchronized
271
+ private fun consumeClickFromIntent(intent: Intent?): String? {
272
+ val raw = intent?.getStringExtra(NotificationRenderer.EXTRA_EVENT) ?: return null
273
+ intent.removeExtra(NotificationRenderer.EXTRA_EVENT)
274
+ cancelClickedNotification(raw)
275
+ return raw
276
+ }
277
+
278
+ private fun cancelClickedNotification(rawEvent: String) {
279
+ runCatching {
280
+ val id = JSONObject(rawEvent).optInt("notificationId", 0)
281
+ if (id != 0) NotificationManagerCompat.from(context).cancel(id)
282
+ }
283
+ }
284
+
285
+ private fun prefs() = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)
286
+ }
@@ -0,0 +1,14 @@
1
+ package com.amrshbib.pushbib
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class PushbibPackage : ReactPackage {
9
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
10
+ listOf(PushbibModule(reactContext))
11
+
12
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> =
13
+ emptyList()
14
+ }
package/index.d.ts ADDED
@@ -0,0 +1,224 @@
1
+ export type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'verbose';
2
+
3
+ export interface InitializeOptions {
4
+ baseUrl: string;
5
+ appId: string;
6
+ appKey: string;
7
+ autoOpenLaunchUrls?: boolean;
8
+ logLevel?: LogLevel;
9
+ }
10
+
11
+ export interface NotificationButton {
12
+ id: string;
13
+ text: string;
14
+ }
15
+
16
+ export interface PushbibNotification {
17
+ notificationId?: string;
18
+ channelId?: string;
19
+ title?: string;
20
+ subtitle?: string;
21
+ body?: string;
22
+ imageUrl?: string;
23
+ largeIcon?: string;
24
+ url?: string;
25
+ buttons?: NotificationButton[];
26
+ data: Record<string, string>;
27
+ }
28
+
29
+ export interface NotificationClickEvent {
30
+ notification: PushbibNotification;
31
+ result: {
32
+ actionId: string | null;
33
+ url: string | null;
34
+ };
35
+ }
36
+
37
+ export interface NotificationWillDisplayEvent {
38
+ notification: PushbibNotification;
39
+ preventDefault(): void;
40
+ }
41
+
42
+ export interface NotificationReceivedEvent {
43
+ notification: PushbibNotification;
44
+ }
45
+
46
+ export interface PushSubscriptionSnapshot {
47
+ id: string | null;
48
+ token: string | null;
49
+ optedIn: boolean;
50
+ }
51
+
52
+ export interface MeResult {
53
+ external_id: string;
54
+ subscriptions: Array<{
55
+ subscription_id: string;
56
+ platform: string;
57
+ status: string;
58
+ subscribed: boolean;
59
+ last_active: string;
60
+ }>;
61
+ tags: Record<string, string>;
62
+ }
63
+
64
+ export type NotificationEventName = 'click' | 'received' | 'foregroundWillDisplay' | 'permissionChange';
65
+
66
+ export interface NotificationsNamespace {
67
+ requestPermission(): Promise<boolean>;
68
+ hasPermission(): Promise<boolean>;
69
+ clearAll(): void;
70
+ setForegroundDisplayEnabled(enabled: boolean): Promise<void>;
71
+ getForegroundDisplayEnabled(): Promise<boolean>;
72
+ setBackgroundDisplayEnabled(enabled: boolean): Promise<void>;
73
+ getBackgroundDisplayEnabled(): Promise<boolean>;
74
+ addEventListener(event: 'click', listener: (event: NotificationClickEvent) => void): void;
75
+ addEventListener(event: 'received', listener: (event: NotificationReceivedEvent) => void): void;
76
+ addEventListener(event: 'foregroundWillDisplay', listener: (event: NotificationWillDisplayEvent) => void): void;
77
+ addEventListener(event: 'permissionChange', listener: (granted: boolean) => void): void;
78
+ removeEventListener(event: NotificationEventName, listener: (...args: any[]) => void): void;
79
+ }
80
+
81
+ export interface PushSubscriptionNamespace {
82
+ getId(): Promise<string | null>;
83
+ getToken(): Promise<string | null>;
84
+ getOptedIn(): Promise<boolean>;
85
+ optIn(): Promise<void>;
86
+ optOut(): Promise<void>;
87
+ addEventListener(event: 'change', listener: (snapshot: PushSubscriptionSnapshot) => void): void;
88
+ removeEventListener(event: 'change', listener: (snapshot: PushSubscriptionSnapshot) => void): void;
89
+ }
90
+
91
+ export interface LocationPoint {
92
+ lat: number;
93
+ long: number;
94
+ }
95
+
96
+ export interface LocationNamespace {
97
+ setLocation(latitude: number, longitude: number): Promise<void>;
98
+ getLocation(): Promise<LocationPoint | null>;
99
+ clearLocation(): Promise<void>;
100
+ }
101
+
102
+ export interface UserNamespace {
103
+ addTag(key: string, value: string | number | boolean): Promise<void>;
104
+ addTags(tags: Record<string, string | number | boolean>): Promise<void>;
105
+ removeTag(key: string): Promise<void>;
106
+ removeTags(keys: string[]): Promise<void>;
107
+ getTags(): Record<string, string>;
108
+ getExternalId(): Promise<string | null>;
109
+ pushSubscription: PushSubscriptionNamespace;
110
+ }
111
+
112
+ export interface LiveActivityRegisterOptions {
113
+ activityId?: string;
114
+ activityPushToken?: string;
115
+ pushToStartToken?: string;
116
+ attributesType?: string;
117
+ notificationId?: number;
118
+ expiresIn?: number;
119
+ }
120
+
121
+ export interface LiveActivitySession {
122
+ activity_id: string;
123
+ session_id: string;
124
+ platform: 'ios' | 'android';
125
+ status: 'active' | 'ended' | 'expired';
126
+ attributes_type: string | null;
127
+ notification_id: number | null;
128
+ activity_token_registered: boolean;
129
+ push_to_start_registered: boolean;
130
+ last_sequence_number: number;
131
+ expires_at: string;
132
+ }
133
+
134
+ export interface LiveUpdateEvent {
135
+ liveUpdate: {
136
+ activityId: string;
137
+ action: 'START' | 'UPDATE' | 'END';
138
+ notificationId: number;
139
+ sequenceNumber: number;
140
+ streamId?: string;
141
+ alerting: boolean;
142
+ title?: string;
143
+ body?: string;
144
+ progress?: number;
145
+ indeterminate?: boolean;
146
+ staleDate?: number;
147
+ dismissalDate?: number;
148
+ contentState?: Record<string, unknown>;
149
+ data: Record<string, string>;
150
+ };
151
+ displayed: boolean;
152
+ outcome:
153
+ | 'shown'
154
+ | 'ended'
155
+ | 'notifications-disabled'
156
+ | 'stale-sequence'
157
+ | 'opted-out'
158
+ | 'notify-blocked'
159
+ | 'render-error';
160
+ }
161
+
162
+ export interface LiveActivitiesNamespace {
163
+ register(options: LiveActivityRegisterOptions): Promise<LiveActivitySession>;
164
+ end(activityId?: string): Promise<{ ended_count: number }>;
165
+ getSessions(): Promise<LiveActivitySession[]>;
166
+ addEventListener(event: 'update', handler: (event: LiveUpdateEvent) => void): void;
167
+ removeEventListener(event: 'update', handler: (event: LiveUpdateEvent) => void): void;
168
+ }
169
+
170
+ export type ChannelImportance = 'low' | 'medium' | 'high' | 'urgent';
171
+ export type ChannelVisibility = 'secret' | 'private' | 'public';
172
+ export type ChannelMode = 'off' | 'default' | 'custom';
173
+
174
+ export interface ChannelDefinition {
175
+ key: string;
176
+ runtime_id: string;
177
+ previous_runtime_id: string | null;
178
+ native_id: string | null;
179
+ name: string;
180
+ description: string | null;
181
+ is_default: boolean;
182
+ importance: ChannelImportance;
183
+ sound: { mode: ChannelMode; name?: string };
184
+ vibration: { mode: ChannelMode; pattern?: number[] };
185
+ led: { mode: ChannelMode; color?: string };
186
+ lockscreen_visibility: ChannelVisibility;
187
+ show_badge: boolean;
188
+ bypass_dnd: boolean;
189
+ group_key: string | null;
190
+ group_name: string | null;
191
+ }
192
+
193
+ export interface DeviceChannel {
194
+ id: string;
195
+ name: string | null;
196
+ importance: number;
197
+ blocked: boolean;
198
+ showBadge: boolean;
199
+ group?: string | null;
200
+ }
201
+
202
+ export interface ChannelsNamespace {
203
+ sync(): Promise<number>;
204
+ list(): Promise<DeviceChannel[]>;
205
+ definitions(): Promise<ChannelDefinition[]>;
206
+ openSettings(key?: string): Promise<boolean>;
207
+ }
208
+
209
+ export interface PushbibStatic {
210
+ initialize(options: InitializeOptions): void;
211
+ login(externalId: string): Promise<void>;
212
+ logout(): Promise<void>;
213
+ getMe(): Promise<MeResult>;
214
+ setLogLevel(level: LogLevel): void;
215
+ User: UserNamespace;
216
+ Notifications: NotificationsNamespace;
217
+ Location: LocationNamespace;
218
+ LiveActivities: LiveActivitiesNamespace;
219
+ Channels: ChannelsNamespace;
220
+ }
221
+
222
+ declare const Pushbib: PushbibStatic;
223
+ export default Pushbib;
224
+ export const SDK_VERSION: string;
@@ -0,0 +1,16 @@
1
+ #import <Foundation/Foundation.h>
2
+ #import <UserNotifications/UserNotifications.h>
3
+
4
+ NS_ASSUME_NONNULL_BEGIN
5
+
6
+ @interface PushbibCenterDelegate : NSObject <UNUserNotificationCenterDelegate>
7
+
8
+ + (instancetype)shared;
9
+
10
+ @property (nonatomic, weak, nullable) id<UNUserNotificationCenterDelegate> original;
11
+
12
+ + (NSDictionary *)normalizeContent:(UNNotificationContent *)content;
13
+
14
+ @end
15
+
16
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,138 @@
1
+ #import "PushbibCenterDelegate.h"
2
+ #import "PushbibEventBus.h"
3
+
4
+ @implementation PushbibCenterDelegate
5
+
6
+ + (instancetype)shared {
7
+ static PushbibCenterDelegate *instance;
8
+ static dispatch_once_t once;
9
+ dispatch_once(&once, ^{
10
+ instance = [PushbibCenterDelegate new];
11
+ });
12
+ return instance;
13
+ }
14
+
15
+ static BOOL PushbibFlag(NSDictionary *userInfo, NSString *key, BOOL fallback) {
16
+ id raw = userInfo[key];
17
+ if (raw == nil || raw == NSNull.null) return fallback;
18
+ if ([raw isKindOfClass:NSNumber.class]) return [raw boolValue];
19
+ NSString *value = [[raw description] lowercaseString];
20
+ if ([value isEqualToString:@"false"] || [value isEqualToString:@"0"] || [value isEqualToString:@"no"]) {
21
+ return NO;
22
+ }
23
+ return YES;
24
+ }
25
+
26
+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center
27
+ willPresentNotification:(UNNotification *)notification
28
+ withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
29
+ NSDictionary *userInfo = notification.request.content.userInfo ?: @{};
30
+
31
+ [[PushbibEventBus shared]
32
+ postEvent:PushbibEventReceived
33
+ body:@{@"notification" : [PushbibCenterDelegate normalizeContent:notification.request.content]}];
34
+
35
+ if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"pushbib_opted_out"] isEqualToString:@"1"]) {
36
+ completionHandler(UNNotificationPresentationOptionNone);
37
+ return;
38
+ }
39
+
40
+ if (!PushbibFlag(userInfo, @"showForeground", YES)) {
41
+ completionHandler(UNNotificationPresentationOptionNone);
42
+ return;
43
+ }
44
+
45
+ if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"pushbib_show_foreground"] isEqualToString:@"0"]) {
46
+ completionHandler(UNNotificationPresentationOptionNone);
47
+ return;
48
+ }
49
+
50
+ id<UNUserNotificationCenterDelegate> original = self.original;
51
+ if (original && [original respondsToSelector:_cmd]) {
52
+ [original userNotificationCenter:center
53
+ willPresentNotification:notification
54
+ withCompletionHandler:completionHandler];
55
+ return;
56
+ }
57
+
58
+ UNNotificationPresentationOptions show;
59
+ if (@available(iOS 14.0, *)) {
60
+ show = UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList |
61
+ UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge;
62
+ } else {
63
+ show = UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound |
64
+ UNNotificationPresentationOptionBadge;
65
+ }
66
+
67
+ PushbibEventBus *bus = [PushbibEventBus shared];
68
+ if (!bus.hasForegroundHandler) {
69
+ completionHandler(show);
70
+ return;
71
+ }
72
+
73
+ NSString *completionId = [[NSUUID UUID] UUIDString];
74
+ [bus storeDisplayDecision:completionId
75
+ block:^(BOOL display) {
76
+ completionHandler(display ? show : UNNotificationPresentationOptionNone);
77
+ }
78
+ timeout:5.0];
79
+ [bus postEvent:PushbibEventForegroundWillDisplay
80
+ body:@{
81
+ @"completionId" : completionId,
82
+ @"notification" : [PushbibCenterDelegate normalizeContent:notification.request.content],
83
+ }];
84
+ }
85
+
86
+ - (void)userNotificationCenter:(UNUserNotificationCenter *)center
87
+ didReceiveNotificationResponse:(UNNotificationResponse *)response
88
+ withCompletionHandler:(void (^)(void))completionHandler {
89
+ NSString *actionId = nil;
90
+ if (![response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier] &&
91
+ ![response.actionIdentifier isEqualToString:UNNotificationDismissActionIdentifier]) {
92
+ actionId = response.actionIdentifier;
93
+ }
94
+
95
+ BOOL dismissed = [response.actionIdentifier isEqualToString:UNNotificationDismissActionIdentifier];
96
+ if (!dismissed) {
97
+ NSMutableDictionary *body = [NSMutableDictionary new];
98
+ body[@"notification"] = [PushbibCenterDelegate normalizeContent:response.notification.request.content];
99
+ if (actionId) body[@"actionId"] = actionId;
100
+ [[PushbibEventBus shared] postEvent:PushbibEventClick body:body];
101
+ }
102
+
103
+ id<UNUserNotificationCenterDelegate> original = self.original;
104
+ if (original && [original respondsToSelector:_cmd]) {
105
+ [original userNotificationCenter:center
106
+ didReceiveNotificationResponse:response
107
+ withCompletionHandler:completionHandler];
108
+ } else {
109
+ completionHandler();
110
+ }
111
+ }
112
+
113
+ + (NSDictionary *)normalizeContent:(UNNotificationContent *)content {
114
+ NSDictionary *userInfo = content.userInfo ?: @{};
115
+ NSSet *controlKeys = [NSSet setWithArray:@[
116
+ @"aps", @"url", @"imageUrl", @"largeIcon", @"buttons", @"pushbib_payload",
117
+ @"showForeground", @"showBackground"
118
+ ]];
119
+
120
+ NSMutableDictionary *data = [NSMutableDictionary new];
121
+ for (NSString *key in userInfo) {
122
+ if (![key isKindOfClass:NSString.class]) continue;
123
+ if ([controlKeys containsObject:key]) continue;
124
+ if ([key hasPrefix:@"gcm."] || [key hasPrefix:@"google."]) continue;
125
+ data[key] = userInfo[key];
126
+ }
127
+
128
+ NSMutableDictionary *notification = [NSMutableDictionary new];
129
+ if (content.title.length) notification[@"title"] = content.title;
130
+ if (content.subtitle.length) notification[@"subtitle"] = content.subtitle;
131
+ if (content.body.length) notification[@"body"] = content.body;
132
+ if (userInfo[@"url"]) notification[@"url"] = [userInfo[@"url"] description];
133
+ if (userInfo[@"imageUrl"]) notification[@"imageUrl"] = [userInfo[@"imageUrl"] description];
134
+ notification[@"data"] = data;
135
+ return notification;
136
+ }
137
+
138
+ @end