@altcraft/react-native-sdk 0.0.3 → 0.0.5

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.
@@ -4,12 +4,14 @@ package com.altcraft.sdk
4
4
  //
5
5
  // Copyright © 2025 Altcraft. All rights reserved.
6
6
 
7
+ import android.util.Log
7
8
  import androidx.activity.ComponentActivity
8
9
  import com.altcraft.sdk.config.AltcraftConfiguration
9
10
  import com.altcraft.sdk.data.DataClasses
10
- import com.altcraft.sdk.mob_events.PublicMobileEventFunction
11
+ import com.altcraft.sdk.mob_events.PublicMobileEventFunctions
11
12
  import com.altcraft.sdk.push.events.PublicPushEventFunctions
12
13
  import com.altcraft.sdk.push.subscribe.PublicPushSubscriptionFunctions
14
+ import com.altcraft.sdk.profile.PublicProfileFunctions
13
15
  import com.altcraft.sdk.push.token.PublicPushTokenFunctions
14
16
  import com.altcraft.sdk.rn.getArrayOrNull
15
17
  import com.altcraft.sdk.rn.getBooleanOrNull
@@ -31,7 +33,7 @@ import com.facebook.react.bridge.ReadableMap
31
33
  import com.facebook.react.bridge.UiThreadUtil
32
34
  import com.facebook.react.bridge.WritableMap
33
35
  import com.facebook.react.module.annotations.ReactModule
34
- import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter
36
+
35
37
  import kotlinx.coroutines.CoroutineScope
36
38
  import kotlinx.coroutines.Dispatchers
37
39
  import kotlinx.coroutines.SupervisorJob
@@ -40,800 +42,952 @@ import kotlinx.coroutines.launch
40
42
  // ---------------------- Constants ----------------------
41
43
 
42
44
  private object RnConstants {
43
- // Module
44
- const val MODULE_NAME: String = "Sdk"
45
-
46
- // JS event emitter
47
- const val JS_EVENT_NAME: String = "AltcraftSdkEvent"
48
-
49
- // Promise reject codes
50
- const val ERR_INIT_INVALID_CONFIG: String = "ALTCRAFT_INIT_INVALID_CONFIG"
51
- const val ERR_INIT_ERROR: String = "ALTCRAFT_INIT_ERROR"
52
- const val ERR_GET_PUSH_TOKEN: String = "getPushToken"
53
- const val ERR_SET_PUSH_TOKEN: String = "setPushToken"
54
- const val ERR_CLEAR: String = "clear"
55
- const val ERR_UNSUSPEND: String = "unSuspendPushSubscription"
56
- const val ERR_GET_LATEST_STATUS: String = "getStatusOfLatestSubscription"
57
- const val ERR_GET_CURRENT_STATUS: String = "getStatusForCurrentSubscription"
58
- const val ERR_GET_LATEST_STATUS_PROVIDER: String = "getStatusOfLatestSubscriptionForProvider"
59
-
60
- // Promise reject messages
61
- const val MSG_PROVIDER_IS_BLANK: String = "provider is blank"
62
- const val MSG_INIT_UNKNOWN: String = "Altcraft initialization failed with unknown error"
63
- const val MSG_INIT_ERROR: String = "Altcraft initialization error"
64
-
65
- // Keys: TokenData map
66
- const val KEY_PROVIDER: String = "provider"
67
- const val KEY_TOKEN: String = "token"
68
-
69
- // Keys: SDK event map
70
- const val KEY_FUNCTION: String = "function"
71
- const val KEY_CODE: String = "code"
72
- const val KEY_MESSAGE: String = "message"
73
- const val KEY_TYPE: String = "type"
74
- const val KEY_VALUE: String = "value"
75
-
76
- // Event types for JS
77
- const val TYPE_EVENT: String = "event"
78
- const val TYPE_ERROR: String = "error"
79
- const val TYPE_RETRY_ERROR: String = "retryError"
80
-
81
- // Keys: ResponseWithHttpCode -> JS map
82
- const val KEY_HTTP_CODE: String = "httpCode"
83
- const val KEY_RESPONSE: String = "response"
84
- const val KEY_ERROR: String = "error"
85
- const val KEY_ERROR_TEXT: String = "errorText"
86
- const val KEY_PROFILE: String = "profile"
87
- const val KEY_ID: String = "id"
88
- const val KEY_STATUS: String = "status"
89
- const val KEY_IS_TEST: String = "isTest"
90
- const val KEY_SUBSCRIPTION: String = "subscription"
91
- const val KEY_SUBSCRIPTION_ID: String = "subscriptionId"
92
- const val KEY_HASH_ID: String = "hashId"
93
-
94
- // Fields not mapped yet (kept for parity with TS)
95
- const val KEY_FIELDS: String = "fields"
96
- const val KEY_CATS: String = "cats"
45
+ // Module
46
+ const val MODULE_NAME: String = "Sdk"
47
+
48
+ // JS event emitter
49
+ const val JS_EVENT_NAME: String = "AltcraftSdkEvent"
50
+
51
+ // Promise reject codes
52
+ const val ERR_INIT_INVALID_CONFIG: String = "ALTCRAFT_INIT_INVALID_CONFIG"
53
+ const val ERR_INIT_ERROR: String = "ALTCRAFT_INIT_ERROR"
54
+ const val ERR_GET_PUSH_TOKEN: String = "getPushToken"
55
+ const val ERR_SET_PUSH_TOKEN: String = "setPushToken"
56
+ const val ERR_CLEAR: String = "clear"
57
+ const val ERR_UNSUSPEND: String = "unSuspendPushSubscription"
58
+ const val ERR_GET_LATEST_STATUS: String = "getStatusOfLatestSubscription"
59
+ const val ERR_GET_CURRENT_STATUS: String = "getStatusForCurrentSubscription"
60
+ const val ERR_GET_LATEST_STATUS_PROVIDER: String = "getStatusOfLatestSubscriptionForProvider"
61
+ const val ERR_UPDATE_PROFILE_FIELDS: String = "updateProfileFields"
62
+ const val ERR_FORCED_TOKEN_UPDATE: String = "forcedTokenUpdate"
63
+ const val ERR_DELETE_DEVICE_TOKEN: String = "deleteDeviceToken"
64
+ const val ERR_CHANGE_PROVIDER_PRIORITY: String = "changePushProviderPriorityList"
65
+
66
+ // Promise reject messages
67
+ const val MSG_PROVIDER_IS_BLANK: String = "provider is blank"
68
+ const val MSG_INIT_UNKNOWN: String = "Altcraft initialization failed with unknown error"
69
+ const val MSG_INIT_ERROR: String = "Altcraft initialization error"
70
+
71
+ // Keys: TokenData map
72
+ const val KEY_PROVIDER: String = "provider"
73
+ const val KEY_TOKEN: String = "token"
74
+
75
+ // Keys: SDK event map
76
+ const val KEY_FUNCTION: String = "function"
77
+ const val KEY_CODE: String = "code"
78
+ const val KEY_MESSAGE: String = "message"
79
+ const val KEY_TYPE: String = "type"
80
+ const val KEY_VALUE: String = "value"
81
+
82
+ // Event types for JS
83
+ const val TYPE_EVENT: String = "event"
84
+ const val TYPE_ERROR: String = "error"
85
+ const val TYPE_RETRY_ERROR: String = "retryError"
86
+
87
+ // Keys: ResponseWithHttpCode -> JS map
88
+ const val KEY_HTTP_CODE: String = "httpCode"
89
+ const val KEY_RESPONSE: String = "response"
90
+ const val KEY_ERROR: String = "error"
91
+ const val KEY_ERROR_TEXT: String = "errorText"
92
+ const val KEY_PROFILE: String = "profile"
93
+ const val KEY_ID: String = "id"
94
+ const val KEY_STATUS: String = "status"
95
+ const val KEY_IS_TEST: String = "isTest"
96
+ const val KEY_SUBSCRIPTION: String = "subscription"
97
+ const val KEY_SUBSCRIPTION_ID: String = "subscriptionId"
98
+ const val KEY_HASH_ID: String = "hashId"
99
+
100
+ // Fields not mapped yet (kept for parity with TS)
101
+ const val KEY_FIELDS: String = "fields"
102
+ const val KEY_CATS: String = "cats"
97
103
  }
98
104
 
99
105
  @ReactModule(name = RnConstants.MODULE_NAME)
