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