diff --git a/__tests__/background-push-handler.test.ts b/__tests__/background-push-handler.test.ts new file mode 100644 index 000000000..85a8151b7 --- /dev/null +++ b/__tests__/background-push-handler.test.ts @@ -0,0 +1,182 @@ +// Platform.OS and the registered headless tasks live in mocks the tests can read and change. +const mockPlatform = { + OS: 'ios' as 'ios' | 'android', + select: (spec: { [key: string]: unknown }) => spec.default, +}; +const mockHeadlessTasks = new Map< + string, + () => (data: unknown) => Promise +>(); + +jest.mock('react-native', () => ({ + Platform: mockPlatform, + AppRegistry: { + registerHeadlessTask: jest.fn( + (key: string, provider: () => (data: unknown) => Promise) => { + mockHeadlessTasks.set(key, provider); + } + ), + }, +})); +jest.mock('../src/native-logger-listener', () => ({ + NativeLoggerListener: { warn: jest.fn() }, +})); +jest.mock('../src/specs/modules/NativeCustomerIOMessagingPush', () => { + const nativeModule = { + registerBackgroundPushHandler: jest.fn(), + unregisterBackgroundPushHandler: jest.fn(), + acknowledgeBackgroundPush: jest.fn(), + onBackgroundPushReceived: jest.fn((listener) => { + nativeModule.emit = listener; + return { remove: jest.fn() }; + }), + emit: undefined as unknown, + }; + return { __esModule: true, default: nativeModule }; +}); + +type NativeMock = { + registerBackgroundPushHandler: jest.Mock; + unregisterBackgroundPushHandler: jest.Mock; + acknowledgeBackgroundPush: jest.Mock; + onBackgroundPushReceived: jest.Mock; + emit?: (event: unknown) => Promise; +}; + +const push = { + deliveryId: 'delivery-1', + deliveryToken: 'token-1', + data: { account: 'refresh' }, +}; +const event = { id: 'push-1', push }; + +// The handler is module state, so each test loads a fresh copy of the module. +const load = () => { + let loaded!: { + pushMessaging: import('../src/customerio-push').CustomerIOPushMessaging; + native: NativeMock; + warn: jest.Mock; + registerHeadlessTask: jest.Mock; + }; + jest.isolateModules(() => { + const { CustomerIOPushMessaging } = require('../src/customerio-push'); + loaded = { + pushMessaging: new CustomerIOPushMessaging(), + native: require('../src/specs/modules/NativeCustomerIOMessagingPush') + .default, + warn: require('../src/native-logger-listener').NativeLoggerListener.warn, + registerHeadlessTask: + require('react-native').AppRegistry.registerHeadlessTask, + }; + }); + return loaded; +}; + +const runTask = (data: unknown) => + mockHeadlessTasks.get('CustomerIOBackgroundPush')!()(data); + +beforeEach(() => { + jest.clearAllMocks(); + mockHeadlessTasks.clear(); +}); + +describe('setBackgroundPushHandler on Android', () => { + beforeEach(() => { + mockPlatform.OS = 'android'; + }); + + it('registers the Headless JS task once, before telling native', () => { + const { pushMessaging, native, registerHeadlessTask } = load(); + + pushMessaging.setBackgroundPushHandler(jest.fn()); + pushMessaging.setBackgroundPushHandler(jest.fn()); + + expect(registerHeadlessTask).toHaveBeenCalledTimes(1); + expect(registerHeadlessTask.mock.invocationCallOrder[0]).toBeLessThan( + native.registerBackgroundPushHandler.mock.invocationCallOrder[0]! + ); + expect(native.registerBackgroundPushHandler).toHaveBeenCalledTimes(2); + expect(native.onBackgroundPushReceived).not.toHaveBeenCalled(); + }); + + it('runs the handler, then acknowledges the push', async () => { + const { pushMessaging, native } = load(); + const handler = jest.fn(async () => { + expect(native.acknowledgeBackgroundPush).not.toHaveBeenCalled(); + }); + pushMessaging.setBackgroundPushHandler(handler); + + await runTask(event); + + expect(handler).toHaveBeenCalledWith(push); + expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1'); + }); + + it('acknowledges a push whose handler throws', async () => { + const { pushMessaging, native, warn } = load(); + pushMessaging.setBackgroundPushHandler(async () => { + throw new Error('boom'); + }); + + await expect(runTask(event)).resolves.toBeUndefined(); + + expect(warn).toHaveBeenCalled(); + expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1'); + }); + + it('stops calling a removed handler but still acknowledges', async () => { + const { pushMessaging, native } = load(); + const handler = jest.fn(); + pushMessaging.setBackgroundPushHandler(handler).remove(); + + await runTask(event); + + expect(native.unregisterBackgroundPushHandler).toHaveBeenCalledTimes(1); + expect(handler).not.toHaveBeenCalled(); + expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1'); + }); + + it('keeps a replacement when the old subscription is removed', async () => { + const { pushMessaging, native } = load(); + // The same function twice, so only the subscription tells them apart. + const handler = jest.fn(); + const first = pushMessaging.setBackgroundPushHandler(handler); + pushMessaging.setBackgroundPushHandler(handler); + + first.remove(); + await runTask(event); + + expect(native.unregisterBackgroundPushHandler).not.toHaveBeenCalled(); + expect(handler).toHaveBeenCalledWith(push); + }); +}); + +describe('setBackgroundPushHandler on iOS', () => { + beforeEach(() => { + mockPlatform.OS = 'ios'; + }); + + it('listens for native events before telling native', () => { + const { pushMessaging, native } = load(); + + pushMessaging.setBackgroundPushHandler(jest.fn()); + + expect( + native.onBackgroundPushReceived.mock.invocationCallOrder[0] + ).toBeLessThan( + native.registerBackgroundPushHandler.mock.invocationCallOrder[0]! + ); + expect(mockHeadlessTasks.size).toBe(0); + }); + + it('runs the handler for a native event, then acknowledges it', async () => { + const { pushMessaging, native } = load(); + const handler = jest.fn(); + pushMessaging.setBackgroundPushHandler(handler); + + await native.emit!(event); + + expect(handler).toHaveBeenCalledWith(push); + expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1'); + }); +}); diff --git a/android/build.gradle b/android/build.gradle index d55359a39..411a5946b 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -161,6 +161,10 @@ dependencies { // noinspection GradleDynamicVersion api 'com.facebook.react:react-native:+' implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + // Silent push runs the JavaScript handler in a WorkManager job, which waits without holding a + // WorkManager thread. The native push module already ships both at runtime. + implementation "androidx.work:work-runtime:2.12.0" + implementation "androidx.concurrent:concurrent-futures:1.1.0" // Jetpack Compose — needed because the Visual Notification Inbox view managers host // the native `@Composable` inbox components inside a ComposeView. diff --git a/android/gradle.properties b/android/gradle.properties index 55bbf8343..bed905b9b 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -2,4 +2,4 @@ customerio.reactnative.kotlinVersion=2.1.20 customerio.reactnative.compileSdkVersion=36 customerio.reactnative.targetSdkVersion=36 customerio.reactnative.minSdkVersion=24 -customerio.reactnative.cioSDKVersionAndroid=5.0.3 +customerio.reactnative.cioSDKVersionAndroid=5.1.1 diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml index 5deacb42e..b55632390 100644 --- a/android/src/main/AndroidManifest.xml +++ b/android/src/main/AndroidManifest.xml @@ -14,6 +14,13 @@ + + + diff --git a/android/src/main/java/io/customer/reactnative/sdk/messagingpush/NativeMessagingPushModule.kt b/android/src/main/java/io/customer/reactnative/sdk/messagingpush/NativeMessagingPushModule.kt index e6a0de8ab..e5536af00 100644 --- a/android/src/main/java/io/customer/reactnative/sdk/messagingpush/NativeMessagingPushModule.kt +++ b/android/src/main/java/io/customer/reactnative/sdk/messagingpush/NativeMessagingPushModule.kt @@ -54,9 +54,22 @@ class NativeMessagingPushModule( override fun invalidate() { reactContext.removeActivityEventListener(this) + ReactBackgroundPush.release(reactContext) super.invalidate() } + override fun registerBackgroundPushHandler() { + ReactBackgroundPush.register(reactContext) + } + + override fun unregisterBackgroundPushHandler() { + ReactBackgroundPush.unregister(reactContext) + } + + override fun acknowledgeBackgroundPush(id: String) { + ReactBackgroundPush.acknowledge(id) + } + override fun getPushPermissionStatus(promise: Promise?) { val result = checkPushPermissionStatus(reactContext).toReactNativeResult promise?.resolve(result) diff --git a/android/src/main/java/io/customer/reactnative/sdk/messagingpush/ReactBackgroundPush.kt b/android/src/main/java/io/customer/reactnative/sdk/messagingpush/ReactBackgroundPush.kt new file mode 100644 index 000000000..880cf8605 --- /dev/null +++ b/android/src/main/java/io/customer/reactnative/sdk/messagingpush/ReactBackgroundPush.kt @@ -0,0 +1,238 @@ +package io.customer.reactnative.sdk.messagingpush + +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.net.Uri +import android.os.Build +import android.os.Handler +import android.os.Looper +import androidx.concurrent.futures.CallbackToFutureAdapter +import androidx.work.Data +import androidx.work.ListenableWorker +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.OutOfQuotaPolicy +import androidx.work.WorkManager +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import com.facebook.react.ReactApplication +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.ReactContext +import com.facebook.react.jstasks.HeadlessJsTaskConfig +import com.facebook.react.jstasks.HeadlessJsTaskContext +import com.google.common.util.concurrent.ListenableFuture +import io.customer.messagingpush.data.communication.CustomerIOBackgroundPushCallback +import io.customer.messagingpush.data.model.CustomerIOBackgroundPushPayload +import io.customer.messagingpush.di.backgroundPushCallbackFallback +import io.customer.sdk.core.di.SDKComponent +import java.util.UUID + +/** + * Hands Customer.io silent pushes to the JavaScript handler set with `setBackgroundPushHandler`. + * + * Firebase's receive thread gets only a few seconds, so each push runs in a WorkManager job that + * keeps the process alive while JavaScript handles it. A started service, React Native Firebase's + * approach, can't start from the background for a normal-priority message. + * + * A push waits until JavaScript registers its handler, starting React Native if it isn't running, + * and then runs as a Headless JS task, which keeps JavaScript timers running in the background. It + * ends when JavaScript acknowledges it or after [TIMEOUT_MS]. A push starts a job only once + * JavaScript has set a handler, so apps that don't use silent push see no change. + */ +internal object ReactBackgroundPush : CustomerIOBackgroundPushCallback { + /** Keep in sync with `BACKGROUND_PUSH_TASK` in customerio-push.ts. */ + private const val TASK_KEY = "CustomerIOBackgroundPush" + + /** Counted from when the job starts, so it includes starting React Native, as on iOS. */ + private const val TIMEOUT_MS = 25_000L + + private const val PREFERENCES = "io.customer.reactnative.background-push" + private const val KEY_HANDLER_SET = "handlerSet" + private const val KEY_DELIVERY_ID = "deliveryId" + private const val KEY_DELIVERY_TOKEN = "deliveryToken" + private const val DATA_PREFIX = "data." + + private class Pending(val push: Data, val finish: () -> Unit) { + var task: Pair? = null + } + + private val main = Handler(Looper.getMainLooper()) + + // The React instance whose JavaScript set the handler. Written on the main thread. + @Volatile + private var handlerContext: ReactContext? = null + + // Main thread only. + private val pending = mutableMapOf() + + override fun onBackgroundPushReceived(context: Context, payload: CustomerIOBackgroundPushPayload) { + if (handlerContext == null && !preferences(context).getBoolean(KEY_HANDLER_SET, false)) return + + val request = OneTimeWorkRequestBuilder() + .setInputData( + workDataOf( + KEY_DELIVERY_ID to payload.deliveryId, + KEY_DELIVERY_TOKEN to payload.deliveryToken, + *payload.data.map { (key, value) -> DATA_PREFIX + key to value }.toTypedArray(), + ) + ) + .apply { + // Before Android 12, expedited work needs a foreground notification, and a silent + // push must never show anything. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) + } + } + .build() + WorkManager.getInstance(context).enqueue(request) + } + + /** Called by the job on the main thread. */ + fun run(context: Context, id: String, push: Data, finish: () -> Unit) { + pending[id] = Pending(push, finish) + main.postDelayed({ + val entry = pending[id] ?: return@postDelayed + // JavaScript never registered, so this version of the app no longer sets a handler. + if (entry.task == null) forget(context) + complete(id) + }, TIMEOUT_MS) + val handler = handlerContext + if (handler != null) { + startTask(handler, id) + } else { + (context.applicationContext as? ReactApplication)?.reactHost?.start() + } + } + + fun stop(id: String) { + main.post { complete(id) } + } + + fun register(context: ReactContext) { + preferences(context).edit().putBoolean(KEY_HANDLER_SET, true).apply() + main.post { + handlerContext = context + pending.keys.toList().forEach { startTask(context, it) } + } + } + + /** JavaScript removed its handler. */ + fun unregister(context: ReactContext) { + forget(context) + main.post { + if (handlerContext === context) handlerContext = null + } + } + + /** The React instance is going away, as on a reload; pushes it didn't finish go to the next one. */ + fun release(context: ReactContext) { + main.post { + if (handlerContext === context) handlerContext = null + pending.forEach { (id, entry) -> + if (entry.task?.first === context) { + entry.task = null + handlerContext?.let { startTask(it, id) } + } + } + } + } + + fun acknowledge(id: String) { + main.post { complete(id) } + } + + private fun startTask(context: ReactContext, id: String) { + val entry = pending[id] ?: return + if (entry.task != null) return + val push = entry.push + val data = Arguments.createMap() + push.keyValueMap.forEach { (key, value) -> + if (key.startsWith(DATA_PREFIX)) data.putString(key.removePrefix(DATA_PREFIX), value as String) + } + val event = Arguments.createMap().apply { + putString("id", id) + putMap( + "push", + Arguments.createMap().apply { + putString("deliveryId", push.getString(KEY_DELIVERY_ID)) + putString("deliveryToken", push.getString(KEY_DELIVERY_TOKEN)) + putMap("data", data) + } + ) + } + // No task timeout: this object ends the task, since React Native's bridgeless runtime + // never reports a finished task. + val taskId = HeadlessJsTaskContext.getInstance(context) + .startTask(HeadlessJsTaskConfig(TASK_KEY, event, 0, true)) + entry.task = context to taskId + } + + private fun complete(id: String) { + val entry = pending.remove(id) ?: return + entry.task?.let { (context, taskId) -> + val tasks = HeadlessJsTaskContext.getInstance(context) + if (tasks.isTaskRunning(taskId)) tasks.finishTask(taskId) + } + entry.finish() + } + + private fun forget(context: Context) { + preferences(context).edit().remove(KEY_HANDLER_SET).apply() + } + + private fun preferences(context: Context) = + context.applicationContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) +} + +internal class ReactBackgroundPushWorker( + context: Context, + params: WorkerParameters, +) : ListenableWorker(context, params) { + // WorkManager can stop a job and run it again with the same work ID, so each run has its own. + private val runId = UUID.randomUUID().toString() + + override fun startWork(): ListenableFuture = + CallbackToFutureAdapter.getFuture { completer -> + ReactBackgroundPush.run(applicationContext, runId, inputData) { + completer.set(Result.success()) + } + "Customer.io silent push" + } + + override fun onStopped() { + ReactBackgroundPush.stop(runId) + } +} + +/** + * Sets the silent push callback when the process starts, before JavaScript runs, since Firebase + * can start a killed app's process just to deliver a push. A callback in the app's own push config + * takes precedence. + */ +internal class ReactBackgroundPushInitProvider : ContentProvider() { + override fun onCreate(): Boolean { + SDKComponent.backgroundPushCallbackFallback.callback = ReactBackgroundPush + return true + } + + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String?, + ) = null + + override fun getType(uri: Uri): String? = null + + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?) = 0 + + override fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array?, + ) = 0 +} diff --git a/api-extractor-output/customerio-reactnative.api.md b/api-extractor-output/customerio-reactnative.api.md index feee22183..44db6142e 100644 --- a/api-extractor-output/customerio-reactnative.api.md +++ b/api-extractor-output/customerio-reactnative.api.md @@ -15,6 +15,16 @@ import type { UnsafeObject } from 'react-native/Libraries/Types/CodegenTypes'; import type { ViewProps } from 'react-native'; import { ViewStyle } from 'react-native'; +// @public +export type CioBackgroundPush = { + deliveryId: string; + data: Record; + deliveryToken: string; +}; + +// @public +export type CioBackgroundPushHandler = (push: CioBackgroundPush) => void | Promise; + // @public export enum CioColorScheme { Auto = "auto", @@ -184,6 +194,9 @@ export class CustomerIOPushMessaging implements NativePushSpec { isAndroid(): boolean; onBackgroundMessageReceived(message: any): Promise; onMessageReceived(message: any, handleNotificationTrigger?: boolean): Promise; + setBackgroundPushHandler(handler: CioBackgroundPushHandler): { + remove(): void; + }; // (undocumented) showPromptForPushNotifications(options?: CioPushPermissionOptions): Promise; trackNotificationReceived(payload: Object): void; diff --git a/docs/silent-push.md b/docs/silent-push.md new file mode 100644 index 000000000..1c9852a88 --- /dev/null +++ b/docs/silent-push.md @@ -0,0 +1,135 @@ +# Silent push + +A Customer.io silent push shows nothing. It wakes your app and hands it the text key/value data you set on +the message, so the app can refresh state in the background. The SDK tracks the delivered metric; silent +pushes have no opened metric. + +Silent push needs the customerio-reactnative release that adds `setBackgroundPushHandler`, which bundles native +SDKs that support it (Android 5.1.1, iOS 5.2.1). Customer.io sends a silent push to every iOS and Android device +on the profile, so handling it is up to the app. An app that doesn't handle it shows nothing. + +Use one route on each platform: + +| Your app | Android and iOS | +| --- | --- | +| The Customer.io SDK owns push (APN or FCM through the Customer.io SDK; Expo apps) | `setBackgroundPushHandler` ([details](#with-the-customer-io-sdk)) | +| Uses `@react-native-firebase/messaging` | React Native Firebase's handlers ([details](#with-react-native-firebase)) | + +If an app handles silent pushes in React Native Firebase and also sets `setBackgroundPushHandler`, each push can +arrive twice. + +## What a silent push carries + +Your data arrives as text keys and values, plus two keys Customer.io adds: `CIO-Background-Delivery-ID` (the +delivery ID) and `CIO-Background-Delivery-Token` (the device token the push was sent to). +`setBackgroundPushHandler` strips them and gives you `deliveryId` and `deliveryToken`; React Native Firebase passes +them through in `remoteMessage.data`. + +On Android the message is data-only, at the priority set on the message (normal unless you choose high). On iOS +it is a background notification (`content-available: 1`, priority 5). Like a regular push, it has no expiry. + +- **Repeats.** The same push can arrive more than once. Key your work on the delivery ID. +- **Time.** Keep the work short. The SDK waits up to 25 seconds for your handler, including the time React Native + takes to start. +- **Delays.** Android can hold normal-priority messages while the device is idle, and iOS throttles background + notifications and keeps only the newest for a device that's offline. + +## With the Customer.io SDK + +Set the handler in your entry file (`index.js`), before `AppRegistry.registerComponent`. On Android, a silent push +that starts your app in the background runs `index.js` without mounting your app, so a handler set inside a +component would miss it. + +```js +// index.js +import { AppRegistry } from 'react-native'; +import { CustomerIO } from 'customerio-reactnative'; +import App from './src/App'; + +CustomerIO.pushMessaging.setBackgroundPushHandler(async ({ deliveryId, data }) => { + await refreshAccount(data, { idempotencyKey: deliveryId }); +}); + +AppRegistry.registerComponent('MyApp', () => App); +``` + +A handler that throws or rejects is logged and counts as finished. Setting a new handler replaces the previous +one, and the returned subscription's `remove()` stops delivery. You need `deliveryToken` only to track delivery +yourself with `CustomerIO.trackMetric` when automatic push tracking is off. + +Your handler can run before any component mounts, so `CustomerIO.initialize` in a component may not have run yet. +To call the SDK from the handler, initialize it in `index.js` too. + +### Android + +Nothing else is needed. The SDK runs your handler in a Headless JS task from a WorkManager job, in the running app +or in a React Native instance it starts in the background. Your `Application` must provide a `ReactHost`, as the +React Native template does. + +A push that starts an app that isn't running reaches your handler once your JavaScript has set it at least once. +If a later version of your app stops setting the handler, the first push that finds none within 25 seconds turns +this off, and calling `remove()` on the subscription turns it off right away. + +### iOS + +Add the Remote notifications background mode: in Xcode, Signing & Capabilities > Background Modes > Remote +notifications, or `remote-notification` under `UIBackgroundModes` in `Info.plist`. + +If your `AppDelegate` is wrapped with `CioAppDelegateWrapper`, as in the Customer.io push setup, nothing else is +needed. Once your JavaScript has set the handler, in this launch or an earlier one, the wrapper hands each +Customer.io silent push to it and tells iOS when it's done. Until then, and for every other notification, your app +delegate gets the push as before. If iOS launched the app for the push, it starts your app as usual and the push +waits until JavaScript sets the handler. As on Android, a later version that stops setting the handler turns this +off with the first push that finds none, and `remove()` turns it off right away. iOS doesn't wake an app the person +force-quit. + +Apps using Firebase Cloud Messaging with Firebase's app delegate proxy on (the default) need GoogleUtilities +8.1.5 or later, or no background notification reaches `CioAppDelegateWrapper`. Run `pod update GoogleUtilities`, +or set `FirebaseAppDelegateProxyEnabled` to `NO` in `Info.plist`. + +If your app delegate isn't wrapped with `CioAppDelegateWrapper`, forward background notifications yourself: + +```swift +import customerio_reactnative + +func application( + _ application: UIApplication, + didReceiveRemoteNotification userInfo: [AnyHashable: Any], + fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void +) { + if NativeMessagingPush.handleBackgroundPush(userInfo: userInfo, completionHandler: completionHandler) { + return // A Customer.io silent push. The SDK tracks Delivered and calls completionHandler. + } + completionHandler(.noData) // Or pass the notification to your other handlers. +} +``` + +## With React Native Firebase + +Handle Customer.io silent pushes in React Native Firebase's handlers on both platforms, and don't set +`setBackgroundPushHandler`. `messaging().onMessage` receives a silent push while the app is in the foreground, +and `messaging().setBackgroundMessageHandler` while it's in the background or not running. Keep forwarding +messages to Customer.io as you do today, and don't render a silent push yourself: + +```js +messaging().setBackgroundMessageHandler(async (remoteMessage) => { + const handled = await CustomerIO.pushMessaging.onBackgroundMessageReceived(remoteMessage); + if (remoteMessage.data?.['CIO-Background-Delivery-ID']) { + // A Customer.io silent push: read your keys from remoteMessage.data. + await refreshAccount(remoteMessage.data); + return; + } + if (!handled) { + // Not a Customer.io message: handle it as before. + } +}); +``` + +On Android, `onMessageReceived` and `onBackgroundMessageReceived` show nothing for a silent push, track Delivered +and resolve `true`. React Native Firebase runs `setBackgroundMessageHandler` by starting a service, which Android 8 +and later refuse for a normal-priority message once the app has been in the background for a few minutes; then +neither your handler nor Customer.io sees the push. Choose high priority for Android silent pushes on this route. + +On iOS, add the Remote notifications background mode as above. `onMessageReceived` and +`onBackgroundMessageReceived` do nothing on iOS and resolve `true`; the SDK tracks Delivered as the push passes +through `CioAppDelegateWrapper`. diff --git a/example/index.js b/example/index.js index 5c32d1c2b..78548bbe7 100644 --- a/example/index.js +++ b/example/index.js @@ -1,6 +1,13 @@ import {AppRegistry} from 'react-native'; +import {CustomerIO} from 'customerio-reactnative'; import App from './src/App'; +// Before registerComponent: on Android, a silent push can start the app in the background and run +// this file without mounting App. +CustomerIO.pushMessaging.setBackgroundPushHandler(async push => { + console.log('[SilentPush] received', JSON.stringify(push)); +}); + AppRegistry.registerComponent('React Native FCM', () => App); AppRegistry.registerComponent('React Native APN', () => App); AppRegistry.registerComponent('React Native Android', () => App); diff --git a/example/ios/SampleApp/Info.plist b/example/ios/SampleApp/Info.plist index e57d643a2..dbb4db558 100644 --- a/example/ios/SampleApp/Info.plist +++ b/example/ios/SampleApp/Info.plist @@ -24,6 +24,7 @@ UIBackgroundModes location + remote-notification UIViewControllerBasedStatusBarAppearance diff --git a/ios/wrappers/push/CustomerIOReactNativeBackgroundPushRouter.swift b/ios/wrappers/push/CustomerIOReactNativeBackgroundPushRouter.swift new file mode 100644 index 000000000..27fef12c7 --- /dev/null +++ b/ios/wrappers/push/CustomerIOReactNativeBackgroundPushRouter.swift @@ -0,0 +1,78 @@ +import CioMessagingPush +import Foundation +import UIKit + +/// Hands Customer.io silent pushes to the JavaScript handler and owns each push's completion +/// handler. iOS can launch the app for a push before JavaScript runs, so a push waits until +/// JavaScript registers its handler. It completes with `.newData` when JavaScript acknowledges it, +/// or `.noData` after 25 seconds, within the roughly 30 seconds iOS allows. Main thread only. +enum CustomerIOReactNativeBackgroundPushRouter { + private struct PendingPush { + let push: [String: Any] + let completion: (UIBackgroundFetchResult) -> Void + var sent = false + } + + private static var pending: [String: PendingPush] = [:] + private static weak var handler: NativeMessagingPush? + + private static let handlerSetKey = "io.customer.reactnative.backgroundPushHandlerSet" + + /// JavaScript set a handler in this launch or an earlier one. + static var isHandlerExpected: Bool { + handler != nil || UserDefaults.standard.bool(forKey: handlerSetKey) + } + + static func accept(_ push: CustomerIOBackgroundPush, completion: @escaping (UIBackgroundFetchResult) -> Void) { + let id = UUID().uuidString + pending[id] = PendingPush( + push: ["deliveryId": push.deliveryID, "deliveryToken": push.deliveryToken, "data": push.data], + completion: completion + ) + send(id) + DispatchQueue.main.asyncAfter(deadline: .now() + 25) { + // JavaScript never registered, so this version of the app no longer sets a handler. + if pending[id]?.sent == false { + UserDefaults.standard.removeObject(forKey: handlerSetKey) + } + complete(id, with: .noData) + } + } + + static func register(_ module: NativeMessagingPush) { + handler = module + UserDefaults.standard.set(true, forKey: handlerSetKey) + pending.keys.forEach(send) + } + + /// JavaScript removed its handler. + static func unregister(_ module: NativeMessagingPush) { + if handler === module { + handler = nil + } + UserDefaults.standard.removeObject(forKey: handlerSetKey) + } + + /// The React instance is going away, as on a reload; pushes it didn't finish go to the next one. + static func release(_ module: NativeMessagingPush) { + guard handler === module else { return } + handler = nil + for id in pending.keys { + pending[id]?.sent = false + } + } + + static func acknowledge(_ id: String) { + complete(id, with: .newData) + } + + private static func send(_ id: String) { + guard let handler, let entry = pending[id], !entry.sent else { return } + pending[id]?.sent = true + handler.emitBackgroundPush(["id": id, "push": entry.push]) + } + + private static func complete(_ id: String, with result: UIBackgroundFetchResult) { + pending.removeValue(forKey: id)?.completion(result) + } +} diff --git a/ios/wrappers/push/NativeMessagingPush.mm b/ios/wrappers/push/NativeMessagingPush.mm index 6d169013f..17015fb1b 100644 --- a/ios/wrappers/push/NativeMessagingPush.mm +++ b/ios/wrappers/push/NativeMessagingPush.mm @@ -1,11 +1,27 @@ #import "../utils/RCTCustomerIOUtils.h" #import +#import #import +@protocol NativeMessagingPushBridge +- (void)setEventEmitter:(id)emitter; +@end + +// Runs at process start, before iOS can deliver a silent push that launched the app. A constructor +// because RCT_EXPORT_MODULE already defines +load. +__attribute__((constructor)) static void RCTNativeMessagingPushInstallBackgroundPushHandler(void) { + Class swiftClass = NSClassFromString(@"NativeMessagingPush"); + SEL selector = NSSelectorFromString(@"installWrapperBackgroundPushHandler"); + if ([swiftClass respondsToSelector:selector]) { + ((void (*)(id, SEL))[swiftClass methodForSelector:selector])(swiftClass, selector); + } +} + // Objective-C wrapper for new architecture TurboModule implementation -@interface RCTNativeMessagingPush : NSObject +@interface RCTNativeMessagingPush + : NativeCustomerIOMessagingPushSpecBase // Bridge to Swift implementation for cross-language compatibility -@property(nonatomic, strong) id swiftBridge; +@property(nonatomic, strong) id swiftBridge; @end @implementation RCTNativeMessagingPush @@ -30,10 +46,16 @@ - (instancetype)init { RCT_ASSERT_NOT_NIL(swiftClass, @"NativeMessagingPush Swift class", @"during runtime lookup"); _swiftBridge = [[swiftClass alloc] init]; [self assertBridgeAvailable:@"creating NativeMessagingPush Swift instance"]; + [_swiftBridge setEventEmitter:self]; } return self; } +- (void)invalidate { + [self assertBridgeAvailable:@"during invalidate"]; + [_swiftBridge invalidate]; +} + // Module initialization can happen on background thread + (BOOL)requiresMainQueueSetup { return NO; @@ -79,6 +101,25 @@ - (void)getPushPermissionStatus:(RCTPromiseResolveBlock)resolve [_swiftBridge getPushPermissionStatus:resolve reject:reject]; } +- (void)registerBackgroundPushHandler { + [self assertBridgeAvailable:@"during registerBackgroundPushHandler"]; + [_swiftBridge registerBackgroundPushHandler]; +} + +- (void)unregisterBackgroundPushHandler { + [self assertBridgeAvailable:@"during unregisterBackgroundPushHandler"]; + [_swiftBridge unregisterBackgroundPushHandler]; +} + +- (void)acknowledgeBackgroundPush:(NSString *)id { + [self assertBridgeAvailable:@"during acknowledgeBackgroundPush"]; + [_swiftBridge acknowledgeBackgroundPush:id]; +} + +- (void)emitOnBackgroundPushReceived:(NSDictionary *)value { + [super emitOnBackgroundPushReceived:value]; +} + // Export class factory function for React Native component registration Class NativeCustomerIOMessagingPushCls(void) { return RCTNativeMessagingPush.class; diff --git a/ios/wrappers/push/NativeMessagingPush.swift b/ios/wrappers/push/NativeMessagingPush.swift index 387cab4cd..56540792f 100644 --- a/ios/wrappers/push/NativeMessagingPush.swift +++ b/ios/wrappers/push/NativeMessagingPush.swift @@ -1,6 +1,7 @@ import CioInternalCommon -import CioMessagingPush +@_spi(Internal) import CioMessagingPush import Foundation +import UIKit enum PushPermissionStatus: String, CaseIterable { case denied @@ -15,6 +16,80 @@ enum PushPermissionStatus: String, CaseIterable { @objc(NativeMessagingPush) public class NativeMessagingPush: NSObject { private let logger: CioInternalCommon.Logger = DIGraphShared.shared.logger + private weak var objcEventEmitter: AnyObject? + + /// Lets `CioAppDelegateWrapper` hand Customer.io silent pushes to JavaScript, after the native SDK + /// records Delivered. Called at process start from NativeMessagingPush.mm, before iOS can deliver + /// a push that launched the app. Other pushes, and every push in apps whose JavaScript never set a + /// handler, go to the app delegate as before. + @available(iOSApplicationExtension, unavailable) + @objc + public static func installWrapperBackgroundPushHandler() { + MessagingPush.wrapperBackgroundPushHandler = { push, completion in + guard CustomerIOReactNativeBackgroundPushRouter.isHandlerExpected else { return false } + CustomerIOReactNativeBackgroundPushRouter.accept(push, completion: completion) + return true + } + } + + /// For an app delegate that isn't wrapped with `CioAppDelegateWrapper`: call it first in + /// `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`. Returns `true` for a + /// Customer.io silent push once JavaScript has set a handler, and then calls `completionHandler` + /// itself; returns `false` for any other push and leaves `completionHandler` to the caller. + @available(iOSApplicationExtension, unavailable) + @objc(handleBackgroundPushWithUserInfo:completionHandler:) + public static func handleBackgroundPush( + userInfo: [AnyHashable: Any], + completionHandler: @escaping (UIBackgroundFetchResult) -> Void + ) -> Bool { + let result = MessagingPush.shared.handleBackgroundPush(userInfo: userInfo) + guard CustomerIOReactNativeBackgroundPushRouter.isHandlerExpected else { return false } + switch result { + case .notBackground: + return false + case .unsupported: + completionHandler(.noData) + return true + case .received(let push): + CustomerIOReactNativeBackgroundPushRouter.accept(push, completion: completionHandler) + return true + } + } + + @objc + public func setEventEmitter(_ emitter: AnyObject) { + objcEventEmitter = emitter + } + + @objc + func registerBackgroundPushHandler() { + DispatchQueue.main.async { CustomerIOReactNativeBackgroundPushRouter.register(self) } + } + + @objc + func unregisterBackgroundPushHandler() { + DispatchQueue.main.async { CustomerIOReactNativeBackgroundPushRouter.unregister(self) } + } + + @objc + func acknowledgeBackgroundPush(_ id: String) { + DispatchQueue.main.async { CustomerIOReactNativeBackgroundPushRouter.acknowledge(id) } + } + + @objc + func invalidate() { + DispatchQueue.main.async { CustomerIOReactNativeBackgroundPushRouter.release(self) } + } + + func emitBackgroundPush(_ body: [String: Any]) { + // Codegen derives this selector from `onBackgroundPushReceived` in NativeCustomerIOMessagingPush.ts. + let selector = Selector(("emitOnBackgroundPushReceived:")) + guard let emitter = objcEventEmitter, emitter.responds(to: selector) else { + assertionFailure("ObjC event emitter does not respond to selector: emitOnBackgroundPushReceived:") + return + } + _ = emitter.perform(selector, with: body as NSDictionary) + } @objc public func onMessageReceived( diff --git a/package.json b/package.json index e7e4caeae..dddccc357 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ }, "./package.json": "./package.json" }, - "cioNativeiOSSdkVersion": "= 5.1.3", + "cioNativeiOSSdkVersion": "= 5.2.1", "files": [ "src", "lib", diff --git a/src/customerio-push.ts b/src/customerio-push.ts index 470104914..2d7f4ff14 100644 --- a/src/customerio-push.ts +++ b/src/customerio-push.ts @@ -1,8 +1,11 @@ -import { Platform, type TurboModule } from 'react-native'; +import { AppRegistry, Platform, type TurboModule } from 'react-native'; +import { NativeLoggerListener } from './native-logger-listener'; import NativeCustomerIOMessagingPush, { type Spec as CodegenSpec, } from './specs/modules/NativeCustomerIOMessagingPush'; import { + type CioBackgroundPush, + type CioBackgroundPushHandler, type CioPushPermissionOptions, CioPushPermissionStatus, } from './types'; @@ -13,7 +16,14 @@ import { callNativeModule, ensureNativeModule } from './utils/native-bridge'; * * @internal */ -interface NativePushSpec extends Omit {} +interface NativePushSpec extends Omit< + CodegenSpec, + | keyof TurboModule + | 'registerBackgroundPushHandler' + | 'unregisterBackgroundPushHandler' + | 'acknowledgeBackgroundPush' + | 'onBackgroundPushReceived' +> {} // Reference to the native CustomerIO Data Pipelines module for SDK operations const nativeModule = ensureNativeModule(NativeCustomerIOMessagingPush); @@ -23,6 +33,25 @@ const withNativeModule = (fn: (native: CodegenSpec) => R): R => { return callNativeModule(nativeModule, fn); }; +// Keep in sync with `TASK_KEY` in ReactBackgroundPush.kt. +const BACKGROUND_PUSH_TASK = 'CustomerIOBackgroundPush'; + +type BackgroundPushEvent = { id: string; push: CioBackgroundPush }; + +let backgroundPushHandler: CioBackgroundPushHandler | undefined; +let backgroundPushSubscription: { remove(): void } | undefined; +let backgroundPushListening = false; + +// Runs the handler, then acknowledges the push so native can end the OS's background time. +const handleBackgroundPush = async (event: BackgroundPushEvent) => { + try { + await backgroundPushHandler?.(event.push); + } catch (error) { + NativeLoggerListener.warn('Silent push handler failed:', error); + } + withNativeModule((native) => native.acknowledgeBackgroundPush(event.id)); +}; + /** @public */ class CustomerIOPushMessaging implements NativePushSpec { /** @@ -119,6 +148,52 @@ class CustomerIOPushMessaging implements NativePushSpec { ); } + /** + * Sets the handler for Customer.io silent pushes. Call it at the top level of your entry file + * (`index.js`), before `AppRegistry.registerComponent`: on Android, a silent push that starts the + * app in the background runs that file without mounting your app. + * + * The SDK waits up to 25 seconds for the returned promise, including the time React Native takes + * to start. Setting a new handler replaces the previous one. + * + * @param handler - receives each silent push + * @returns a subscription whose `remove()` stops delivery to this handler + */ + setBackgroundPushHandler(handler: CioBackgroundPushHandler): { + remove(): void; + } { + return withNativeModule((native) => { + if (!backgroundPushListening) { + if (Platform.OS === 'android') { + AppRegistry.registerHeadlessTask( + BACKGROUND_PUSH_TASK, + () => handleBackgroundPush + ); + } else { + native.onBackgroundPushReceived((event) => + handleBackgroundPush(event as BackgroundPushEvent) + ); + } + backgroundPushListening = true; + } + backgroundPushHandler = handler; + native.registerBackgroundPushHandler(); + + const subscription = { + remove: () => { + if (backgroundPushSubscription !== subscription) { + return; + } + backgroundPushSubscription = undefined; + backgroundPushHandler = undefined; + native.unregisterBackgroundPushHandler(); + }, + }; + backgroundPushSubscription = subscription; + return subscription; + }); + } + isAndroid(): boolean { return Platform.OS === 'android'; } diff --git a/src/specs/modules/NativeCustomerIOMessagingPush.ts b/src/specs/modules/NativeCustomerIOMessagingPush.ts index 5fc8c54ab..217ed0cd9 100644 --- a/src/specs/modules/NativeCustomerIOMessagingPush.ts +++ b/src/specs/modules/NativeCustomerIOMessagingPush.ts @@ -1,5 +1,8 @@ import { TurboModuleRegistry, type TurboModule } from 'react-native'; -import type { UnsafeObject } from 'react-native/Libraries/Types/CodegenTypes'; +import type { + EventEmitter, + UnsafeObject, +} from 'react-native/Libraries/Types/CodegenTypes'; /** * Native module specification for CustomerIO Push Messaging React Native SDK @@ -20,6 +23,11 @@ export interface Spec extends TurboModule { getRegisteredDeviceToken(): Promise; showPromptForPushNotifications(options: NativeBridgeObject): Promise; getPushPermissionStatus(): Promise; + registerBackgroundPushHandler(): void; + unregisterBackgroundPushHandler(): void; + acknowledgeBackgroundPush(id: string): void; + // iOS only. Android runs the handler as a Headless JS task. + readonly onBackgroundPushReceived: EventEmitter; } export default TurboModuleRegistry.getEnforcing( diff --git a/src/types/push.ts b/src/types/push.ts index 3dac4aa2a..3bf1a8f1c 100644 --- a/src/types/push.ts +++ b/src/types/push.ts @@ -32,6 +32,28 @@ export type CioPushPermissionOptions = { }; }; +/** + * A Customer.io silent push, which shows nothing and hands the app the data set on the message. + * + * @public + */ +export type CioBackgroundPush = { + /** The same push can arrive more than once with the same ID, so key your work on it. */ + deliveryId: string; + data: Record; + /** Only needed to track delivery yourself when automatic push tracking is off. */ + deliveryToken: string; +}; + +/** + * Receives Customer.io silent pushes. The SDK waits up to 25 seconds for the returned promise. + * + * @public + */ +export type CioBackgroundPushHandler = ( + push: CioBackgroundPush +) => void | Promise; + /** * Current push notification permission status. *