100
106
  class SdkModule(reactContext: ReactApplicationContext) : NativeSdkSpec(reactContext) {
101
107
 
102
- private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
103
-
104
- override fun getName(): String = RnConstants.MODULE_NAME
105
-
106
- /**
107
- * Required by NativeEventEmitter (no-op on Android).
108
- *
109
- * @param eventName Event name from JS side.
110
- */
111
- override fun addListener(eventName: String) {
112
- // no-op
108
+ private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
109
+
110
+ override fun getName(): String = RnConstants.MODULE_NAME
111
+
112
+ /**
113
+ * Required by NativeEventEmitter (no-op on Android).
114
+ *
115
+ * @param eventName Event name from JS side.
116
+ */
117
+ override fun addListener(eventName: String) {
118
+ // no-op
119
+ }
120
+
121
+ /**
122
+ * Required by NativeEventEmitter (no-op on Android).
123
+ *
124
+ * @param count Number of JS listeners removed.
125
+ */
126
+ override fun removeListeners(count: Double) {
127
+ // no-op
128
+ }
129
+
130
+ // ---------------------- init ----------------------
131
+
132
+ /**
133
+ * Initializes the native Altcraft SDK using RN config map.
134
+ *
135
+ * @param config React Native configuration object.
136
+ * ```
137
+ * Required: `apiUrl`.
138
+ * Optional: `rToken`, `appInfo`, `providerPriorityList`, `enableLogging`,
139
+ * Android-only: `android_icon`, `android_usingService`, `android_serviceMessage`,
140
+ * `android_pushReceiverModules`, `android_pushChannelName`, `android_pushChannelDescription`.
141
+ * @param promise
142
+ * ```
143
+ * Promise resolved on success; rejected on invalid config or initialization failure.
144
+ */
145
+ override fun initialize(config: ReadableMap, promise: Promise) {
146
+ AltcraftRnInitializer.initialize(
147
+ reactContext = reactApplicationContext,
148
+ config = config,
149
+ promise = promise
150
+ )
151
+ }
152
+
153
+ // ---------------------- token-API for RN (ONLY getPushToken / setPushToken)
154
+ // ----------------------
155
+
156
+ /**
157
+ * Returns current push token data from native side.
158
+ *
159
+ * @param promise Resolves to `{ provider, token }` or `null` if token is not available.
160
+ */
161
+ override fun getPushToken(promise: Promise) {
162
+ coroutineScope.launch {
163
+ try {
164
+ val tokenData = PublicPushTokenFunctions.getPushToken(reactApplicationContext)
165
+ if (tokenData == null) {
166
+ promise.resolve(null)
167
+ } else {
168
+ val map = Arguments.createMap()
169
+ map.putString(RnConstants.KEY_PROVIDER, tokenData.provider)
170
+ map.putString(RnConstants.KEY_TOKEN, tokenData.token)
171
+ promise.resolve(map)
172
+ }
173
+ } catch (e: Exception) {
174
+ promise.reject(RnConstants.ERR_GET_PUSH_TOKEN, e)
175
+ }
113
176
  }
114
-
115
- /**
116
- * Required by NativeEventEmitter (no-op on Android).
117
- *
118
- * @param count Number of JS listeners removed.
119
- */
120
- override fun removeListeners(count: Double) {
121
- // no-op
177
+ }
178
+
179
+ /**
180
+ * Sets or clears push token for the given provider.
181
+ *
182
+ * @param provider Provider identifier (must be non-blank).
183
+ * @param token Token string or `null` to clear (native expects String; `null` is converted to
184
+ * empty string).
185
+ * @param promise Resolves when the token is saved on native side.
186
+ */
187
+ override fun setPushToken(provider: String, token: String?, promise: Promise) {
188
+ if (provider.isBlank()) {
189
+ promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, RnConstants.MSG_PROVIDER_IS_BLANK)
190
+ return
122
191
  }
123
192
 
124
- // ---------------------- init ----------------------
125
-
126
- /**
127
- * Initializes the native Altcraft SDK using RN config map.
128
- *
129
- * @param config React Native configuration object.
130
- * ```
131
- * Required: `apiUrl`.
132
- * Optional: `rToken`, `appInfo`, `providerPriorityList`, `enableLogging`,
133
- * Android-only: `android_icon`, `android_usingService`, `android_serviceMessage`,
134
- * `android_pushReceiverModules`, `android_pushChannelName`, `android_pushChannelDescription`.
135
- * @param promise
136
- * ```
137
- * Promise resolved on success; rejected on invalid config or initialization failure.
138
- */
139
- override fun initialize(config: ReadableMap, promise: Promise) {
140
- AltcraftRnInitializer.initialize(
141
- reactContext = reactApplicationContext,
142
- config = config,
143
- promise = promise
193
+ coroutineScope.launch {
194
+ try {
195
+ val tokenToPass: String = token ?: ""
196
+
197
+ PublicPushTokenFunctions.setPushToken(
198
+ context = reactApplicationContext,
199
+ provider = provider,
200
+ token = tokenToPass
144
201
  )
202
+ promise.resolve(null)
203
+ } catch (e: Exception) {
204
+ promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, e)
205
+ }
145
206
  }
146
-
147
- // ---------------------- token-API for RN (ONLY getPushToken / setPushToken)
148
- // ----------------------
149
-
150
- /**
151
- * Returns current push token data from native side.
152
- *
153
- * @param promise Resolves to `{ provider, token }` or `null` if token is not available.
154
- */
155
- override fun getPushToken(promise: Promise) {
156
- coroutineScope.launch {
157
- try {
158
- val tokenData = PublicPushTokenFunctions.getPushToken(reactApplicationContext)
159
- if (tokenData == null) {
160
- promise.resolve(null)
161
- } else {
162
- val map = Arguments.createMap()
163
- map.putString(RnConstants.KEY_PROVIDER, tokenData.provider)
164
- map.putString(RnConstants.KEY_TOKEN, tokenData.token)
165
- promise.resolve(map)
166
- }
167
- } catch (e: Exception) {
168
- promise.reject(RnConstants.ERR_GET_PUSH_TOKEN, e)
169
- }
170
- }
207
+ }
208
+
209
+ // ---------------------- AltcraftSDK: clear / permission ----------------------
210
+
211
+ /**
212
+ * Clears SDK local state and stored data (native).
213
+ *
214
+ * @param promise Resolves after cleanup is finished.
215
+ */
216
+ override fun clear(promise: Promise) {
217
+ try {
218
+ AltcraftSDK.clear(reactApplicationContext) { promise.resolve(null) }
219
+ } catch (e: Exception) {
220
+ promise.reject(RnConstants.ERR_CLEAR, e)
171
221
  }
172
-
173
- /**
174
- * Sets or clears push token for the given provider.
175
- *
176
- * @param provider Provider identifier (must be non-blank).
177
- * @param token Token string or `null` to clear (native expects String; `null` is converted to
178
- * empty string).
179
- * @param promise Resolves when the token is saved on native side.
180
- */
181
- override fun setPushToken(provider: String, token: String?, promise: Promise) {
182
- if (provider.isBlank()) {
183
- promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, RnConstants.MSG_PROVIDER_IS_BLANK)
184
- return
222
+ }
223
+
224
+ /**
225
+ * Requests notification permission (Android-only runtime behavior). Safe no-op if current
226
+ * Activity is not a ComponentActivity.
227
+ */
228
+ override fun requestNotificationPermission() {
229
+ val activity = currentActivity
230
+ if (activity !is ComponentActivity) return
231
+
232
+ UiThreadUtil.runOnUiThread {
233
+ try {
234
+ AltcraftSDK.requestNotificationPermission(reactApplicationContext, activity)
235
+ } catch (_: Exception) {
236
+ // ignore
237
+ }
238
+ }
239
+ }
240
+
241
+ // ---------------------- MobileEvent bridge ----------------------
242
+
243
+ /**
244
+ * Sends a mobile event to the server (fire-and-forget).
245
+ *
246
+ * @param sid Pixel identifier.
247
+ * @param eventName Event name.
248
+ * @param sendMessageId Optional message identifier to link the event.
249
+ * @param payload Optional event payload (string-only map).
250
+ * @param matching Optional matching parameters (string-only map).
251
+ * @param matchingType Optional matching mode/type.
252
+ * @param profileFields Optional profile fields (string-only map).
253
+ * @param subscription Optional subscription info (email/sms/push/cc_data), converted on native
254
+ * side.
255
+ * @param utm Optional UTM tags for attribution.
256
+ */
257
+ override fun mobileEvent(
258
+ sid: String,
259
+ eventName: String,
260
+ sendMessageId: String?,
261
+ payload: ReadableMap?,
262
+ matching: ReadableMap?,
263
+ matchingType: String?,
264
+ profileFields: ReadableMap?,
265
+ subscription: ReadableMap?,
266
+ utm: ReadableMap?
267
+ ) {
268
+ try {
269
+ val utmData =
270
+ utm?.let {
271
+ DataClasses.UTM(
272
+ campaign = it.getString("campaign"),
273
+ content = it.getString("content"),
274
+ keyword = it.getString("keyword"),
275
+ medium = it.getString("medium"),
276
+ source = it.getString("source"),
277
+ temp = it.getString("temp")
278
+ )
185
279
  }
186
280
 
187
- coroutineScope.launch {
188
- try {
189
- val tokenToPass: String = token ?: ""
190
-
191
- PublicPushTokenFunctions.setPushToken(
192
- context = reactApplicationContext,
193
- provider = provider,
194
- token = tokenToPass
195
- )
196
- promise.resolve(null)
197
- } catch (e: Exception) {
198
- promise.reject(RnConstants.ERR_SET_PUSH_TOKEN, e)
199
- }
200
- }
281
+ PublicMobileEventFunctions.mobileEvent(
282
+ context = reactApplicationContext,
283
+ sid = sid,
284
+ eventName = eventName,
285
+ sendMessageId = sendMessageId,
286
+ payload = Converter.toKotlinMap(payload),
287
+ matching = Converter.toKotlinMap(matching),
288
+ matchingType = matchingType,
289
+ profileFields = Converter.toKotlinMap(profileFields),
290
+ subscription = Converter.toSubscriptionOrNull(subscription),
291
+ utm = utmData
292
+ )
293
+ } catch (e: Exception) {
294
+ Log.e("altcraft_lib_android_bridge", "mobileEvent failed: ${e.message}")
201
295
  }
202
-
203
- // ---------------------- AltcraftSDK: clear / permission ----------------------
204
-
205
- /**
206
- * Clears SDK local state and stored data (native).
207
- *
208
- * @param promise Resolves after cleanup is finished.
209
- */
210
- override fun clear(promise: Promise) {
211
- try {
212
- AltcraftSDK.clear(reactApplicationContext) { promise.resolve(null) }
213
- } catch (e: Exception) {
214
- promise.reject(RnConstants.ERR_CLEAR, e)
215
- }
296
+ }
297
+
298
+ // ---------------------- push payload bridge ----------------------
299
+
300
+ /**
301
+ * Forwards a push payload to native SDK (Android-only behavior).
302
+ *
303
+ * @param message Push payload map (string-only).
304
+ */
305
+ override fun takePush(message: ReadableMap?) {
306
+ try {
307
+ if (message == null) return
308
+ val map = Converter.toStringMapOrNull(message) ?: return
309
+ if (map.isNotEmpty()) {
310
+ AltcraftSDK.PushReceiver.takePush(reactApplicationContext, map)
311
+ }
312
+ } catch (e: Exception) {
313
+ Log.e("altcraft_lib_android_bridge", "takePush failed: ${e.message}")
216
314
  }
217
-
218
- /**
219
- * Requests notification permission (Android-only runtime behavior). Safe no-op if current
220
- * Activity is not a ComponentActivity.
221
- */
222
- override fun requestNotificationPermission() {
223
- val activity = currentActivity
224
- if (activity !is ComponentActivity) return
225
-
226
- UiThreadUtil.runOnUiThread {
227
- try {
228
- AltcraftSDK.requestNotificationPermission(reactApplicationContext, activity)
229
- } catch (_: Exception) {
230
- // ignore
231
- }
232
- }
315
+ }
316
+
317
+ // ---------------------- manual push events ----------------------
318
+
319
+ /**
320
+ * Reports a push delivery event (Android-only behavior).
321
+ *
322
+ * @param message Optional push payload (string-only map).
323
+ * @param messageUID Optional Altcraft message UID.
324
+ */
325
+ override fun deliveryEvent(message: ReadableMap?, messageUID: String?) {
326
+ try {
327
+ val map = Converter.toStringMapOrNull(message)
328
+ PublicPushEventFunctions.deliveryEvent(
329
+ context = reactApplicationContext,
330
+ message = map,
331
+ messageUID = messageUID
332
+ )
333
+ } catch (e: Exception) {
334
+ Log.e("altcraft_lib_android_bridge", "deliveryEvent failed: ${e.message}")
233
335
  }
234
-
235
- // ---------------------- MobileEvent bridge ----------------------
236
-
237
- /**
238
- * Sends a mobile event to the server (fire-and-forget).
239
- *
240
- * @param sid Pixel identifier.
241
- * @param eventName Event name.
242
- * @param sendMessageId Optional message identifier to link the event.
243
- * @param payload Optional event payload (string-only map).
244
- * @param matching Optional matching parameters (string-only map).
245
- * @param matchingType Optional matching mode/type.
246
- * @param profileFields Optional profile fields (string-only map).
247
- * @param subscription Optional subscription info (email/sms/push/cc_data), converted on native
248
- * side.
249
- * @param utm Optional UTM tags for attribution.
250
- */
251
- override fun mobileEvent(
252
- sid: String,
253
- eventName: String,
254
- sendMessageId: String?,
255
- payload: ReadableMap?,
256
- matching: ReadableMap?,
257
- matchingType: String?,
258
- profileFields: ReadableMap?,
259
- subscription: ReadableMap?,
260
- utm: ReadableMap?
261
- ) {
262
- try {
263
- val utmData =
264
- utm?.let {
265
- DataClasses.UTM(
266
- campaign = it.getString("campaign"),
267
- content = it.getString("content"),
268
- keyword = it.getString("keyword"),
269
- medium = it.getString("medium"),
270
- source = it.getString("source"),
271
- temp = it.getString("temp")
272
- )
273
- }
274
-
275
- PublicMobileEventFunction.mobileEvent(
276
- context = reactApplicationContext,
277
- sid = sid,
278
- eventName = eventName,
279
- sendMessageId = sendMessageId,
280
- payload = Converter.toKotlinMap(payload),
281
- matching = Converter.toKotlinMap(matching),
282
- matchingType = matchingType,
283
- profileFields = Converter.toKotlinMap(profileFields),
284
- subscription = Converter.toSubscriptionOrNull(subscription),
285
- utm = utmData
286
- )
287
- } catch (e: Exception) {
288
- // Log error but don't crash bridge
289
- e.printStackTrace()
290
- }
336
+ }
337
+
338
+ /**
339
+ * Reports a push open event (Android-only behavior).
340
+ *
341
+ * @param message Optional push payload (string-only map).
342
+ * @param messageUID Optional Altcraft message UID.
343
+ */
344
+ override fun openEvent(message: ReadableMap?, messageUID: String?) {
345
+ try {
346
+ val map = Converter.toStringMapOrNull(message)
347
+ PublicPushEventFunctions.openEvent(
348
+ context = reactApplicationContext,
349
+ message = map,
350
+ messageUID = messageUID
351
+ )
352
+ } catch (e: Exception) {
353
+ Log.e("altcraft_lib_android_bridge", "openEvent failed: ${e.message}")
291
354
  }
292
-
293
- // ---------------------- push payload bridge ----------------------
294
-
295
- /**
296
- * Forwards a push payload to native SDK (Android-only behavior).
297
- *
298
- * @param message Push payload map (string-only).
299
- */
300
- override fun takePush(message: ReadableMap?) {
301
- if (message == null) return
302
- val map = Converter.toStringMapOrNull(message) ?: return
303
- if (map.isNotEmpty()) {
304
- AltcraftSDK.PushReceiver.takePush(reactApplicationContext, map)
305
- }
355
+ }
356
+
357
+ // --------------------- Events bridge for RN ---------------------
358
+
359
+ /**
360
+ * Subscribes native SDK events stream and forwards events to JS via DeviceEventEmitter. Calling
361
+ * from JS multiple times replaces handler on JS side (native always emits to the same event
362
+ * name).
363
+ */
364
+ override fun subscribeToEvents() {
365
+ try {
366
+ Events.subscribe { event -> sendEventToJs(event) }
367
+ } catch (e: Exception) {
368
+ Log.e("altcraft_lib_android_bridge", "subscribeToEvents failed: ${e.message}")
306
369
  }
307
-
308
- // ---------------------- manual push events ----------------------
309
-
310
- /**
311
- * Reports a push delivery event (Android-only behavior).
312
- *
313
- * @param message Optional push payload (string-only map).
314
- * @param messageUID Optional Altcraft message UID.
315
- */
316
- override fun deliveryEvent(message: ReadableMap?, messageUID: String?) {
317
- try {
318
- val map = Converter.toStringMapOrNull(message)
319
- PublicPushEventFunctions.deliveryEvent(
320
- context = reactApplicationContext,
321
- message = map,
322
- messageUID = messageUID
323
- )
324
- } catch (_: Exception) {
325
- // ignore
326
- }
370
+ }
371
+
372
+ /** Unsubscribes native SDK events stream. */
373
+ override fun unsubscribeFromEvent() {
374
+ try {
375
+ Events.unsubscribe()
376
+ } catch (e: Exception) {
377
+ Log.e("altcraft_lib_android_bridge", "unsubscribeFromEvent failed: ${e.message}")
327
378
  }
328
-
329
- /**
330
- * Reports a push open event (Android-only behavior).
331
- *
332
- * @param message Optional push payload (string-only map).
333
- * @param messageUID Optional Altcraft message UID.
334
- */
335
- override fun openEvent(message: ReadableMap?, messageUID: String?) {
336
- try {
337
- val map = Converter.toStringMapOrNull(message)
338
- PublicPushEventFunctions.openEvent(
339
- context = reactApplicationContext,
340
- message = map,
341
- messageUID = messageUID
342
- )
343
- } catch (_: Exception) {
344
- // ignore
379
+ }
380
+
381
+ private fun sendEventToJs(event: DataClasses.Event) {
382
+ try {
383
+ val eventMap = Arguments.createMap()
384
+ eventMap.putString(RnConstants.KEY_FUNCTION, event.function)
385
+
386
+ val code = event.eventCode
387
+ if (code != null) eventMap.putInt(RnConstants.KEY_CODE, code)
388
+ else eventMap.putNull(RnConstants.KEY_CODE)
389
+
390
+ val message = event.eventMessage ?: event.toString()
391
+ eventMap.putString(RnConstants.KEY_MESSAGE, message)
392
+
393
+ val value = event.eventValue
394
+ if (value != null) {
395
+ val valueMap = Arguments.createMap()
396
+ for ((key, anyValue) in value.entries) {
397
+ when (anyValue) {
398
+ null -> valueMap.putNull(key)
399
+ is String -> valueMap.putString(key, anyValue)
400
+ is Boolean -> valueMap.putBoolean(key, anyValue)
401
+ is Int -> valueMap.putInt(key, anyValue)
402
+ is Double -> valueMap.putDouble(key, anyValue)
403
+ is Float -> valueMap.putDouble(key, anyValue.toDouble())
404
+ is Long -> valueMap.putDouble(key, anyValue.toDouble())
405
+ else -> valueMap.putString(key, anyValue.toString())
406
+ }
345
407
  }
346
- }
347
-
348
- // --------------------- Events bridge for RN ---------------------
408
+ eventMap.putMap(RnConstants.KEY_VALUE, valueMap)
409
+ } else {
410
+ eventMap.putNull(RnConstants.KEY_VALUE)
411
+ }
412
+ val type =
413
+ when (event) {
414
+ is DataClasses.Error -> RnConstants.TYPE_ERROR
415
+ is DataClasses.RetryError -> RnConstants.TYPE_RETRY_ERROR
416
+ else -> RnConstants.TYPE_EVENT
417
+ }
418
+ eventMap.putString(RnConstants.KEY_TYPE, type)
349
419
 
350
- /**
351
- * Subscribes native SDK events stream and forwards events to JS via DeviceEventEmitter. Calling
352
- * from JS multiple times replaces handler on JS side (native always emits to the same event
353
- * name).
354
- */
355
- override fun subscribeToEvents() {
356
- Events.subscribe { event -> sendEventToJs(event) }
420
+ SdkEventEmitter.emit(RnConstants.JS_EVENT_NAME, eventMap)
421
+ } catch (e: Exception) {
422
+ Log.e("altcraft_lib_android_bridge", "sendEventToJs failed: ${e.message}")
357
423
  }
358
-
359
- /** Unsubscribes native SDK events stream. */
360
- override fun unsubscribeFromEvent() {
361
- Events.unsubscribe()
424
+ }
425
+
426
+ // --------------------- subscription bridge ---------------------
427
+
428
+ /**
429
+ * Sends a push subscribe request.
430
+ *
431
+ * @param sync Execution mode:
432
+ * ```
433
+ * `true` — synchronous server request returning the operation result.
434
+ * `false` — asynchronous server request returning enqueue result.
435
+ * `null` — defaults to `true` on Android bridge.
436
+ * @param profileFields
437
+ * ```
438
+ * Optional profile fields (string-only map).
439
+ * @param customFields Optional custom fields (string-only map).
440
+ * @param cats Optional categories list.
441
+ * @param replace Optional flag to replace an existing subscription.
442
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
443
+ */
444
+ override fun pushSubscribe(
445
+ sync: Boolean?,
446
+ profileFields: ReadableMap?,
447
+ customFields: ReadableMap?,
448
+ cats: ReadableArray?,
449
+ replace: Boolean?,
450
+ skipTriggers: Boolean?
451
+ ) {
452
+ try {
453
+ val isSync = sync ?: true
454
+ PublicPushSubscriptionFunctions.pushSubscribe(
455
+ context = reactApplicationContext,
456
+ sync = isSync,
457
+ profileFields = Converter.toKotlinMap(profileFields),
458
+ customFields = Converter.toKotlinMap(customFields),
459
+ cats = Converter.toCategoryListOrNull(cats),
460
+ replace = replace,
461
+ skipTriggers = skipTriggers
462
+ )
463
+ } catch (e: Exception) {
464
+ Log.e("altcraft_lib_android_bridge", "pushSubscribe failed: ${e.message}")
362
465
  }
363
-
364
- private fun sendEventToJs(event: DataClasses.Event) {
365
- val eventMap = Arguments.createMap()
366
- eventMap.putString(RnConstants.KEY_FUNCTION, event.function)
367
-
368
- val code = event.eventCode
369
- if (code != null) eventMap.putInt(RnConstants.KEY_CODE, code)
370
- else eventMap.putNull(RnConstants.KEY_CODE)
371
-
372
- val message = event.eventMessage ?: event.toString()
373
- eventMap.putString(RnConstants.KEY_MESSAGE, message)
374
-
375
- val value = event.eventValue
376
- if (value != null) {
377
- val valueMap = Arguments.createMap()
378
- for ((key, anyValue) in value.entries) {
379
- when (anyValue) {
380
- null -> valueMap.putNull(key)
381
- is String -> valueMap.putString(key, anyValue)
382
- is Boolean -> valueMap.putBoolean(key, anyValue)
383
- is Int -> valueMap.putInt(key, anyValue)
384
- is Double -> valueMap.putDouble(key, anyValue)
385
- is Float -> valueMap.putDouble(key, anyValue.toDouble())
386
- is Long -> valueMap.putDouble(key, anyValue.toDouble())
387
- else -> valueMap.putString(key, anyValue.toString())
388
- }
389
- }
390
- eventMap.putMap(RnConstants.KEY_VALUE, valueMap)
391
- } else {
392
- eventMap.putNull(RnConstants.KEY_VALUE)
393
- }
394
- val type =
395
- when (event) {
396
- is DataClasses.Error -> RnConstants.TYPE_ERROR
397
- is DataClasses.RetryError -> RnConstants.TYPE_RETRY_ERROR
398
- else -> RnConstants.TYPE_EVENT
399
- }
400
- eventMap.putString(RnConstants.KEY_TYPE, type)
401
-
402
- reactApplicationContext
403
- .getJSModule(RCTDeviceEventEmitter::class.java)
404
- .emit(RnConstants.JS_EVENT_NAME, eventMap)
466
+ }
467
+
468
+ /**
469
+ * Sends a push suspend request.
470
+ *
471
+ * @param sync Execution mode (see [pushSubscribe]).
472
+ * @param profileFields Optional profile fields (string-only map).
473
+ * @param customFields Optional custom fields (string-only map).
474
+ * @param cats Optional categories list.
475
+ * @param replace Optional flag to replace an existing subscription.
476
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
477
+ */
478
+ override fun pushSuspend(
479
+ sync: Boolean?,
480
+ profileFields: ReadableMap?,
481
+ customFields: ReadableMap?,
482
+ cats: ReadableArray?,
483
+ replace: Boolean?,
484
+ skipTriggers: Boolean?
485
+ ) {
486
+ try {
487
+ val isSync = sync ?: true
488
+ PublicPushSubscriptionFunctions.pushSuspend(
489
+ context = reactApplicationContext,
490
+ sync = isSync,
491
+ profileFields = Converter.toKotlinMap(profileFields),
492
+ customFields = Converter.toKotlinMap(customFields),
493
+ cats = Converter.toCategoryListOrNull(cats),
494
+ replace = replace,
495
+ skipTriggers = skipTriggers
496
+ )
497
+ } catch (e: Exception) {
498
+ Log.e("altcraft_lib_android_bridge", "pushSuspend failed: ${e.message}")
405
499
  }
406
-
407
- // --------------------- subscription bridge ---------------------
408
-
409
- /**
410
- * Sends a push subscribe request.
411
- *
412
- * @param sync Execution mode:
413
- * ```
414
- * `true` — synchronous server request returning the operation result.
415
- * `false` — asynchronous server request returning enqueue result.
416
- * `null` — defaults to `true` on Android bridge.
417
- * @param profileFields
418
- * ```
419
- * Optional profile fields (string-only map).
420
- * @param customFields Optional custom fields (string-only map).
421
- * @param cats Optional categories list.
422
- * @param replace Optional flag to replace an existing subscription.
423
- * @param skipTriggers Optional flag to skip trigger execution on the server.
424
- */
425
- override fun pushSubscribe(
426
- sync: Boolean?,
427
- profileFields: ReadableMap?,
428
- customFields: ReadableMap?,
429
- cats: ReadableArray?,
430
- replace: Boolean?,
431
- skipTriggers: Boolean?
432
- ) {
433
- val isSync = sync ?: true
434
- PublicPushSubscriptionFunctions.pushSubscribe(
435
- context = reactApplicationContext,
436
- sync = isSync,
437
- profileFields = Converter.toKotlinMap(profileFields),
438
- customFields = Converter.toKotlinMap(customFields),
439
- cats = Converter.toCategoryListOrNull(cats),
440
- replace = replace,
441
- skipTriggers = skipTriggers
442
- )
500
+ }
501
+
502
+ /**
503
+ * Sends a push unsubscribe request.
504
+ *
505
+ * @param sync Execution mode (see [pushSubscribe]).
506
+ * @param profileFields Optional profile fields (string-only map).
507
+ * @param customFields Optional custom fields (string-only map).
508
+ * @param cats Optional categories list.
509
+ * @param replace Optional flag to replace an existing subscription.
510
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
511
+ */
512
+ override fun pushUnSubscribe(
513
+ sync: Boolean?,
514
+ profileFields: ReadableMap?,
515
+ customFields: ReadableMap?,
516
+ cats: ReadableArray?,
517
+ replace: Boolean?,
518
+ skipTriggers: Boolean?
519
+ ) {
520
+ try {
521
+ val isSync = sync ?: true
522
+ PublicPushSubscriptionFunctions.pushUnSubscribe(
523
+ context = reactApplicationContext,
524
+ sync = isSync,
525
+ profileFields = Converter.toKotlinMap(profileFields),
526
+ customFields = Converter.toKotlinMap(customFields),
527
+ cats = Converter.toCategoryListOrNull(cats),
528
+ replace = replace,
529
+ skipTriggers = skipTriggers
530
+ )
531
+ } catch (e: Exception) {
532
+ Log.e("altcraft_lib_android_bridge", "pushUnSubscribe failed: ${e.message}")
443
533
  }
444
-
445
- /**
446
- * Sends a push suspend request.
447
- *
448
- * @param sync Execution mode (see [pushSubscribe]).
449
- * @param profileFields Optional profile fields (string-only map).
450
- * @param customFields Optional custom fields (string-only map).
451
- * @param cats Optional categories list.
452
- * @param replace Optional flag to replace an existing subscription.
453
- * @param skipTriggers Optional flag to skip trigger execution on the server.
454
- */
455
- override fun pushSuspend(
456
- sync: Boolean?,
457
- profileFields: ReadableMap?,
458
- customFields: ReadableMap?,
459
- cats: ReadableArray?,
460
- replace: Boolean?,
461
- skipTriggers: Boolean?
462
- ) {
463
- val isSync = sync ?: true
464
- PublicPushSubscriptionFunctions.pushSuspend(
465
- context = reactApplicationContext,
466
- sync = isSync,
467
- profileFields = Converter.toKotlinMap(profileFields),
468
- customFields = Converter.toKotlinMap(customFields),
469
- cats = Converter.toCategoryListOrNull(cats),
470
- replace = replace,
471
- skipTriggers = skipTriggers
472
- )
534
+ }
535
+
536
+ // --------------------- async status bridges ---------------------
537
+
538
+ /**
539
+ * Unsuspends push subscriptions based on native matching rules.
540
+ *
541
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
542
+ */
543
+ override fun unSuspendPushSubscription(promise: Promise) {
544
+ coroutineScope.launch {
545
+ try {
546
+ val res =
547
+ PublicPushSubscriptionFunctions.unSuspendPushSubscription(
548
+ reactApplicationContext
549
+ )
550
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
551
+ } catch (e: Exception) {
552
+ promise.reject(RnConstants.ERR_UNSUSPEND, e)
553
+ }
473
554
  }
474
-
475
- /**
476
- * Sends a push unsubscribe request.
477
- *
478
- * @param sync Execution mode (see [pushSubscribe]).
479
- * @param profileFields Optional profile fields (string-only map).
480
- * @param customFields Optional custom fields (string-only map).
481
- * @param cats Optional categories list.
482
- * @param replace Optional flag to replace an existing subscription.
483
- * @param skipTriggers Optional flag to skip trigger execution on the server.
484
- */
485
- override fun pushUnSubscribe(
486
- sync: Boolean?,
487
- profileFields: ReadableMap?,
488
- customFields: ReadableMap?,
489
- cats: ReadableArray?,
490
- replace: Boolean?,
491
- skipTriggers: Boolean?
492
- ) {
493
- val isSync = sync ?: true
494
- PublicPushSubscriptionFunctions.pushUnSubscribe(
495
- context = reactApplicationContext,
496
- sync = isSync,
497
- profileFields = Converter.toKotlinMap(profileFields),
498
- customFields = Converter.toKotlinMap(customFields),
499
- cats = Converter.toCategoryListOrNull(cats),
500
- replace = replace,
501
- skipTriggers = skipTriggers
502
- )
555
+ }
556
+
557
+ /**
558
+ * Returns the status of the latest subscription in profile.
559
+ *
560
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
561
+ */
562
+ override fun getStatusOfLatestSubscription(promise: Promise) {
563
+ coroutineScope.launch {
564
+ try {
565
+ val res =
566
+ PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
567
+ reactApplicationContext
568
+ )
569
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
570
+ } catch (e: Exception) {
571
+ promise.reject(RnConstants.ERR_GET_LATEST_STATUS, e)
572
+ }
503
573
  }
504
-
505
- // --------------------- async status bridges ---------------------
506
-
507
- /**
508
- * Unsuspends push subscriptions based on native matching rules.
509
- *
510
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
511
- */
512
- override fun unSuspendPushSubscription(promise: Promise) {
513
- coroutineScope.launch {
514
- try {
515
- val res =
516
- PublicPushSubscriptionFunctions.unSuspendPushSubscription(
517
- reactApplicationContext
518
- )
519
- promise.resolve(responseWithHttpCodeToWritableMap(res))
520
- } catch (e: Exception) {
521
- promise.reject(RnConstants.ERR_UNSUSPEND, e)
522
- }
523
- }
574
+ }
575
+
576
+ /**
577
+ * Returns the status of the latest subscription for the given provider.
578
+ *
579
+ * @param provider Optional provider identifier (may be null).
580
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
581
+ */
582
+ override fun getStatusOfLatestSubscriptionForProvider(provider: String?, promise: Promise) {
583
+ coroutineScope.launch {
584
+ try {
585
+ val res =
586
+ PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
587
+ context = reactApplicationContext,
588
+ provider = provider
589
+ )
590
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
591
+ } catch (e: Exception) {
592
+ promise.reject(RnConstants.ERR_GET_LATEST_STATUS_PROVIDER, e)
593
+ }
524
594
  }
525
-
526
- /**
527
- * Returns the status of the latest subscription in profile.
528
- *
529
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
530
- */
531
- override fun getStatusOfLatestSubscription(promise: Promise) {
532
- coroutineScope.launch {
533
- try {
534
- val res =
535
- PublicPushSubscriptionFunctions.getStatusOfLatestSubscription(
536
- reactApplicationContext
537
- )
538
- promise.resolve(responseWithHttpCodeToWritableMap(res))
539
- } catch (e: Exception) {
540
- promise.reject(RnConstants.ERR_GET_LATEST_STATUS, e)
541
- }
542
- }
595
+ }
596
+
597
+ /**
598
+ * Returns the status for current subscription (by current provider/token context).
599
+ *
600
+ * @param promise Resolves to response with HTTP code or `null` if unavailable.
601
+ */
602
+ override fun getStatusForCurrentSubscription(promise: Promise) {
603
+ coroutineScope.launch {
604
+ try {
605
+ val res =
606
+ PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
607
+ reactApplicationContext
608
+ )
609
+ promise.resolve(responseWithHttpCodeToWritableMap(res))
610
+ } catch (e: Exception) {
611
+ promise.reject(RnConstants.ERR_GET_CURRENT_STATUS, e)
612
+ }
543
613
  }
544
-
545
- /**
546
- * Returns the status of the latest subscription for the given provider.
547
- *
548
- * @param provider Optional provider identifier (may be null).
549
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
550
- */
551
- override fun getStatusOfLatestSubscriptionForProvider(provider: String?, promise: Promise) {
552
- coroutineScope.launch {
553
- try {
554
- val res =
555
- PublicPushSubscriptionFunctions.getStatusOfLatestSubscriptionForProvider(
556
- context = reactApplicationContext,
557
- provider = provider
558
- )
559
- promise.resolve(responseWithHttpCodeToWritableMap(res))
560
- } catch (e: Exception) {
561
- promise.reject(RnConstants.ERR_GET_LATEST_STATUS_PROVIDER, e)
562
- }
563
- }
614
+ }
615
+
616
+ // ---------------------- Profile API ----------------------
617
+
618
+ /**
619
+ * Updates profile fields on the server.
620
+ *
621
+ * @param profileFields Optional profile fields (string-only map).
622
+ * @param skipTriggers Optional flag to skip trigger execution on the server.
623
+ */
624
+ override fun updateProfileFields(
625
+ profileFields: ReadableMap?,
626
+ skipTriggers: Boolean?
627
+ ) {
628
+ try {
629
+ PublicProfileFunctions.updateProfileFields(
630
+ context = reactApplicationContext,
631
+ profileFields = Converter.toKotlinMap(profileFields),
632
+ skipTriggers = skipTriggers
633
+ )
634
+ } catch (e: Exception) {
635
+ Log.e("altcraft_lib_android_bridge", "updateProfileFields failed: ${e.message}")
564
636
  }
565
-
566
- /**
567
- * Returns the status for current subscription (by current provider/token context).
568
- *
569
- * @param promise Resolves to response with HTTP code or `null` if unavailable.
570
- */
571
- override fun getStatusForCurrentSubscription(promise: Promise) {
572
- coroutineScope.launch {
573
- try {
574
- val res =
575
- PublicPushSubscriptionFunctions.getStatusForCurrentSubscription(
576
- reactApplicationContext
577
- )
578
- promise.resolve(responseWithHttpCodeToWritableMap(res))
579
- } catch (e: Exception) {
580
- promise.reject(RnConstants.ERR_GET_CURRENT_STATUS, e)
581
- }
637
+ }
638
+
639
+ // ---------------------- Token management API ----------------------
640
+
641
+ /**
642
+ * Forces a push token refresh (delete + re-register).
643
+ *
644
+ * @param promise Resolves when the token update flow completes.
645
+ */
646
+ override fun forcedTokenUpdate(promise: Promise) {
647
+ coroutineScope.launch {
648
+ try {
649
+ PublicPushTokenFunctions.forcedTokenUpdate(reactApplicationContext) {
650
+ promise.resolve(null)
582
651
  }
652
+ } catch (e: Exception) {
653
+ promise.reject(RnConstants.ERR_FORCED_TOKEN_UPDATE, e)
654
+ }
583
655
  }
584
-
585
- /**
586
- * Maps {@link DataClasses.ResponseWithHttpCode} to a RN {@link WritableMap}. Returns `null` if
587
- * input is `null`. Unmapped fields (`fields`, `cats`) are set to `null`.
588
- */
589
- private fun responseWithHttpCodeToWritableMap(
590
- data: DataClasses.ResponseWithHttpCode?
591
- ): WritableMap? {
592
- if (data == null) return null
593
-
594
- val resp = data.response
595
-
596
- return Arguments.createMap().apply root@{
597
- putNullableInt(RnConstants.KEY_HTTP_CODE, data.httpCode)
598
-
599
- if (resp == null) {
600
- putNull(RnConstants.KEY_RESPONSE)
601
- return@root
602
- }
603
-
604
- val respMap =
605
- Arguments.createMap().apply resp@{
606
- putNullableInt(RnConstants.KEY_ERROR, resp.error)
607
- putNullableString(RnConstants.KEY_ERROR_TEXT, resp.errorText)
608
-
609
- val profile = resp.profile
610
- if (profile == null) {
611
- putNull(RnConstants.KEY_PROFILE)
612
- return@resp
613
- }
614
-
615
- val profileMap =
616
- Arguments.createMap().apply profile@{
617
- putNullableString(RnConstants.KEY_ID, profile.id)
618
- putNullableString(RnConstants.KEY_STATUS, profile.status)
619
- putNullableBoolean(RnConstants.KEY_IS_TEST, profile.isTest)
620
-
621
- val sub = profile.subscription
622
- if (sub == null) {
623
- putNull(RnConstants.KEY_SUBSCRIPTION)
624
- return@profile
625
- }
626
-
627
- val subMap =
628
- Arguments.createMap().apply sub@{
629
- putNullableString(
630
- RnConstants.KEY_SUBSCRIPTION_ID,
631
- sub.subscriptionId
632
- )
633
- putNullableString(
634
- RnConstants.KEY_HASH_ID,
635
- sub.hashId
636
- )
637
- putNullableString(
638
- RnConstants.KEY_PROVIDER,
639
- sub.provider
640
- )
641
- putNullableString(
642
- RnConstants.KEY_STATUS,
643
- sub.status
644
- )
645
-
646
- putNull(RnConstants.KEY_FIELDS)
647
- putNull(RnConstants.KEY_CATS)
648
- }
649
-
650
- putMap(RnConstants.KEY_SUBSCRIPTION, subMap)
651
- }
652
-
653
- putMap(RnConstants.KEY_PROFILE, profileMap)
654
- }
655
-
656
- putMap(RnConstants.KEY_RESPONSE, respMap)
657
- }
656
+ }
657
+
658
+ /**
659
+ * Deletes the device token for a given provider.
660
+ *
661
+ * @param provider Provider identifier (e.g. `android-firebase`).
662
+ * @param promise Resolves when the delete call is dispatched.
663
+ */
664
+ override fun deleteDeviceToken(provider: String, promise: Promise) {
665
+ try {
666
+ PublicPushTokenFunctions.deleteDeviceToken(
667
+ context = reactApplicationContext,
668
+ provider = provider
669
+ ) {
670
+ promise.resolve(null)
671
+ }
672
+ } catch (e: Exception) {
673
+ promise.reject(RnConstants.ERR_DELETE_DEVICE_TOKEN, e)
658
674
  }
675
+ }
676
+
677
+ /**
678
+ * Changes the push provider priority list at runtime.
679
+ *
680
+ * @param priorityList Ordered list of provider identifiers.
681
+ * @param promise Resolves when the priority list is updated and token update is triggered.
682
+ */
683
+ override fun changePushProviderPriorityList(priorityList: ReadableArray, promise: Promise) {
684
+ coroutineScope.launch {
685
+ try {
686
+ val list = priorityList.toStringList()
687
+ PublicPushTokenFunctions.changePushProviderPriorityList(
688
+ context = reactApplicationContext,
689
+ priorityList = list
690
+ )
691
+ promise.resolve(null)
692
+ } catch (e: Exception) {
693
+ promise.reject(RnConstants.ERR_CHANGE_PROVIDER_PRIORITY, e)
694
+ }
695
+ }
696
+ }
697
+
698
+ // ---------------------- PushReceiver helpers ----------------------
699
+
700
+ /**
701
+ * Checks whether a push payload belongs to Altcraft.
702
+ *
703
+ * @param message Push payload map (string-only).
704
+ * @return `true` if the message contains the Altcraft marker key.
705
+ */
706
+ override fun isAltcraftPush(message: ReadableMap?): Boolean {
707
+ try {
708
+ if (message == null) return false
709
+ val map = Converter.toStringMapOrNull(message) ?: return false
710
+ return AltcraftSDK.PushReceiver.isAltcraftPush(map)
711
+ } catch (e: Exception) {
712
+ Log.e("altcraft_lib_android_bridge", "isAltcraftPush failed: ${e.message}")
713
+ return false
714
+ }
715
+ }
716
+
717
+ // ---------------------- SDK lifecycle ----------------------
718
+
719
+ /**
720
+ * Allows re-running initial retry/scheduling/token-check logic
721
+ * in this process on the next [initialization].
722
+ */
723
+ override fun unlockInitialOperationsInThisSession() {
724
+ try {
725
+ AltcraftSDK.unlockInitialOperationsInThisSession()
726
+ } catch (e: Exception) {
727
+ Log.e(
728
+ "altcraft_lib_android_bridge",
729
+ "unlockInitialOperationsInThisSession failed: ${e.message}"
730
+ )
731
+ }
732
+ }
733
+
734
+ /**
735
+ * Sets the App Group name (iOS-only, no-op on Android).
736
+ */
737
+ override fun setAppGroup(groupName: String?) {
738
+ // no-op on Android
739
+ }
740
+
741
+ /**
742
+ * Maps {@link DataClasses.ResponseWithHttpCode} to a RN {@link WritableMap}. Returns `null` if
743
+ * input is `null`. Unmapped fields (`fields`, `cats`) are set to `null`.
744
+ */
745
+ private fun responseWithHttpCodeToWritableMap(
746
+ data: DataClasses.ResponseWithHttpCode?
747
+ ): WritableMap? {
748
+ if (data == null) return null
749
+
750
+ val resp = data.response
751
+
752
+ return Arguments.createMap().apply root@{
753
+ putNullableInt(RnConstants.KEY_HTTP_CODE, data.httpCode)
754
+
755
+ if (resp == null) {
756
+ putNull(RnConstants.KEY_RESPONSE)
757
+ return@root
758
+ }
759
+
760
+ val respMap =
761
+ Arguments.createMap().apply resp@{
762
+ putNullableInt(RnConstants.KEY_ERROR, resp.error)
763
+ putNullableString(RnConstants.KEY_ERROR_TEXT, resp.errorText)
764
+
765
+ val profile = resp.profile
766
+ if (profile == null) {
767
+ putNull(RnConstants.KEY_PROFILE)
768
+ return@resp
769
+ }
770
+
771
+ val profileMap =
772
+ Arguments.createMap().apply profile@{
773
+ putNullableString(RnConstants.KEY_ID, profile.id)
774
+ putNullableString(RnConstants.KEY_STATUS, profile.status)
775
+ putNullableBoolean(RnConstants.KEY_IS_TEST, profile.isTest)
776
+
777
+ val sub = profile.subscription
778
+ if (sub == null) {
779
+ putNull(RnConstants.KEY_SUBSCRIPTION)
780
+ return@profile
781
+ }
782
+
783
+ val subMap =
784
+ Arguments.createMap().apply sub@{
785
+ putNullableString(
786
+ RnConstants.KEY_SUBSCRIPTION_ID,
787
+ sub.subscriptionId
788
+ )
789
+ putNullableString(
790
+ RnConstants.KEY_HASH_ID,
791
+ sub.hashId
792
+ )
793
+ putNullableString(
794
+ RnConstants.KEY_PROVIDER,
795
+ sub.provider
796
+ )
797
+ putNullableString(
798
+ RnConstants.KEY_STATUS,
799
+ sub.status
800
+ )
801
+
802
+ putNull(RnConstants.KEY_FIELDS)
803
+ putNull(RnConstants.KEY_CATS)
804
+ }
659
805
 
660
- /**
661
- * Stores a key-value pair in native persistent storage.
662
- *
663
- * Platform behavior:
664
- * - iOS: uses UserDefaults (optionally scoped by `suiteName` / App Group).
665
- * - Android: uses SharedPreferences; `suiteName` is used as preferences name.
666
- *
667
- * Supported value types:
668
- * - primitives (Boolean, Number, String)
669
- * - complex structures serialized as JSON string
670
- * - `null` removes the stored value
671
- *
672
- * @param suiteName Storage namespace / suite name (platform-dependent).
673
- * @param key Storage key.
674
- * @param value Value to store or `null` to remove.
675
- */
676
- override fun setUserDefaultsValue(suiteName: String?, key: String, value: String?) {
677
- val k = key.trim()
678
- if (k.isEmpty()) return
679
-
680
- val prefsName =
681
- suiteName?.trim().takeUnless { it.isNullOrEmpty() }
682
- ?: reactApplicationContext.packageName
683
-
684
- val prefs =
685
- reactApplicationContext.getSharedPreferences(
686
- prefsName,
687
- android.content.Context.MODE_PRIVATE
688
- )
689
-
690
- if (value == null) {
691
- prefs.edit().remove(k).apply()
692
- return
693
- }
694
-
695
- val v = value.trim()
696
-
697
- // Store JSON as String (SharedPreferences has no native JSON type)
698
- if ((v.startsWith("{") && v.endsWith("}")) || (v.startsWith("[") && v.endsWith("]"))) {
699
- prefs.edit().putString(k, v).apply()
700
- return
701
- }
702
-
703
- // Boolean
704
- if (v.equals("true", ignoreCase = true) || v.equals("false", ignoreCase = true)) {
705
- prefs.edit().putBoolean(k, v.equals("true", ignoreCase = true)).apply()
706
- return
707
- }
708
-
709
- // Integer (Long)
710
- v.toLongOrNull()?.let { asLong ->
711
- prefs.edit().putLong(k, asLong).apply()
712
- return
713
- }
806
+ putMap(RnConstants.KEY_SUBSCRIPTION, subMap)
807
+ }
714
808
 
715
- // Double -> keep precision as String
716
- v.toDoubleOrNull()?.let {
717
- prefs.edit().putString(k, v).apply()
718
- return
809
+ putMap(RnConstants.KEY_PROFILE, profileMap)
719
810
  }
720
811
 
721
- // Fallback: String
722
- prefs.edit().putString(k, value).apply()
812
+ putMap(RnConstants.KEY_RESPONSE, respMap)
723
813
  }
814
+ }
815
+
816
+ /**
817
+ * Stores a key-value pair in native persistent storage.
818
+ *
819
+ * Platform behavior:
820
+ * - iOS: uses UserDefaults (optionally scoped by `suiteName` / App Group).
821
+ * - Android: uses SharedPreferences; `suiteName` is used as preferences name.
822
+ *
823
+ * Supported value types:
824
+ * - primitives (Boolean, Number, String)
825
+ * - complex structures serialized as JSON string
826
+ * - `null` removes the stored value
827
+ *
828
+ * @param suiteName Storage namespace / suite name (platform-dependent).
829
+ * @param key Storage key.
830
+ * @param value Value to store or `null` to remove.
831
+ */
832
+ override fun setUserDefaultsValue(suiteName: String?, key: String, value: String?) {
833
+ try {
834
+ val k = key.trim()
835
+ if (k.isEmpty()) return
836
+
837
+ val prefsName =
838
+ suiteName?.trim().takeUnless { it.isNullOrEmpty() }
839
+ ?: reactApplicationContext.packageName
840
+
841
+ val prefs =
842
+ reactApplicationContext.getSharedPreferences(
843
+ prefsName,
844
+ android.content.Context.MODE_PRIVATE
845
+ )
724
846
 
725
- companion object {
726
- const val NAME: String = RnConstants.MODULE_NAME
847
+ if (value == null) {
848
+ prefs.edit().remove(k).apply()
849
+ return
850
+ }
851
+
852
+ val v = value.trim()
853
+
854
+ // Store JSON as String (SharedPreferences has no native JSON type)
855
+ if ((v.startsWith("{") && v.endsWith("}")) || (v.startsWith("[") && v.endsWith("]"))) {
856
+ prefs.edit().putString(k, v).apply()
857
+ return
858
+ }
859
+
860
+ // Boolean
861
+ if (v.equals("true", ignoreCase = true) || v.equals("false", ignoreCase = true)) {
862
+ prefs.edit().putBoolean(k, v.equals("true", ignoreCase = true)).apply()
863
+ return
864
+ }
865
+
866
+ // Integer (Long)
867
+ v.toLongOrNull()?.let { asLong ->
868
+ prefs.edit().putLong(k, asLong).apply()
869
+ return
870
+ }
871
+
872
+ // Double -> keep precision as String
873
+ v.toDoubleOrNull()?.let {
874
+ prefs.edit().putString(k, v).apply()
875
+ return
876
+ }
877
+
878
+ // Fallback: String
879
+ prefs.edit().putString(k, value).apply()
880
+ } catch (e: Exception) {
881
+ Log.e("altcraft_lib_android_bridge", "setUserDefaultsValue failed: ${e.message}")
727
882
  }
883
+ }
884
+
885
+ companion object {
886
+ const val NAME: String = RnConstants.MODULE_NAME
887
+ }
728
888
  }
729
889
 
730
890
  /** Internal RN initializer entry point. */
731
891
  internal object AltcraftRnInitializer {
732
892
 
733
- fun initialize(reactContext: ReactApplicationContext, config: ReadableMap, promise: Promise) {
734
- try {
735
- val configuration = AltcraftRnConfigMapper.buildConfiguration(config)
736
-
737
- AltcraftSDK.initialization(reactContext, configuration) { result ->
738
- reactContext.runOnUiQueueThread {
739
- if (result.isSuccess) {
740
- promise.resolve(null)
741
- } else {
742
- val throwable = result.exceptionOrNull()
743
- if (throwable != null) {
744
- promise.reject(
745
- RnConstants.ERR_INIT_ERROR,
746
- throwable.message ?: RnConstants.MSG_INIT_ERROR,
747
- throwable
748
- )
749
- } else {
750
- promise.reject(RnConstants.ERR_INIT_ERROR, RnConstants.MSG_INIT_UNKNOWN)
751
- }
752
- }
753
- }
893
+ fun initialize(reactContext: ReactApplicationContext, config: ReadableMap, promise: Promise) {
894
+ try {
895
+ val configuration = AltcraftRnConfigMapper.buildConfiguration(config)
896
+
897
+ AltcraftSDK.initialization(reactContext, configuration) { result ->
898
+ reactContext.runOnUiQueueThread {
899
+ if (result.isSuccess) {
900
+ promise.resolve(null)
901
+ } else {
902
+ val throwable = result.exceptionOrNull()
903
+ if (throwable != null) {
904
+ promise.reject(
905
+ RnConstants.ERR_INIT_ERROR,
906
+ throwable.message ?: RnConstants.MSG_INIT_ERROR,
907
+ throwable
908
+ )
909
+ } else {
910
+ promise.reject(RnConstants.ERR_INIT_ERROR, RnConstants.MSG_INIT_UNKNOWN)
754
911
  }
755
- } catch (e: Exception) {
756
- promise.reject(
757
- RnConstants.ERR_INIT_INVALID_CONFIG,
758
- e.message ?: "Invalid Altcraft configuration",
759
- e
760
- )
912
+ }
761
913
  }
914
+ }
915
+ } catch (e: Exception) {
916
+ promise.reject(
917
+ RnConstants.ERR_INIT_INVALID_CONFIG,
918
+ e.message ?: "Invalid Altcraft configuration",
919
+ e
920
+ )
762
921
  }
922
+ }
763
923
  }
764
924
 
765
925
  /** Maps React Native configuration object to native [AltcraftConfiguration]. */
766
926
  internal object AltcraftRnConfigMapper {
767
927
 
768
- private const val KEY_API_URL = "apiUrl"
769
- private const val KEY_R_TOKEN = "rToken"
770
- private const val KEY_APP_INFO = "appInfo"
771
- private const val KEY_PROVIDER_PRIORITY_LIST = "providerPriorityList"
772
- private const val KEY_ENABLE_LOGGING = "enableLogging"
773
-
774
- private const val KEY_ANDROID_ICON = "android_icon"
775
- private const val KEY_ANDROID_USING_SERVICE = "android_usingService"
776
- private const val KEY_ANDROID_SERVICE_MESSAGE = "android_serviceMessage"
777
- private const val KEY_ANDROID_PUSH_RECEIVER_MODULES = "android_pushReceiverModules"
778
- private const val KEY_ANDROID_PUSH_CHANNEL_NAME = "android_pushChannelName"
779
- private const val KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION = "android_pushChannelDescription"
780
-
781
- private const val KEY_APP_ID = "appID"
782
- private const val KEY_APP_IID = "appIID"
783
- private const val KEY_APP_VER = "appVer"
784
-
785
- private const val MSG_API_URL_REQUIRED = "apiUrl is required for AltcraftConfiguration"
786
- private const val MSG_API_URL_MUST_BE_STRING = "apiUrl must be a non-null string"
787
-
788
- fun buildConfiguration(config: ReadableMap): AltcraftConfiguration {
789
- if (!config.hasNonNullKey(KEY_API_URL)) {
790
- throw IllegalArgumentException(MSG_API_URL_REQUIRED)
791
- }
792
-
793
- val apiUrl =
794
- config.getString(KEY_API_URL)
795
- ?: throw IllegalArgumentException(MSG_API_URL_MUST_BE_STRING)
928
+ private const val KEY_API_URL = "apiUrl"
929
+ private const val KEY_R_TOKEN = "rToken"
930
+ private const val KEY_APP_INFO = "appInfo"
931
+ private const val KEY_PROVIDER_PRIORITY_LIST = "providerPriorityList"
932
+ private const val KEY_ENABLE_LOGGING = "enableLogging"
933
+
934
+ private const val KEY_ANDROID_ICON = "android_icon"
935
+ private const val KEY_ANDROID_USING_SERVICE = "android_usingService"
936
+ private const val KEY_ANDROID_SERVICE_MESSAGE = "android_serviceMessage"
937
+ private const val KEY_ANDROID_PUSH_RECEIVER_MODULES = "android_pushReceiverModules"
938
+ private const val KEY_ANDROID_PUSH_CHANNEL_NAME = "android_pushChannelName"
939
+ private const val KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION = "android_pushChannelDescription"
940
+
941
+ private const val KEY_APP_ID = "appID"
942
+ private const val KEY_APP_IID = "appIID"
943
+ private const val KEY_APP_VER = "appVer"
944
+
945
+ private const val MSG_API_URL_REQUIRED = "apiUrl is required for AltcraftConfiguration"
946
+ private const val MSG_API_URL_MUST_BE_STRING = "apiUrl must be a non-null string"
947
+
948
+ fun buildConfiguration(config: ReadableMap): AltcraftConfiguration {
949
+ if (!config.hasNonNullKey(KEY_API_URL)) {
950
+ throw IllegalArgumentException(MSG_API_URL_REQUIRED)
951
+ }
796
952
 
797
- val rToken = config.getStringOrNull(KEY_R_TOKEN)
953
+ val apiUrl =
954
+ config.getString(KEY_API_URL)
955
+ ?: throw IllegalArgumentException(MSG_API_URL_MUST_BE_STRING)
798
956
 
799
- val appInfo =
800
- config.getMapOrNull(KEY_APP_INFO)?.let { appInfoMap ->
801
- val appID = appInfoMap.getStringOrNull(KEY_APP_ID) ?: ""
802
- val appIID = appInfoMap.getStringOrNull(KEY_APP_IID) ?: ""
803
- val appVer = appInfoMap.getStringOrNull(KEY_APP_VER) ?: ""
804
- DataClasses.AppInfo(appID = appID, appIID = appIID, appVer = appVer)
805
- }
957
+ val rToken = config.getStringOrNull(KEY_R_TOKEN)
806
958
 
807
- val providerPriorityList = config.getArrayOrNull(KEY_PROVIDER_PRIORITY_LIST)?.toStringList()
959
+ val appInfo =
960
+ config.getMapOrNull(KEY_APP_INFO)?.let { appInfoMap ->
961
+ val appID = appInfoMap.getStringOrNull(KEY_APP_ID) ?: ""
962
+ val appIID = appInfoMap.getStringOrNull(KEY_APP_IID) ?: ""
963
+ val appVer = appInfoMap.getStringOrNull(KEY_APP_VER) ?: ""
964
+ DataClasses.AppInfo(appID = appID, appIID = appIID, appVer = appVer)
965
+ }
808
966
 
809
- val enableLogging = config.getBooleanOrNull(KEY_ENABLE_LOGGING)
967
+ val providerPriorityList = config.getArrayOrNull(KEY_PROVIDER_PRIORITY_LIST)?.toStringList()
810
968
 
811
- val icon = config.getIntOrNull(KEY_ANDROID_ICON)
969
+ val enableLogging = config.getBooleanOrNull(KEY_ENABLE_LOGGING)
812
970
 
813
- val usingService = config.getBooleanOrNull(KEY_ANDROID_USING_SERVICE) ?: false
971
+ val icon = config.getIntOrNull(KEY_ANDROID_ICON)
814
972
 
815
- val serviceMessage = config.getStringOrNull(KEY_ANDROID_SERVICE_MESSAGE)
973
+ val pushReceiverModules =
974
+ config.getArrayOrNull(KEY_ANDROID_PUSH_RECEIVER_MODULES)?.toStringList()
816
975
 
817
- val pushReceiverModules =
818
- config.getArrayOrNull(KEY_ANDROID_PUSH_RECEIVER_MODULES)?.toStringList()
976
+ val pushChannelName = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_NAME)
819
977
 
820
- val pushChannelName = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_NAME)
978
+ val pushChannelDescription = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION)
821
979
 
822
- val pushChannelDescription = config.getStringOrNull(KEY_ANDROID_PUSH_CHANNEL_DESCRIPTION)
823
-
824
- return AltcraftConfiguration.Builder(
825
- apiUrl = apiUrl,
826
- icon = icon,
827
- rToken = rToken,
828
- usingService = usingService,
829
- serviceMessage = serviceMessage,
830
- appInfo = appInfo,
831
- providerPriorityList = providerPriorityList,
832
- pushReceiverModules = pushReceiverModules,
833
- pushChannelName = pushChannelName,
834
- pushChannelDescription = pushChannelDescription,
835
- enableLogging = enableLogging
836
- )
837
- .build()
838
- }
980
+ return AltcraftConfiguration.Builder(
981
+ apiUrl = apiUrl,
982
+ icon = icon,
983
+ rToken = rToken,
984
+ appInfo = appInfo,
985
+ providerPriorityList = providerPriorityList,
986
+ pushReceiverModules = pushReceiverModules,
987
+ pushChannelName = pushChannelName,
988
+ pushChannelDescription = pushChannelDescription,
989
+ enableLogging = enableLogging
990
+ )
991
+ .build()
992
+ }
839
993
  }