infobip-mobile-messaging-react-native-plugin 14.8.0 → 14.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@ The document describes library integration steps for your React Native project.
12
12
  ## Requirements
13
13
  - node (v20.16.0 or higher)
14
14
  - ruby (2.7.8 or higher; the Example app uses 3.3.5)
15
- - React Native (v0.79.0)
15
+ - React Native (v0.84.0)
16
16
 
17
17
  For iOS project:
18
18
  - Xcode and Command Line Tools (16.x or newer, tested with 26.0.1)
@@ -12,23 +12,17 @@ import android.content.Context;
12
12
  import android.content.SharedPreferences;
13
13
  import android.preference.PreferenceManager;
14
14
 
15
- import android.util.Log;
16
-
17
- import org.infobip.mobile.messaging.api.support.http.serialization.JsonSerializer;
18
- import org.infobip.mobile.messaging.dal.json.JSONArrayAdapter;
19
- import org.infobip.mobile.messaging.dal.json.JSONObjectAdapter;
20
15
  import org.json.JSONObject;
21
16
 
22
17
  import java.util.ArrayList;
23
- import java.util.Arrays;
24
- import java.util.HashSet;
18
+ import java.util.Iterator;
25
19
  import java.util.List;
26
- import java.util.Set;
27
20
 
28
21
  class CacheManager {
29
- private static final String EVENTS_KEY = Utils.TAG + ".cache.events";
22
+ private static final String LEGACY_EVENTS_KEY = Utils.TAG + ".cache.events";
30
23
  private static final Object cacheLock = new Object();
31
- private static final JsonSerializer serializer = new JsonSerializer(false, new JSONObjectAdapter(), new JSONArrayAdapter());
24
+ private static final List<Event> cachedEvents = new ArrayList<>();
25
+ private static final int MAX_CACHE_SIZE = 100;
32
26
 
33
27
  static class Event {
34
28
  String type;
@@ -45,102 +39,57 @@ class CacheManager {
45
39
  public String toString() {
46
40
  return type;
47
41
  }
48
-
49
- }
50
-
51
- static void saveEvent(Context context, String event, JSONObject object, String actionId, String actionInputText) {
52
- if (context == null) {
53
- RNMMLogger.e(Utils.TAG, "context is null, can't cache event " + event);
54
- return;
55
- }
56
- String serialized = serializer.serialize(new Event(event, object, actionId, actionInputText));
57
- saveStringsToSet(context, EVENTS_KEY, serialized);
58
42
  }
59
43
 
60
- static void saveEvent(Context context, String event, int unreadMessagesCounter) {
61
- if (context == null) {
62
- RNMMLogger.e(Utils.TAG, "context is null, can't cache event " + event);
63
- return;
64
- }
65
- //int `unreadMessagesCounter` isn't a JSONObject, so it'll go as a second argument
66
- String serialized = serializer.serialize(new Event(event, null, unreadMessagesCounter));
67
- saveStringsToSet(context, EVENTS_KEY, serialized);
68
- }
69
-
70
- static Event[] loadEvents(Context context, String eventType) {
71
- if (context == null) {
72
- RNMMLogger.e(Utils.TAG, "context is null, can't load cached events " + eventType);
73
- return new Event[0];
74
- }
75
- Set<String> serialized = getStringSet(context, EVENTS_KEY);
76
- if (serialized == null || serialized.isEmpty()) {
77
- return new Event[0];
78
- }
79
-
80
- List<Event> matched = new ArrayList<>();
81
- Set<String> unmatchedSerialized = new HashSet<>();
82
- for (String s : serialized) {
83
- Event e = serializer.deserialize(s, Event.class);
84
- if (eventType.equals(e.type)) {
85
- matched.add(e);
86
- } else {
87
- unmatchedSerialized.add(s);
44
+ static void saveEvent(String event, JSONObject object, String actionId, String actionInputText) {
45
+ synchronized (cacheLock) {
46
+ if (cachedEvents.size() >= MAX_CACHE_SIZE) {
47
+ Event removed = cachedEvents.remove(0);
48
+ RNMMLogger.w(Utils.TAG, "Cache full, dropping oldest event: " + removed.type);
88
49
  }
50
+ cachedEvents.add(new Event(event, object, actionId, actionInputText));
89
51
  }
90
-
91
- updateStringsSet(context, EVENTS_KEY, unmatchedSerialized);
92
-
93
- return matched.toArray(new Event[matched.size()]);
94
52
  }
95
53
 
96
- private static Set<String> getStringSet(Context context, String key) {
97
- SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
54
+ static void saveEvent(String event, int unreadMessagesCounter) {
98
55
  synchronized (cacheLock) {
99
- return new HashSet<>(sharedPreferences.getStringSet(key, new HashSet<String>()));
56
+ if (cachedEvents.size() >= MAX_CACHE_SIZE) {
57
+ Event removed = cachedEvents.remove(0);
58
+ RNMMLogger.w(Utils.TAG, "Cache full, dropping oldest event: " + removed.type);
59
+ }
60
+ cachedEvents.add(new Event(event, null, unreadMessagesCounter));
100
61
  }
101
62
  }
102
63
 
103
- private static Set<String> getAndRemoveStringSet(Context context, String key) {
104
- SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
105
- Set<String> set;
64
+ static Event[] loadEvents(String eventType) {
106
65
  synchronized (cacheLock) {
107
- set = sharedPreferences.getStringSet(key, new HashSet<String>());
108
- if (set.isEmpty()) {
109
- return new HashSet<String>();
66
+ List<Event> matched = new ArrayList<>();
67
+ Iterator<Event> iterator = cachedEvents.iterator();
68
+ while (iterator.hasNext()) {
69
+ Event e = iterator.next();
70
+ if (eventType.equals(e.type)) {
71
+ matched.add(e);
72
+ iterator.remove();
73
+ }
110
74
  }
111
- sharedPreferences
112
- .edit()
113
- .remove(key)
114
- .apply();
75
+ return matched.toArray(new Event[0]);
115
76
  }
116
- return set;
117
77
  }
118
78
 
119
- @SuppressWarnings("UnusedReturnValue")
120
- private static Set<String> saveStringsToSet(Context context, String key, String... strings) {
121
- return saveStringSet(context, key, new HashSet<String>(Arrays.asList(strings)));
122
- }
123
-
124
- private static Set<String> saveStringSet(Context context, String key, Set<String> newSet) {
125
- SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
79
+ static void clearCache() {
126
80
  synchronized (cacheLock) {
127
- Set<String> set = sharedPreferences.getStringSet(key, new HashSet<String>());
128
- newSet.addAll(set);
129
- sharedPreferences
130
- .edit()
131
- .putStringSet(key, newSet)
132
- .apply();
133
- return set;
81
+ cachedEvents.clear();
134
82
  }
135
83
  }
136
84
 
137
- private static void updateStringsSet(Context context, String key, Set<String> newSet) {
85
+ static void cleanupLegacyCache(Context context) {
86
+ if (context == null) {
87
+ return;
88
+ }
138
89
  SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
139
- synchronized (cacheLock) {
140
- sharedPreferences
141
- .edit()
142
- .putStringSet(key, newSet)
143
- .apply();
90
+ if (sharedPreferences.contains(LEGACY_EVENTS_KEY)) {
91
+ sharedPreferences.edit().remove(LEGACY_EVENTS_KEY).apply();
92
+ RNMMLogger.d(Utils.TAG, "Cleaned up legacy SharedPreferences event cache");
144
93
  }
145
94
  }
146
95
  }
@@ -392,18 +392,22 @@ class RNMMChatEventReceiver : ReactNativeBroadcastReceiver() {
392
392
  emitOrCache(context, RNMMChatService.EVENT_INAPPCHAT_UNREAD_MESSAGES_COUNT_UPDATED, unreadChatMessagesCounter)
393
393
  }
394
394
 
395
+ // Early-exit when plugin is not initialized avoids calling getReactContext() which throws
396
+ // UnsupportedOperationException on new architecture when app is killed. When reactContext is
397
+ // null (e.g. during lifecycle transitions), events are cached regardless of jsHasListeners
398
+ // since sending requires a valid ReactContext. This preserves the original behavior.
395
399
  private fun emitOrCache(context: Context?, eventType: String, unreadMessagesCounter: Int) {
400
+ if (!pluginInitialized) {
401
+ CacheManager.saveEvent(eventType, unreadMessagesCounter)
402
+ return
403
+ }
396
404
  val reactContext: ReactContext? = getReactContext(context)
397
- if (!pluginInitialized || reactContext == null) {
398
- CacheManager.saveEvent(context, eventType, unreadMessagesCounter)
399
- } else if (jsHasListeners && reactContext != null) {
405
+ if (reactContext == null) {
406
+ CacheManager.saveEvent(eventType, unreadMessagesCounter)
407
+ } else if (jsHasListeners) {
400
408
  ReactNativeEvent.send(eventType, reactContext, unreadMessagesCounter)
401
- } else if (reactContext != null) {
402
- CacheManager.saveEvent(reactContext, eventType, unreadMessagesCounter)
403
- } else if (context != null) {
404
- CacheManager.saveEvent(context, eventType, unreadMessagesCounter)
405
409
  } else {
406
- RNMMLogger.e(TAG, "Both reactContext and androidContext are null, can't emit or cache event " + eventType)
410
+ CacheManager.saveEvent(eventType, unreadMessagesCounter)
407
411
  }
408
412
  }
409
413
  }
@@ -27,11 +27,16 @@ abstract class ReactNativeBroadcastReceiver : BroadcastReceiver() {
27
27
  get() = ReactNativeMobileMessagingService.jsHasListeners
28
28
 
29
29
  protected fun getReactContext(context: Context?): ReactContext? {
30
- return ReactNativeMobileMessagingService.lastReactContext
31
- ?: (context?.applicationContext as? ReactApplication)
32
- ?.reactNativeHost
33
- ?.reactInstanceManager
34
- ?.currentReactContext
30
+ return try {
31
+ ReactNativeMobileMessagingService.lastReactContext
32
+ ?: (context?.applicationContext as? ReactApplication)
33
+ ?.reactNativeHost
34
+ ?.reactInstanceManager
35
+ ?.currentReactContext
36
+ } catch (e: Exception) {
37
+ RNMMLogger.w(Utils.TAG, "Failed to get ReactContext: ${e.message}")
38
+ null
39
+ }
35
40
  }
36
41
 
37
42
  }
@@ -951,7 +951,7 @@ class ReactNativeMobileMessagingService(
951
951
  fun addListener(eventName: String) {
952
952
  RNMMLogger.d(Utils.TAG, "addListener: $eventName")
953
953
  jsHasListeners = true
954
- val events = CacheManager.loadEvents(reactContext, eventName)
954
+ val events = CacheManager.loadEvents(eventName)
955
955
  for (event in events) {
956
956
  if (eventName == event.type) {
957
957
  ReactNativeEvent.send(event.type, reactContext, event.jsonObject, *event.objects)
@@ -1088,18 +1088,22 @@ class MessageEventReceiver : ReactNativeBroadcastReceiver() {
1088
1088
  emitOrCache(event, context, message, actionId, actionInputText)
1089
1089
  }
1090
1090
 
1091
+ // Early-exit when plugin is not initialized avoids calling getReactContext() which throws
1092
+ // UnsupportedOperationException on new architecture when app is killed. When reactContext is
1093
+ // null (e.g. during lifecycle transitions), events are cached regardless of jsHasListeners
1094
+ // since sending requires a valid ReactContext. This preserves the original behavior.
1091
1095
  private fun emitOrCache(eventType: String, context: Context?, message: JSONObject?, actionId: String?, actionInputText: String?) {
1096
+ if (!pluginInitialized) {
1097
+ CacheManager.saveEvent(eventType, message, actionId, actionInputText)
1098
+ return
1099
+ }
1092
1100
  val reactContext: ReactContext? = getReactContext(context)
1093
- if (!pluginInitialized || reactContext == null) {
1094
- CacheManager.saveEvent(context, eventType, message, actionId, actionInputText)
1095
- } else if (jsHasListeners && reactContext != null) {
1101
+ if (reactContext == null) {
1102
+ CacheManager.saveEvent(eventType, message, actionId, actionInputText)
1103
+ } else if (jsHasListeners) {
1096
1104
  ReactNativeEvent.send(eventType, reactContext, message, actionId, actionInputText)
1097
- } else if (reactContext != null) {
1098
- CacheManager.saveEvent(reactContext, eventType, message, actionId, actionInputText)
1099
- } else if (context != null) {
1100
- CacheManager.saveEvent(context, eventType, message, actionId, actionInputText)
1101
1105
  } else {
1102
- RNMMLogger.e(Utils.TAG, "Both reactContext and androidContext are null, can't emit or cache event " + eventType)
1106
+ CacheManager.saveEvent(eventType, message, actionId, actionInputText)
1103
1107
  }
1104
1108
  }
1105
1109
 
@@ -27,6 +27,7 @@ class MobileMessagingModule(reactContext: ReactApplicationContext) : NativeMobil
27
27
 
28
28
  init {
29
29
  reactApplicationContext.addLifecycleEventListener(this)
30
+ CacheManager.cleanupLegacyCache(reactApplicationContext)
30
31
  ReactNativeMobileMessagingService.pluginInitialized = true
31
32
  service.registerBroadcastReceiver()
32
33
  }
@@ -199,6 +200,7 @@ class MobileMessagingModule(reactContext: ReactApplicationContext) : NativeMobil
199
200
  override fun onHostDestroy() {
200
201
  ReactNativeMobileMessagingService.pluginInitialized = false
201
202
  service.unregisterBroadcastReceiver()
203
+ CacheManager.clearCache()
202
204
  reactApplicationContext.removeLifecycleEventListener(this)
203
205
  ReactNativeMobileMessagingService.unregisterService(reactApplicationContext)
204
206
  }
@@ -28,6 +28,7 @@ class MobileMessagingModule(reactContext: ReactApplicationContext) : ReactContex
28
28
 
29
29
  init {
30
30
  reactApplicationContext.addLifecycleEventListener(this)
31
+ CacheManager.cleanupLegacyCache(reactApplicationContext)
31
32
  ReactNativeMobileMessagingService.pluginInitialized = true
32
33
  service.registerBroadcastReceiver()
33
34
  }
@@ -230,6 +231,7 @@ class MobileMessagingModule(reactContext: ReactApplicationContext) : ReactContex
230
231
 
231
232
  override fun onHostDestroy() {
232
233
  service.unregisterBroadcastReceiver()
234
+ CacheManager.clearCache()
233
235
  reactApplicationContext.removeLifecycleEventListener(this)
234
236
  ReactNativeMobileMessagingService.pluginInitialized = false
235
237
  ReactNativeMobileMessagingService.unregisterService(reactApplicationContext)
@@ -20,7 +20,9 @@ Pod::Spec.new do |s|
20
20
  s.requires_arc = true
21
21
 
22
22
  s.dependency "React-Core"
23
- s.dependency "React-Core-prebuilt"
23
+ if ENV['RCT_USE_PREBUILT_RNCORE'] == '1'
24
+ s.dependency "React-Core-prebuilt"
25
+ end
24
26
 
25
27
  s.dependency "MobileMessaging/Core", mmVersion
26
28
  s.dependency "MobileMessaging/InAppChat", mmVersion
@@ -13,9 +13,15 @@ import MobileMessaging
13
13
  class RNMMChat: NSObject {
14
14
  private var willUseJWT = false
15
15
  private var willUseChatExceptionHandler = false
16
- private var jwtRequestQueue: [((String?) -> Void)] = []
16
+ private var jwtRequestQueue: [JWTRequest] = []
17
17
  private let jwtQueueLock = NSLock()
18
18
 
19
+ private final class JWTRequest {
20
+ var completed = false
21
+ let onResult: (String?) -> Void
22
+ init(_ onResult: @escaping (String?) -> Void) { self.onResult = onResult }
23
+ }
24
+
19
25
  @objc(showChat:)
20
26
  func showChat(presentingOptions: NSDictionary) {
21
27
  MobileMessaging.inAppChat?.delegate = self
@@ -161,22 +167,26 @@ class RNMMChat: NSObject {
161
167
  @objc(setChatJwtProvider)
162
168
  func setChatJwtProvider() {
163
169
  willUseJWT = true
170
+ // We cannot rely on 'showChat' for setting the delegate as we have several presentation modes - any async provider/handler request sets the delegate to ensure proper completions are triggered
171
+ MobileMessaging.inAppChat?.delegate = self
164
172
  }
165
173
 
166
174
  @objc(setChatExceptionHandler:)
167
175
  func setChatExceptionHandler(isHandlerPresent: NSNumber) {
168
176
  // NSNumber due to how RN bridge wraps JavaScript booleans
169
177
  willUseChatExceptionHandler = isHandlerPresent.boolValue
178
+ MobileMessaging.inAppChat?.delegate = self
170
179
  }
171
180
 
172
181
  @objc(setChatJwt:)
173
182
  func setChatJwt(jwt: String?) {
174
183
  jwtQueueLock.lock()
175
- if !jwtRequestQueue.isEmpty {
176
- let completion = jwtRequestQueue.removeFirst()
177
- completion(jwt)
178
- }
179
- jwtQueueLock.unlock()
184
+ defer { jwtQueueLock.unlock() }
185
+ guard let request = jwtRequestQueue.first(where: { !$0.completed }) else { return }
186
+ request.completed = true
187
+ jwtRequestQueue.removeAll(where: { $0 === request })
188
+ // Settled inside the lock so a concurrent getJWT cleanup observes completed == true and jwtResult is set before getJWT returns.
189
+ request.onResult(jwt)
180
190
  }
181
191
 
182
192
  @objc(restartConnection)
@@ -201,15 +211,27 @@ extension RNMMChat: MMInAppChatDelegate {
201
211
  guard willUseJWT else { return nil }
202
212
  var jwtResult: String?
203
213
  let semaphore = DispatchSemaphore(value: 0)
204
-
205
- jwtQueueLock.lock()
206
- jwtRequestQueue.append { jwt in
214
+ let request = JWTRequest { jwt in
207
215
  jwtResult = jwt
208
216
  semaphore.signal()
209
217
  }
218
+
219
+ jwtQueueLock.lock()
220
+ jwtRequestQueue.append(request)
210
221
  jwtQueueLock.unlock()
211
- ReactNativeMobileMessaging.shared?.sendEvent(withName: EventName.inAppChat_jwtRequested, body: nil)
222
+
223
+ ReactNativeMobileMessaging.shared?.sendDirectEvent(withName: EventName.inAppChat_jwtRequested, body: nil)
212
224
  _ = semaphore.wait(timeout: .now() + 45)
225
+
226
+ // Remove this request by identity (not position) so a setChatJwt that fires between the wait timeout and the lock cannot cause us to evict a different in-flight request.
227
+ jwtQueueLock.lock()
228
+ if !request.completed {
229
+ request.completed = true
230
+ if let idx = jwtRequestQueue.firstIndex(where: { $0 === request }) {
231
+ jwtRequestQueue.remove(at: idx)
232
+ }
233
+ }
234
+ jwtQueueLock.unlock()
213
235
  return jwtResult
214
236
  }
215
237
 
@@ -37,7 +37,9 @@ class RNMMChatViewManager: RCTViewManager {
37
37
  }
38
38
 
39
39
  override func didMoveToWindow() {
40
- embedViewController()
40
+ if window != nil { // this could be triggered in an improper manner from RN side, so we confirm UI is in a proper state
41
+ embedViewController()
42
+ }
41
43
  super.didMoveToWindow()
42
44
  }
43
45
 
@@ -64,6 +64,20 @@ class ReactNativeMobileMessaging: RCTEventEmitter {
64
64
  }
65
65
  super.sendEvent(withName: name, body: body)
66
66
  }
67
+
68
+ func sendDirectEvent(withName name: String!, body: Any!) {
69
+ guard let _eventsManager = eventsManager, _eventsManager.hasEventListeners == true else {
70
+ // JS listener persists on the mobileMessaging singleton but RCTEventEmitter's _listenerCount may be zero during a React Navigation transition (reproducible with custom chat navigations and JWT async callback/authentication flow). Bypass that guard by invoking RCTDeviceEventEmitter directly via the public callableJSModules API (bridgeless-safe; the same path super.sendEvent uses internally).
71
+ MMLogDebug("[RNMobileMessaging] sendDirectEvent: invoking RCTDeviceEventEmitter directly")
72
+ self.callableJSModules?.invokeModule(
73
+ "RCTDeviceEventEmitter",
74
+ method: "emit",
75
+ withArgs: [name!, body ?? NSNull()]
76
+ )
77
+ return
78
+ }
79
+ super.sendEvent(withName: name, body: body)
80
+ }
67
81
 
68
82
  @objc
69
83
  override static func requiresMainQueueSetup() -> Bool {
@@ -84,60 +98,109 @@ class ReactNativeMobileMessaging: RCTEventEmitter {
84
98
 
85
99
  @objc(init:onSuccess:onError:)
86
100
  func start(config: NSDictionary, onSuccess: @escaping RCTResponseSenderBlock, onError: @escaping RCTResponseSenderBlock) {
87
- guard let config = config as? [String : AnyObject], let configuration = RNMobileMessagingConfiguration(rawConfig: config) else {
101
+ guard var userConfigDict = config as? [String : AnyObject],
102
+ let applicationCode = userConfigDict.removeValue(forKey: RNMobileMessagingConfiguration.Keys.applicationCode) as? String,
103
+ let configuration = RNMobileMessagingConfiguration(rawConfig: userConfigDict)
104
+ else {
88
105
  onError([NSError(type: .InvalidArguments).reactNativeObject])
89
106
  return
90
107
  }
91
108
 
92
109
  let successCallback: RCTResponseSenderBlock = { [weak self] response in
93
- RNMobileMessagingConfiguration.saveConfigToDefaults(rawConfig: config)
110
+ RNMobileMessagingConfiguration.saveConfigToDefaults(rawConfig: userConfigDict)
94
111
  self?.isStarted = true
95
112
  onSuccess(response)
96
113
  }
97
-
114
+
98
115
  let cachedConfigDict = RNMobileMessagingConfiguration.getRawConfigFromDefaults()
99
- if let cachedConfigDict = cachedConfigDict, (config as NSDictionary) != (cachedConfigDict as NSDictionary)
100
- {
116
+ let keychainApplicationCode = MobileMessaging.getKeychainApplicationCode()
117
+ let shouldRestart = needsRestart(userConfigDict: userConfigDict, applicationCode: applicationCode)
118
+ let shouldStart = cachedConfigDict == nil || keychainApplicationCode == nil
119
+
120
+ if shouldRestart {
101
121
  stop {
102
- self.start(configuration: configuration, onSuccess: successCallback)
122
+ self.startWithApplicationCode(
123
+ configuration: configuration,
124
+ applicationCode: applicationCode,
125
+ onSuccess: successCallback,
126
+ onError: onError
127
+ )
103
128
  }
104
- } else if cachedConfigDict == nil {
105
- start(configuration: configuration, onSuccess: successCallback)
129
+ } else if shouldStart {
130
+ startWithApplicationCode(
131
+ configuration: configuration,
132
+ applicationCode: applicationCode,
133
+ onSuccess: successCallback,
134
+ onError: onError
135
+ )
106
136
  } else {
107
137
  successCallback(nil)
108
138
  }
109
139
  }
110
140
 
111
141
  private func performEarlyStartIfPossible() {
112
- if let cachedConfigDict = RNMobileMessagingConfiguration.getRawConfigFromDefaults(),
113
- let configuration = RNMobileMessagingConfiguration(rawConfig: cachedConfigDict),
114
- !self.isStarted,
115
- !isEarlyStartPerformed
142
+ let cachedConfigDict = RNMobileMessagingConfiguration.getRawConfigFromDefaults()
143
+ let configuration = cachedConfigDict.flatMap(RNMobileMessagingConfiguration.init)
144
+ let applicationCode = MobileMessaging.getKeychainApplicationCode()
145
+
146
+ guard let configuration = configuration,
147
+ let applicationCode = applicationCode,
148
+ !self.isStarted,
149
+ !isEarlyStartPerformed else
116
150
  {
117
- MMLogDebug("[RNMobileMessaging] Performing early start")
118
- isEarlyStartPerformed = true
119
- start(configuration: configuration) { response in }
151
+ return
120
152
  }
153
+
154
+ isEarlyStartPerformed = true
155
+ startWithApplicationCode(configuration: configuration, applicationCode: applicationCode) { response in }
156
+ }
157
+
158
+ private func startWithApplicationCode(
159
+ configuration: RNMobileMessagingConfiguration,
160
+ applicationCode: String,
161
+ onSuccess: @escaping RCTResponseSenderBlock,
162
+ onError: RCTResponseSenderBlock? = nil
163
+ ) {
164
+ guard let mobileMessaging = createMobileMessagingInstance(
165
+ configuration: configuration,
166
+ applicationCode: applicationCode
167
+ ) else {
168
+ MMLogError("[RNMobileMessaging] Failed to initialize MobileMessaging instance, SDK can't start.")
169
+ onError?([NSError(type: .InitializationFailed).reactNativeObject])
170
+ return
171
+ }
172
+
173
+ applyConfigurationAndStart(
174
+ mobileMessaging,
175
+ configuration: configuration,
176
+ onSuccess: onSuccess
177
+ )
121
178
  }
122
-
123
- private func start(configuration: RNMobileMessagingConfiguration, onSuccess: @escaping RCTResponseSenderBlock) {
179
+
180
+ private func createMobileMessagingInstance(configuration: RNMobileMessagingConfiguration, applicationCode: String) -> MobileMessaging? {
181
+ let backendBaseURL = configuration.backendBaseURL ?? MMConsts.APIValues.prodDynamicBaseURLString
182
+ return MobileMessaging.withApplicationCode(
183
+ applicationCode,
184
+ notificationType: configuration.notificationType,
185
+ backendBaseURL: backendBaseURL
186
+ )
187
+ }
188
+
189
+ private func applyConfigurationAndStart(_ mobileMessaging: MobileMessaging, configuration: RNMobileMessagingConfiguration, onSuccess: @escaping RCTResponseSenderBlock) {
124
190
  self.eventsManager?.startObserving()
125
191
  MobileMessaging.privacySettings.systemInfoSendingDisabled = configuration.privacySettings[RNMobileMessagingConfiguration.Keys.systemInfoSendingDisabled].unwrap(orDefault: false)
126
192
  MobileMessaging.privacySettings.carrierInfoSendingDisabled = configuration.privacySettings[RNMobileMessagingConfiguration.Keys.carrierInfoSendingDisabled].unwrap(orDefault: false)
127
193
  MobileMessaging.privacySettings.userDataPersistingDisabled = configuration.privacySettings[RNMobileMessagingConfiguration.Keys.userDataPersistingDisabled].unwrap(orDefault: false)
128
194
 
129
- var mobileMessaging = MobileMessaging.withApplicationCode(
130
- configuration.appCode,
131
- notificationType: configuration.notificationType,
132
- backendBaseURL: configuration.backendBaseURL ?? MMConsts.APIValues.prodDynamicBaseURLString)
195
+ var mobileMessaging = mobileMessaging
133
196
 
134
197
  if let storageAdapter = messageStorageAdapter, configuration.messageStorageEnabled {
135
- mobileMessaging = mobileMessaging?.withMessageStorage(storageAdapter)
198
+ mobileMessaging = mobileMessaging.withMessageStorage(storageAdapter)
136
199
  } else if configuration.defaultMessageStorage {
137
- mobileMessaging = mobileMessaging?.withDefaultMessageStorage()
200
+ mobileMessaging = mobileMessaging.withDefaultMessageStorage()
138
201
  }
139
202
  if let categories = configuration.categories {
140
- mobileMessaging = mobileMessaging?.withInteractiveNotificationCategories(Set(categories))
203
+ mobileMessaging = mobileMessaging.withInteractiveNotificationCategories(Set(categories))
141
204
  }
142
205
  MobileMessaging.userAgent.pluginVersion = "reactNative \(configuration.reactNativePluginVersion)"
143
206
  if configuration.logging {
@@ -145,22 +208,22 @@ class ReactNativeMobileMessaging: RCTEventEmitter {
145
208
  }
146
209
 
147
210
  if configuration.inAppChatEnabled {
148
- mobileMessaging = mobileMessaging?.withInAppChat()
211
+ mobileMessaging = mobileMessaging.withInAppChat()
149
212
  }
150
213
 
151
214
  if configuration.fullFeaturedInAppsEnabled {
152
- mobileMessaging = mobileMessaging?.withFullFeaturedInApps()
215
+ mobileMessaging = mobileMessaging.withFullFeaturedInApps()
153
216
  }
154
217
 
155
218
  if let webViewSettings = configuration.webViewSettings {
156
- mobileMessaging?.webViewSettings.configureWith(rawConfig: webViewSettings)
219
+ mobileMessaging.webViewSettings.configureWith(rawConfig: webViewSettings)
157
220
  }
158
221
 
159
222
  if let jwt = configuration.userDataJwt, !jwt.isEmpty {
160
- mobileMessaging = mobileMessaging?.withJwtSupplier(VariableJwtSupplier(jwt: jwt))
223
+ mobileMessaging = mobileMessaging.withJwtSupplier(VariableJwtSupplier(jwt: jwt))
161
224
  }
162
225
 
163
- mobileMessaging?.start({
226
+ mobileMessaging.start({
164
227
  onSuccess(nil)
165
228
  })
166
229
  }
@@ -169,6 +232,13 @@ class ReactNativeMobileMessaging: RCTEventEmitter {
169
232
  self.eventsManager?.stop(stopObservations: stopObservations)
170
233
  MobileMessaging.stop(false, completion: completion)
171
234
  }
235
+
236
+ private func needsRestart(userConfigDict: [String: AnyObject], applicationCode: String) -> Bool {
237
+ let configurationChanged = RNMobileMessagingConfiguration.didConfigurationChange(userConfigDict: userConfigDict)
238
+ let applicationCodeChanged = MobileMessaging.didApplicationCodeChange(applicationCode: applicationCode)
239
+
240
+ return configurationChanged || applicationCodeChanged
241
+ }
172
242
 
173
243
  /*User Profile Management*/
174
244
 
@@ -11,6 +11,7 @@ import MobileMessaging
11
11
 
12
12
  class RNMobileMessagingConfiguration {
13
13
  static let userDefaultsConfigKey = "com.mobile-messaging.reactNativePluginConfiguration"
14
+ static let ignoreKeysWhenComparing: [String] = [Keys.reactNativePluginVersion]
14
15
 
15
16
  struct Keys {
16
17
  static let privacySettings = "privacySettings"
@@ -34,7 +35,6 @@ class RNMobileMessagingConfiguration {
34
35
  static let backendBaseURL = "backendBaseURL"
35
36
  }
36
37
 
37
- let appCode: String
38
38
  let webRTCUI: [String: AnyObject]?
39
39
  let messageStorageEnabled: Bool
40
40
  let defaultMessageStorage: Bool
@@ -50,13 +50,11 @@ class RNMobileMessagingConfiguration {
50
50
  let backendBaseURL: String?
51
51
 
52
52
  init?(rawConfig: [String: AnyObject]) {
53
- guard let appCode = rawConfig[RNMobileMessagingConfiguration.Keys.applicationCode] as? String,
54
- let ios = rawConfig["ios"] as? [String: AnyObject] else
53
+ guard let ios = rawConfig["ios"] as? [String: AnyObject] else
55
54
  {
56
55
  return nil
57
56
  }
58
57
 
59
- self.appCode = appCode
60
58
  self.webRTCUI = rawConfig[RNMobileMessagingConfiguration.Keys.webRTCUI] as? [String: AnyObject]
61
59
  self.logging = rawConfig[RNMobileMessagingConfiguration.Keys.logging].unwrap(orDefault: false)
62
60
  self.defaultMessageStorage = rawConfig[RNMobileMessagingConfiguration.Keys.defaultMessageStorage].unwrap(orDefault: false)
@@ -70,7 +68,6 @@ class RNMobileMessagingConfiguration {
70
68
  ps[RNMobileMessagingConfiguration.Keys.userDataPersistingDisabled] = rawPrivacySettings[RNMobileMessagingConfiguration.Keys.userDataPersistingDisabled].unwrap(orDefault: false)
71
69
  ps[RNMobileMessagingConfiguration.Keys.carrierInfoSendingDisabled] = rawPrivacySettings[RNMobileMessagingConfiguration.Keys.carrierInfoSendingDisabled].unwrap(orDefault: false)
72
70
  ps[RNMobileMessagingConfiguration.Keys.systemInfoSendingDisabled] = rawPrivacySettings[RNMobileMessagingConfiguration.Keys.systemInfoSendingDisabled].unwrap(orDefault: false)
73
- ps[RNMobileMessagingConfiguration.Keys.applicationCodePersistingDisabled] = rawPrivacySettings[RNMobileMessagingConfiguration.Keys.applicationCodePersistingDisabled].unwrap(orDefault: false)
74
71
 
75
72
  privacySettings = ps
76
73
  } else {
@@ -108,17 +105,7 @@ class RNMobileMessagingConfiguration {
108
105
  }
109
106
 
110
107
  static func saveConfigToDefaults(rawConfig: [String: AnyObject]) {
111
- var serializableConfig = rawConfig.compactMapValues { value -> AnyObject? in
112
- if value is NSString || value is NSNumber || value is NSArray || value is NSDictionary || value is NSDate || value is NSData {
113
- return value
114
- }
115
- return nil
116
- }
117
- if serializableConfig[RNMobileMessagingConfiguration.Keys.messageStorage] != nil {
118
- // Temporal fix so the archiving doesn't fail (messageStorage doesn't contain codable objects).
119
- // Below we overwrite it with a dummy value so messageStorageEnabled keeps working.
120
- serializableConfig[RNMobileMessagingConfiguration.Keys.messageStorage] = NSString(string: "message_storage")
121
- }
108
+ let serializableConfig = serializedConfig(from: rawConfig)
122
109
 
123
110
  do {
124
111
  let data: Data = try NSKeyedArchiver.archivedData(withRootObject: serializableConfig, requiringSecureCoding: false)
@@ -135,10 +122,70 @@ class RNMobileMessagingConfiguration {
135
122
  }
136
123
 
137
124
  do {
138
- return try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [String: AnyObject]
125
+ guard let rawConfig = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [String: AnyObject] else {
126
+ return nil
127
+ }
128
+
129
+ let normalizedConfig = serializedConfig(from: rawConfig)
130
+ if (normalizedConfig as NSDictionary) != (rawConfig as NSDictionary) {
131
+ saveConfigToDefaults(rawConfig: normalizedConfig)
132
+ }
133
+
134
+ return normalizedConfig
139
135
  } catch {
140
136
  MMLogError("[MobileMessaging] Failed to unarchive config from UserDefaults: \(error)")
141
137
  return nil
142
138
  }
143
139
  }
140
+
141
+ static func didConfigurationChange(userConfigDict: [String: AnyObject]) -> Bool {
142
+ var serializedUserConfig = serializedConfig(from: userConfigDict)
143
+ guard let cachedConfigDict = getRawConfigFromDefaults() else {
144
+ return false
145
+ }
146
+ var serializedCachedConfig = serializedConfig(from: cachedConfigDict)
147
+
148
+ removeIgnoredKeys(from: &serializedUserConfig)
149
+ removeIgnoredKeys(from: &serializedCachedConfig)
150
+
151
+ return (serializedUserConfig as NSDictionary) != (serializedCachedConfig as NSDictionary)
152
+ }
153
+
154
+ private static func serializedConfig(from rawConfig: [String: AnyObject]) -> [String: AnyObject] {
155
+ var rawConfig = rawConfig
156
+ rawConfig.removeValue(forKey: RNMobileMessagingConfiguration.Keys.applicationCode)
157
+ sanitizePrivacySettings(in: &rawConfig)
158
+
159
+ var serializableConfig = rawConfig.compactMapValues { value -> AnyObject? in
160
+ if value is NSString || value is NSNumber || value is NSArray || value is NSDictionary || value is NSDate || value is NSData {
161
+ return value
162
+ }
163
+ return nil
164
+ }
165
+
166
+ if rawConfig[RNMobileMessagingConfiguration.Keys.messageStorage] != nil {
167
+ // Preserve the fact that custom message storage was configured without persisting the JS callbacks.
168
+ serializableConfig[RNMobileMessagingConfiguration.Keys.messageStorage] = NSString(string: "message_storage")
169
+ }
170
+
171
+ return serializableConfig
172
+ }
173
+
174
+ private static func removeIgnoredKeys(from config: inout [String: AnyObject]) {
175
+ ignoreKeysWhenComparing.forEach { config.removeValue(forKey: $0) }
176
+ }
177
+
178
+ private static func sanitizePrivacySettings(in rawConfig: inout [String: AnyObject]) {
179
+ guard var rawPrivacySettings = rawConfig[RNMobileMessagingConfiguration.Keys.privacySettings] as? [String: Any] else {
180
+ return
181
+ }
182
+
183
+ rawPrivacySettings.removeValue(forKey: RNMobileMessagingConfiguration.Keys.applicationCodePersistingDisabled)
184
+
185
+ if rawPrivacySettings.isEmpty {
186
+ rawConfig.removeValue(forKey: RNMobileMessagingConfiguration.Keys.privacySettings)
187
+ } else {
188
+ rawConfig[RNMobileMessagingConfiguration.Keys.privacySettings] = rawPrivacySettings as NSDictionary
189
+ }
190
+ }
144
191
  }
@@ -16,6 +16,7 @@ public enum RNMobileMessagingErrorType: Error {
16
16
  case DefaultStorageNotInitialized
17
17
  case NotSupported
18
18
  case NoData
19
+ case InitializationFailed
19
20
 
20
21
  fileprivate var errorCode: Int {
21
22
  switch self {
@@ -29,6 +30,8 @@ public enum RNMobileMessagingErrorType: Error {
29
30
  return 3
30
31
  case .NoData:
31
32
  return 4
33
+ case .InitializationFailed:
34
+ return 5
32
35
  }
33
36
 
34
37
  }
@@ -47,6 +50,8 @@ public enum RNMobileMessagingErrorType: Error {
47
50
  errorDescription = NSLocalizedString("Functionality is not supported.", comment: "")
48
51
  case .NoData:
49
52
  errorDescription = NSLocalizedString("No data retrieved.", comment: "")
53
+ case .InitializationFailed:
54
+ errorDescription = NSLocalizedString("Could not initialize MobileMessaging SDK.", comment: "")
50
55
  }
51
56
  return errorDescription
52
57
  }
@@ -39,6 +39,12 @@ extension MMInbox {
39
39
  var result = [String: Any]()
40
40
  result["countTotal"] = countTotal
41
41
  result["countUnread"] = countUnread
42
+ if let countTotalFiltered = countTotalFiltered {
43
+ result["countTotalFiltered"] = countTotalFiltered
44
+ }
45
+ if let countUnreadFiltered = countUnreadFiltered {
46
+ result["countUnreadFiltered"] = countUnreadFiltered
47
+ }
42
48
  result["messages"] = messages.map({ return $0.dictionaryRepresentation })
43
49
  return result
44
50
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "infobip-mobile-messaging-react-native-plugin",
3
3
  "title": "Infobip Mobile Messaging React Native Plugin",
4
- "version": "14.8.0",
4
+ "version": "14.9.0",
5
5
  "description": "Infobip Mobile Messaging React Native Plugin",
6
6
  "main": "./src/index.js",
7
7
  "scripts": {
package/src/index.d.ts CHANGED
@@ -64,7 +64,6 @@ declare namespace MobileMessagingReactNative {
64
64
  notificationSound?: string;
65
65
  };
66
66
  privacySettings?: {
67
- applicationCodePersistingDisabled?: boolean;
68
67
  userDataPersistingDisabled?: boolean;
69
68
  carrierInfoSendingDisabled?: boolean;
70
69
  systemInfoSendingDisabled?: boolean
@@ -130,13 +129,16 @@ declare namespace MobileMessagingReactNative {
130
129
  export interface MMInbox {
131
130
  countTotal: number;
132
131
  countUnread: number;
133
- messages?: [Message];
132
+ countTotalFiltered?: number;
133
+ countUnreadFiltered?: number;
134
+ messages?: Message[];
134
135
  }
135
136
 
136
137
  export interface MMInboxFilterOptions {
137
138
  fromDateTime?: string;
138
139
  toDateTime?: string;
139
140
  topic?: string;
141
+ topics?: string[];
140
142
  limit?: number;
141
143
  }
142
144
 
@@ -149,6 +151,7 @@ declare namespace MobileMessagingReactNative {
149
151
 
150
152
  export interface Message {
151
153
  messageId: string;
154
+ topic?: string;
152
155
  title?: string;
153
156
  body?: string;
154
157
  sound?: string;
package/src/index.js CHANGED
@@ -166,7 +166,6 @@ class MobileMessaging {
166
166
  * notificationSound: <String>
167
167
  * }
168
168
  * privacySettings: {
169
- * applicationCodePersistingDisabled: <Boolean>,
170
169
  * userDataPersistingDisabled: <Boolean>,
171
170
  * carrierInfoSendingDisabled: <Boolean>,
172
171
  * systemInfoSendingDisabled: <Boolean>
@@ -285,7 +284,14 @@ class MobileMessaging {
285
284
  * @name fetchInboxMessages
286
285
  * @param token access token (JWT in a strictly predefined format) required for current user to have access to the Inbox messages
287
286
  * @param externalUserId External User ID is meant to be an ID of a user in an external (non-Infobip) service
288
- * @param filterOptions filtering options applied to messages list in response. Nullable, will return default number of messages
287
+ * @param filterOptions filtering options applied to messages list in response.
288
+ * {
289
+ * fromDateTime: <String; filter messages received after this datetime in ISO8601 format with timezone, e.g. "2024-03-11T12:00:00+01:00">,
290
+ * toDateTime: <String; filter messages received before this datetime in ISO8601 format with timezone, e.g. "2024-03-20T12:00:00+01:00">,
291
+ * topic: <String; filter messages by a single topic. Mutually exclusive with 'topics'>,
292
+ * topics: <Array<String>; filter messages by multiple topics, e.g. ["topic1", "topic2"]. Mutually exclusive with 'topic'>,
293
+ * limit: <Number; maximum number of messages to return. Default is 20 for standard/single-topic fetches. When using 'topics', no default limit is applied unless explicitly provided, and the limit applies to the total returned messages, not per topic>,
294
+ * }
289
295
  * @param onSuccess will be called on success
290
296
  * @param {Function} onError will be called on error
291
297
  */
@@ -298,7 +304,14 @@ class MobileMessaging {
298
304
  *
299
305
  * @name fetchInboxMessagesWithoutToken
300
306
  * @param externalUserId External User ID is meant to be an ID of a user in an external (non-Infobip) service
301
- * @param filterOptions filtering options applied to messages list in response. Nullable, will return default number of messages
307
+ * @param filterOptions filtering options applied to messages list in response.
308
+ * {
309
+ * fromDateTime: <String; filter messages received after this datetime in ISO8601 format with timezone, e.g. "2024-03-11T12:00:00+01:00">,
310
+ * toDateTime: <String; filter messages received before this datetime in ISO8601 format with timezone, e.g. "2024-03-20T12:00:00+01:00">,
311
+ * topic: <String; filter messages by a single topic. Mutually exclusive with 'topics'>,
312
+ * topics: <Array<String>; filter messages by multiple topics, e.g. ["topic1", "topic2"]. Mutually exclusive with 'topic'>,
313
+ * limit: <Number; maximum number of messages to return. Default is 20 for standard/single-topic fetches. When using 'topics', no default limit is applied unless explicitly provided, and the limit applies to the total returned messages, not per topic>,
314
+ * }
302
315
  * @param onSuccess will be called on success
303
316
  * @param {Function} onError will be called on error
304
317
  */