Repository navigation
Expand file tree
/
Copy pathIterableApi.java
More file actions
2000 lines (1740 loc) · 81.6 KB
/
Copy pathIterableApi.java
File metadata and controls
2000 lines (1740 loc) · 81.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.iterable.iterableapi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.core.app.NotificationManagerCompat;
import com.iterable.iterableapi.util.DeviceInfoUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
/**
* Created by David Truong dt@iterable.com
*/
public class IterableApi {
//region SDK (private/internal)
//---------------------------------------------------------------------------------------
static volatile IterableApi sharedInstance = new IterableApi();
private static final String TAG = "IterableApi";
Context _applicationContext; // Package-private for background initializer access
IterableConfig config;
String _apiKey; // Package-private for background initializer access
private String _email;
private String _userId;
String _userIdUnknown;
private String _authToken;
private boolean _debugMode;
private Bundle _payloadData;
private IterableNotificationData _notificationData;
private String _deviceId;
private boolean _firstForegroundHandled;
private boolean _autoRetryOnJwtFailure;
private IterableHelper.SuccessHandler _setUserSuccessCallbackHandler;
private IterableHelper.FailureHandler _setUserFailureCallbackHandler;
IterableApiClient apiClient = new IterableApiClient(new IterableApiAuthProvider());
final ApiEndpointClassification apiEndpointClassification = new ApiEndpointClassification();
private static final UnknownUserMerge unknownUserMerge = new UnknownUserMerge();
private @Nullable UnknownUserManager unknownUserManager;
private @Nullable IterableInAppManager inAppManager;
private @Nullable IterableEmbeddedManager embeddedManager;
private final IterableInAppManager emptyInAppManager = new EmptyInAppManager();
private final IterableEmbeddedManager emptyEmbeddedManager = new EmptyEmbeddedManager();
private String inboxSessionId;
private IterableAuthManager authManager;
private ConcurrentHashMap<String, String> deviceAttributes = new ConcurrentHashMap<>();
private IterableKeychain keychain;
private final IterablePushRegistration pushRegistration;
//region Background Initialization - Delegated to IterableBackgroundInitializer
//---------------------------------------------------------------------------------------
/**
* Masks PII data for logging - shows only first character followed by asterisks
* @param value The value to mask (email, userId, authToken, etc.)
* @return Masked string (e.g., "u***") or "null" if input is null
*/
private static String maskPII(@Nullable String value) {
if (value == null || value.isEmpty()) {
return "null";
}
if (value.length() == 1) {
return "*";
}
return value.charAt(0) + "***";
}
/**
* Helper method to queue operations if background initialization is in progress,
* otherwise execute immediately for backward compatibility
*/
private void queueOrExecute(Runnable operation, String description) {
// Only queue if background initialization is actively running
if (IterableBackgroundInitializer.isInitializingInBackground()) {
IterableBackgroundInitializer.queueOrExecute(operation, description);
} else {
// Execute immediately for backward compatibility when not using background init
operation.run();
}
}
void fetchRemoteConfiguration() {
apiClient.getRemoteConfiguration(new IterableHelper.IterableActionHandler() {
@Override
public void execute(@Nullable String data) {
if (data == null) {
IterableLogger.e(TAG, "Remote configuration returned null");
return;
}
try {
JSONObject jsonData = new JSONObject(data);
boolean offlineConfiguration = jsonData.getBoolean(IterableConstants.KEY_OFFLINE_MODE);
sharedInstance.apiClient.setOfflineProcessingEnabled(offlineConfiguration);
SharedPreferences sharedPref = sharedInstance.getMainActivityContext().getSharedPreferences(IterableConstants.SHARED_PREFS_SAVED_CONFIGURATION, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IterableConstants.SHARED_PREFS_OFFLINE_MODE_KEY, offlineConfiguration);
// Parse autoRetry flag from remote config.
if (jsonData.has(IterableConstants.KEY_AUTO_RETRY)) {
boolean autoRetryRemote = jsonData.getBoolean(IterableConstants.KEY_AUTO_RETRY);
editor.putBoolean(IterableConstants.SHARED_PREFS_AUTO_RETRY_KEY, autoRetryRemote);
_autoRetryOnJwtFailure = autoRetryRemote;
}
editor.apply();
} catch (JSONException e) {
IterableLogger.e(TAG, "Failed to read remote configuration");
}
}
});
}
public String getEmail() {
return _email;
}
public String getUserId() {
return _userId;
}
public String getAuthToken() {
return _authToken;
}
private void checkAndUpdateAuthToken(@Nullable String authToken) {
// If authHandler exists and if authToken is new, it will be considered as a call to update the authToken.
if (config.authHandler != null && authToken != null && authToken != _authToken) {
setAuthToken(authToken);
}
}
/**
* Stores attribution information.
* @param attributionInfo Attribution information object
*/
void setAttributionInfo(IterableAttributionInfo attributionInfo) {
if (_applicationContext == null) {
IterableLogger.e(TAG, "setAttributionInfo: Iterable SDK is not initialized with a context.");
return;
}
IterableUtil.saveExpirableJsonObject(
getPreferences(),
IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_KEY,
attributionInfo.toJSONObject(),
3600 * IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_EXPIRATION_HOURS * 1000
);
}
Map<String, String> getDeviceAttributes() {
return deviceAttributes;
}
/**
* Returns the current context for the application.
* @return
*/
Context getMainActivityContext() {
return _applicationContext;
}
/**
* Returns an {@link IterableAuthManager} that can be used to manage mobile auth.
* Make sure the Iterable API is initialized before calling this method.
* @return {@link IterableAuthManager} instance
*/
@NonNull
IterableAuthManager getAuthManager() {
if (authManager == null) {
authManager = new IterableAuthManager(this, config.authHandler, config.retryPolicy, config.expiringAuthTokenRefreshPeriodMillis);
}
return authManager;
}
@Nullable
IterableKeychain getKeychain() {
if (_applicationContext == null) {
return null;
}
if (keychain == null) {
try {
keychain = new IterableKeychain(getMainActivityContext(), config.decryptionFailureHandler, null, config.keychainEncryption);
} catch (Exception e) {
IterableLogger.e(TAG, "Failed to create IterableKeychain", e);
}
}
return keychain;
}
static void loadLastSavedConfiguration(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.SHARED_PREFS_SAVED_CONFIGURATION, Context.MODE_PRIVATE);
boolean offlineMode = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_OFFLINE_MODE_KEY, false);
sharedInstance.apiClient.setOfflineProcessingEnabled(offlineMode);
sharedInstance._autoRetryOnJwtFailure = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_AUTO_RETRY_KEY, false);
}
/**
* Returns whether auto-retry on JWT failure is enabled, as determined by remote configuration.
*/
boolean isAutoRetryOnJwtFailure() {
return _autoRetryOnJwtFailure;
}
/**
* Set the notification icon with the given iconName.
* @param context
* @param iconName
*/
static void setNotificationIcon(Context context, String iconName) {
SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(IterableConstants.NOTIFICATION_ICON_NAME, iconName);
editor.apply();
}
/**
* Returns the stored notification icon.
* @param context
* @return
*/
static String getNotificationIcon(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE);
return sharedPref.getString(IterableConstants.NOTIFICATION_ICON_NAME, "");
}
/**
* Sets debug mode.
* @param debugMode
*/
void setDebugMode(boolean debugMode) {
_debugMode = debugMode;
}
/**
* Gets the current state of the debug mode.
* @return
*/
boolean getDebugMode() {
return _debugMode;
}
/**
* Set the payload for a given intent if it is from Iterable.
* @param intent
*/
void setPayloadData(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY) && !IterableNotificationHelper.isGhostPush(extras)) {
setPayloadData(extras);
}
}
/**
* Sets the payload bundle.
* @param bundle
*/
void setPayloadData(Bundle bundle) {
_payloadData = bundle;
}
/**
* Sets the IterableNotification data
* @param data
*/
void setNotificationData(IterableNotificationData data) {
_notificationData = data;
if (data != null) {
setAttributionInfo(new IterableAttributionInfo(data.getCampaignId(), data.getTemplateId(), data.getMessageId()));
}
}
/**
* Gets a list of InAppNotifications from Iterable; passes the result to the callback.
* Now package-private. If you were previously using this method, use
* {@link IterableInAppManager#getMessages()} instead
*
* @param count the number of messages to fetch
* @param onCallback
*/
void getInAppMessages(int count, @NonNull IterableHelper.IterableActionHandler onCallback) {
if (!checkSDKInitialization()) {
return;
}
apiClient.getInAppMessages(count, onCallback);
}
/**
* Gets a list of placements for the list of placement ids passed in from Iterable and
* passes the result to the callback;
* To get list of messages as a list of Embedded Messages in memory, use
* {@link IterableEmbeddedManager#getMessages(long)} instead.
* If no placement ids are passed in, all available messages with corresponding placement id will be returned
*
* @param placementIds array of placement ids - optional
* @param onCallback
*/
public void getEmbeddedMessages(@Nullable Long[] placementIds, @NonNull IterableHelper.IterableActionHandler onCallback) {
if (!checkSDKInitialization()) {
return;
}
apiClient.getEmbeddedMessages(placementIds, onCallback);
}
/**
* Gets a list of placements for the list of placement ids passed in from Iterable and
* passes the result to the success or failure callback;
* To get list of messages as a list of Embedded Messages in memory, use
* {@link IterableEmbeddedManager#getMessages(long)} instead.
* If no placement ids are passed in, all available messages with corresponding placement id will be returned
*
* @param placementIds array of placement ids - optional
* @param onSuccess
* @param onFailure
*/
public void getEmbeddedMessages(@Nullable Long[] placementIds, @NonNull IterableHelper.SuccessHandler onSuccess, @NonNull IterableHelper.FailureHandler onFailure) {
if (!checkSDKInitialization()) {
return;
}
apiClient.getEmbeddedMessages(placementIds, onSuccess, onFailure);
}
/**
* A package-private method to get a list of Embedded Messages from Iterable;
* Passes the result to the success or failure callback.
* Used by the IterableEmbeddedManager.
*
* To get list of messages as a list of EmbeddedMessages in memory, use
* {@link IterableEmbeddedManager#getMessages(long)} instead
*
* @param onSuccess
* @param onFailure
*/
void getEmbeddedMessages(@NonNull IterableHelper.SuccessHandler onSuccess, @NonNull IterableHelper.FailureHandler onFailure) {
if (!checkSDKInitialization()) {
return;
}
apiClient.getEmbeddedMessages(null, onSuccess, onFailure);
}
/**
* Tracks in-app delivery events (per in-app)
* @param message the in-app message to be tracked as delivered */
void trackInAppDelivery(@NonNull IterableInAppMessage message) {
if (!checkSDKInitialization()) {
return;
}
if (message == null) {
IterableLogger.e(TAG, "trackInAppDelivery: message is null");
return;
}
apiClient.trackInAppDelivery(message);
}
/**
* Tracks embedded message received events (per embedded message)
* @param message the embedded message to be tracked as received */
void trackEmbeddedMessageReceived(@NonNull IterableEmbeddedMessage message) {
if (!checkSDKInitialization()) {
return;
}
if (message == null) {
IterableLogger.e(TAG, "trackEmbeddedMessageReceived: message is null");
return;
}
apiClient.trackEmbeddedMessageReceived(message);
}
private String getPushIntegrationName() {
if (config.pushIntegrationName != null) {
return config.pushIntegrationName;
} else {
return _applicationContext.getPackageName();
}
}
private void logoutPreviousUser() {
if (config.autoPushRegistration && isInitialized()) {
disablePush();
}
// Only reset managers if they're initialized
if (inAppManager != null) {
inAppManager.reset();
}
if (embeddedManager != null) {
embeddedManager.reset();
}
if (authManager != null) {
authManager.reset();
}
if (apiClient != null) {
apiClient.onLogout();
}
}
private void onLogin(
@Nullable String authToken,
String userIdOrEmail,
boolean isEmail,
boolean merge,
boolean replay,
boolean isUnknown,
@Nullable IterableHelper.FailureHandler failureHandler
) {
if (!isInitialized()) {
setAuthToken(null);
return;
}
getAuthManager().pauseAuthRetries(false);
if (authToken != null) {
setAuthToken(authToken);
attemptMergeAndEventReplay(userIdOrEmail, isEmail, merge, replay, isUnknown, failureHandler);
} else {
getAuthManager().requestNewAuthToken(false, data -> attemptMergeAndEventReplay(userIdOrEmail, isEmail, merge, replay, isUnknown, failureHandler));
}
}
private void completeUserLogin() {
completeUserLogin(_email, _userId, _authToken);
}
/**
* Completes user login with validated credentials.
* This method ensures sensitive operations (syncInApp, syncMessages, registerForPush) only execute
* with server-validated user data, preventing user-controlled bypass attacks.
*
* @param email Server-validated email (can be null)
* @param userId Server-validated userId (can be null)
* @param authToken Server-validated authToken (must not be null for sensitive operations when JWT auth is enabled)
*/
private void completeUserLogin(@Nullable String email, @Nullable String userId, @Nullable String authToken) {
if (!isInitialized()) {
return;
}
// Only enforce authToken requirement when JWT auth is enabled
// This prevents user-controlled bypass where unvalidated userId/email from keychain
// could be used to access another user's data in JWT auth scenarios
if (config.authHandler != null && authToken == null) {
IterableLogger.w(TAG, "Cannot complete user login - JWT auth enabled but no validated authToken present");
if (_setUserFailureCallbackHandler != null) {
_setUserFailureCallbackHandler.onFailure("JWT authentication is enabled but no valid authToken is available", null);
resetCallbackHandlers();
}
return;
}
if (config.autoPushRegistration) {
registerForPush();
} else if (_setUserSuccessCallbackHandler != null) {
_setUserSuccessCallbackHandler.onSuccess(IterableResponse.setEmailLocalSuccessResponse);
resetCallbackHandlers();
}
getInAppManager().syncInApp();
getEmbeddedManager().syncMessages();
}
private final IterableActivityMonitor.AppStateCallback activityMonitorListener = new IterableActivityMonitor.AppStateCallback() {
@Override
public void onSwitchToForeground() {
onForeground();
}
@Override
public void onSwitchToBackground() {}
};
private void onForeground() {
if (!_firstForegroundHandled) {
_firstForegroundHandled = true;
if (sharedInstance.config.autoPushRegistration && sharedInstance.isInitialized()) {
sharedInstance.registerForPush();
}
fetchRemoteConfiguration();
}
if (_applicationContext == null || sharedInstance.getMainActivityContext() == null) {
IterableLogger.w(TAG, "onForeground: _applicationContext is null");
return;
}
boolean systemNotificationEnabled = NotificationManagerCompat.from(_applicationContext).areNotificationsEnabled();
SharedPreferences sharedPref = sharedInstance.getMainActivityContext().getSharedPreferences(IterableConstants.SHARED_PREFS_FILE, Context.MODE_PRIVATE);
boolean hasStoredPermission = sharedPref.contains(IterableConstants.SHARED_PREFS_DEVICE_NOTIFICATIONS_ENABLED);
boolean isNotificationEnabled = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_DEVICE_NOTIFICATIONS_ENABLED, false);
if (sharedInstance.isInitialized()) {
// Process any pending actions that couldn't be handled when they arrived
IterablePushNotificationUtil.processPendingAction(_applicationContext);
if (sharedInstance.config.autoPushRegistration && hasStoredPermission && (isNotificationEnabled != systemNotificationEnabled)) {
sharedInstance.registerForPush();
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IterableConstants.SHARED_PREFS_DEVICE_NOTIFICATIONS_ENABLED, systemNotificationEnabled);
editor.apply();
}
}
private boolean isInitialized() {
return _apiKey != null && (_email != null || _userId != null);
}
boolean checkSDKInitialization() {
if (!isInitialized()) {
IterableLogger.w(TAG, "Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods");
return false;
}
return true;
}
private SharedPreferences getPreferences() {
return _applicationContext.getSharedPreferences(IterableConstants.SHARED_PREFS_FILE, Context.MODE_PRIVATE);
}
private String getDeviceId() {
if (_deviceId == null) {
_deviceId = getPreferences().getString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, null);
if (_deviceId == null) {
_deviceId = UUID.randomUUID().toString();
getPreferences().edit().putString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, _deviceId).apply();
}
}
return _deviceId;
}
/**
* Completion handler interface for storeAuthData operations.
* Receives the exact credentials that were stored to keychain.
*/
private interface AuthDataStorageHandler {
void onAuthDataStored(String email, String userId, String authToken);
}
private void storeAuthData() {
storeAuthData(null);
}
/**
* Stores auth data and optionally invokes completion handler with the stored credentials.
*
* SECURITY - TOCTOU Protection:
* When a completion handler is provided, it receives the exact credentials that were stored
* to keychain. This prevents TOCTOU (Time-Of-Check-Time-Of-Use) attacks where:
* 1. Credentials are stored to keychain
* 2. Attacker modifies keychain (between store and read)
* 3. Sensitive operations use tampered credentials
*
* By capturing credentials BEFORE storage and passing them directly via completion handler,
* we ensure completeUserLogin uses exactly what was stored, not what's currently in keychain.
*
* @param completionHandler Optional handler invoked synchronously after storage with the stored credentials
*/
private void storeAuthData(AuthDataStorageHandler completionHandler) {
if (_applicationContext == null) {
return;
}
// SECURITY: Capture current instance field values BEFORE storing to keychain.
// These captured values will be passed to completion handler, ensuring the caller
// receives exactly what was stored, not potentially modified keychain data.
final String storedEmail = _email;
final String storedUserId = _userId;
final String storedAuthToken = _authToken;
IterableKeychain iterableKeychain = getKeychain();
if (iterableKeychain != null) {
iterableKeychain.saveEmail(_email);
iterableKeychain.saveUserId(_userId);
iterableKeychain.saveUserIdUnknown(_userIdUnknown);
iterableKeychain.saveAuthToken(_authToken);
} else {
IterableLogger.e(TAG, "Shared preference creation failed. ");
}
// Invoke completion handler with the captured credentials
if (completionHandler != null) {
completionHandler.onAuthDataStored(storedEmail, storedUserId, storedAuthToken);
}
}
private void retrieveEmailAndUserId() {
if (_applicationContext == null) {
return;
}
IterableKeychain iterableKeychain = getKeychain();
if (iterableKeychain != null) {
_email = iterableKeychain.getEmail();
_userId = iterableKeychain.getUserId();
_userIdUnknown = iterableKeychain.getUserIdUnknown();
_authToken = iterableKeychain.getAuthToken();
} else {
IterableLogger.e(TAG, "retrieveEmailAndUserId: Shared preference creation failed. Could not retrieve email/userId");
}
if (config.authHandler != null && checkSDKInitialization()) {
if (_authToken != null) {
getAuthManager().queueExpirationRefresh(_authToken);
} else {
IterableLogger.d(TAG, "Auth token found as null. Rescheduling auth token refresh");
getAuthManager().scheduleAuthTokenRefresh(authManager.getNextRetryInterval(), IterableAuthRefreshReason.STORED_TOKEN_MISSING, null);
}
}
}
private class IterableApiAuthProvider implements IterableApiClient.AuthProvider {
@Nullable
@Override
public String getEmail() {
return _email;
}
@Nullable
@Override
public String getUserId() {
return _userId;
}
@Nullable
@Override
public String getUserIdUnknown() {
return _userIdUnknown;
}
@Nullable
@Override
public String getAuthToken() {
return _authToken;
}
@Override
public String getApiKey() {
return _apiKey;
}
@Override
public String getDeviceId() {
return IterableApi.this.getDeviceId();
}
@Override
public Context getContext() {
return _applicationContext;
}
@Override
public void resetAuth() {
IterableLogger.d(TAG, "Resetting authToken");
_authToken = null;
}
}
//endregion
//region API functions (private/internal)
//---------------------------------------------------------------------------------------
void setAuthToken(String authToken, boolean bypassAuth) {
if (isInitialized()) {
if ((authToken != null && !authToken.equalsIgnoreCase(_authToken)) || (_authToken != null && !_authToken.equalsIgnoreCase(authToken))) {
_authToken = authToken;
// SECURITY: Use completion handler to atomically store and pass validated credentials.
// The completion handler receives exact values stored to keychain, preventing TOCTOU
// attacks where keychain could be modified between storage and completeUserLogin execution.
storeAuthData((email, userId, token) -> completeUserLogin(email, userId, token));
} else if (bypassAuth) {
// SECURITY: Pass current credentials directly to completeUserLogin.
// completeUserLogin will validate authToken presence when JWT auth is enabled.
completeUserLogin(_email, _userId, _authToken);
}
}
}
protected void registerDeviceToken(final @Nullable String email, final @Nullable String userId, final @Nullable String authToken, final @NonNull String applicationName, final @NonNull String deviceToken, final Map<String, String> deviceAttributes) {
registerDeviceToken(email, userId, authToken, applicationName, deviceToken, deviceAttributes, IterableExecutors.push());
}
void registerDeviceToken(final @Nullable String email, final @Nullable String userId, final @Nullable String authToken, final @NonNull String applicationName, final @NonNull String deviceToken, final Map<String, String> deviceAttributes, Executor executor) {
if (shouldSubmitDeviceTokenRegistration(deviceToken)) {
executor.execute(() -> registerDeviceToken(email, userId, authToken, applicationName, deviceToken, null, deviceAttributes));
}
}
private boolean shouldSubmitDeviceTokenRegistration(@Nullable String deviceToken) {
if (deviceToken == null) {
return false;
}
if (!checkSDKInitialization() && _userIdUnknown == null) {
if (sharedInstance.config.enableUnknownUserActivation) {
unknownUserManager.trackUnknownTokenRegistration(deviceToken);
}
return false;
}
return true;
}
protected void disableToken(@Nullable String email, @Nullable String userId, @NonNull String token) {
disableToken(email, userId, null, token, null, null);
}
/**
* Internal api call made from IterablePushRegistration after a registrationToken is obtained.
* It disables the device for all users with this device by default. If `email` or `userId` is provided, it will disable the device for the specific user.
* @param email User email for whom to disable the device.
* @param userId User ID for whom to disable the device.
* @param authToken
* @param deviceToken The device token
*/
protected void disableToken(@Nullable String email, @Nullable String userId, @Nullable String authToken, @NonNull String deviceToken, @Nullable IterableHelper.SuccessHandler onSuccess, @Nullable IterableHelper.FailureHandler onFailure) {
if (deviceToken == null) {
IterableLogger.d(TAG, "device token not available");
return;
}
apiClient.disableToken(email, userId, authToken, deviceToken, onSuccess, onFailure);
}
/**
* Registers the GCM registration ID with Iterable.
*
* @param authToken
* @param applicationName
* @param deviceToken
* @param dataFields
*/
protected void registerDeviceToken(@Nullable String email, @Nullable String userId, @Nullable String authToken, @NonNull String applicationName, @NonNull String deviceToken, @Nullable JSONObject dataFields, Map<String, String> deviceAttributes) {
if (!checkSDKInitialization()) {
return;
}
if (deviceToken == null) {
IterableLogger.e(TAG, "registerDeviceToken: token is null");
return;
}
if (applicationName == null) {
IterableLogger.e(TAG, "registerDeviceToken: applicationName is null, check that pushIntegrationName is set in IterableConfig");
}
IterableHelper.SuccessHandler wrappedSuccessHandler = getSuccessHandler();
IterableHelper.FailureHandler wrappedFailureHandler = getFailureHandler();
apiClient.registerDeviceToken(email, userId, authToken, applicationName, deviceToken, dataFields, deviceAttributes, wrappedSuccessHandler, wrappedFailureHandler);
}
private IterableHelper.SuccessHandler getSuccessHandler() {
IterableHelper.SuccessHandler wrappedSuccessHandler = null;
if (_setUserSuccessCallbackHandler != null || (config.enableUnknownUserActivation && getVisitorUsageTracked() && config.identityResolution.getReplayOnVisitorToKnown())) {
final IterableHelper.SuccessHandler originalSuccessHandler = _setUserSuccessCallbackHandler;
wrappedSuccessHandler = data -> {
trackConsentOnDeviceRegistration();
if (originalSuccessHandler != null) {
originalSuccessHandler.onSuccess(data);
resetCallbackHandlers();
}
};
}
return wrappedSuccessHandler;
}
private IterableHelper.FailureHandler getFailureHandler() {
IterableHelper.FailureHandler wrappedFailureHandler = null;
if (_setUserFailureCallbackHandler != null || (config.enableUnknownUserActivation && getVisitorUsageTracked() && config.identityResolution.getReplayOnVisitorToKnown())) {
final IterableHelper.FailureHandler originalFailureHandler = _setUserFailureCallbackHandler;
wrappedFailureHandler = (reason, data) -> {
trackConsentOnDeviceRegistration();
if (originalFailureHandler != null) {
originalFailureHandler.onFailure(reason, data);
resetCallbackHandlers();
}
};
}
return wrappedFailureHandler;
}
private void resetCallbackHandlers() {
_setUserFailureCallbackHandler = null;
_setUserSuccessCallbackHandler = null;
}
//endregion
//region SDK initialization
//---------------------------------------------------------------------------------------
@NonNull
public static IterableApi getInstance() {
return sharedInstance;
}
public static void initialize(@NonNull Context context, @NonNull String apiKey) {
initialize(context, apiKey, null);
}
public static void initialize(@NonNull Context context, @NonNull String apiKey, @Nullable IterableConfig config) {
sharedInstance._applicationContext = context.getApplicationContext();
sharedInstance._apiKey = apiKey;
sharedInstance.config = config;
if (sharedInstance.config == null) {
sharedInstance.config = new IterableConfig.Builder().build();
}
sharedInstance.retrieveEmailAndUserId();
// Process a pending push action before registering lifecycle callbacks so attribution
// is set before the first onForeground(), which otherwise registers for push twice.
if (IterablePushNotificationUtil.hasPendingAction()) {
IterablePushNotificationUtil.processPendingAction(context);
}
IterableActivityMonitor.getInstance().registerLifecycleCallbacks(context);
IterableActivityMonitor.getInstance().addCallback(sharedInstance.activityMonitorListener);
if (sharedInstance.inAppManager == null) {
sharedInstance.inAppManager = new IterableInAppManager(
sharedInstance,
sharedInstance.config.inAppHandler,
sharedInstance.config.inAppDisplayInterval,
sharedInstance.config.useInMemoryStorageForInApps);
}
if (sharedInstance.embeddedManager == null) {
sharedInstance.embeddedManager = new IterableEmbeddedManager(
sharedInstance
);
}
if (sharedInstance.unknownUserManager == null) {
sharedInstance.unknownUserManager = new UnknownUserManager(
sharedInstance
);
}
loadLastSavedConfiguration(context);
IterablePushNotificationUtil.processPendingAction(context);
if (!sharedInstance.checkSDKInitialization()
&& sharedInstance._userIdUnknown == null
&& sharedInstance.config.enableUnknownUserActivation
&& sharedInstance.getVisitorUsageTracked()) {
sharedInstance.unknownUserManager.updateUnknownSession();
sharedInstance.unknownUserManager.getUnknownCriteria();
}
if (DeviceInfoUtils.isFireTV(context.getPackageManager())) {
try {
JSONObject dataFields = new JSONObject();
JSONObject deviceDetails = new JSONObject();
DeviceInfoUtils.populateDeviceDetails(deviceDetails, context, sharedInstance.getDeviceId(), null);
dataFields.put(IterableConstants.KEY_FIRETV, deviceDetails);
sharedInstance.updateUser(dataFields, false);
} catch (JSONException e) {
IterableLogger.e(TAG, "initialize: exception", e);
}
}
// Notify initialization completion
IterableBackgroundInitializer.notifyInitializationComplete();
}
/**
* Initialize the Iterable SDK in the background to avoid ANRs.
* This method returns immediately and performs all initialization work on a background thread.
* Any API calls made before initialization completes will be queued and executed after initialization.
*
* @param context Application context
* @param apiKey Iterable API key
* @param callback Optional callback for initialization completion (can be null)
*/
public static void initializeInBackground(@NonNull Context context,
@NonNull String apiKey,
@Nullable IterableInitializationCallback callback) {
IterableBackgroundInitializer.initializeInBackground(context, apiKey, null, callback);
}
/**
* Initialize the Iterable SDK in the background to avoid ANRs.
* This method returns immediately and performs all initialization work on a background thread.
* Any API calls made before initialization completes will be queued and executed after initialization.
*
* @param context Application context
* @param apiKey Iterable API key
* @param config Optional configuration (can be null)
* @param callback Optional callback for initialization completion (can be null)
*/
public static void initializeInBackground(@NonNull Context context,
@NonNull String apiKey,
@Nullable IterableConfig config,
@Nullable IterableInitializationCallback callback) {
IterableBackgroundInitializer.initializeInBackground(context, apiKey, config, callback);
}
/**
* Check if SDK initialization is in progress (covers both normal and background initialization)
* @return true if initialization is currently running
*/
public static boolean isSDKInitializing() {
return IterableBackgroundInitializer.isInitializingInBackground();
}
/**
* Check if SDK is fully initialized and ready to use.
* This checks both that initialization has been run (sync or background) and that
* the SDK is properly configured with API key and user identification.
* @return true if SDK is fully initialized and ready for use
*/
public static boolean isSDKInitialized() {
// Check if initialization has been run (either sync or background)
boolean initializationRun = sharedInstance._apiKey != null && sharedInstance._applicationContext != null;
// Check if background initialization has completed (if it was used)
boolean backgroundInitComplete = !IterableBackgroundInitializer.isInitializingInBackground();
// Check if SDK is properly configured (private method logic)
boolean sdkConfigured = sharedInstance.isInitialized();
return initializationRun && backgroundInitComplete && sdkConfigured;
}
/**
* Register a callback to be notified when SDK initialization completes.
* If the SDK is already initialized, the callback is invoked immediately.
*
* @param callback The callback to be notified when initialization completes
*/
public static void onSDKInitialized(@NonNull IterableInitializationCallback callback) {
IterableBackgroundInitializer.onSDKInitialized(callback);
}
public static void setContext(Context context) {
IterableActivityMonitor.getInstance().registerLifecycleCallbacks(context);
}
/**
* Initialize minimal context for push notification handling when the SDK hasn't been fully initialized.
* This is used internally when processing push actions in the background (e.g., openApp=false scenarios)
* to ensure custom actions can be executed even before IterableApi.initialize() is called.
*
* This method only sets the application context if it hasn't already been set, and does not
* perform full SDK initialization. For full initialization, use {@link #initialize(Context, String, IterableConfig)}.
*
* @param context The context to use for initialization (will use application context)
*/
static void initializeForPush(@Nullable Context context) {
if (context == null) {
IterableLogger.w(TAG, "initializeForPush: context is null");
return;
}
if (sharedInstance._applicationContext == null) {
sharedInstance._applicationContext = context.getApplicationContext();
IterableLogger.d(TAG, "initializeForPush: Application context set for background push handling");
}
}
IterableApi() {
config = new IterableConfig.Builder().build();
pushRegistration = new IterablePushRegistration();
}
IterableApi(IterableInAppManager inAppManager) {
this();
this.inAppManager = inAppManager;
}
IterableApi(IterableApiClient apiClient, IterableInAppManager inAppManager) {
this(inAppManager);
this.apiClient = apiClient;
}
IterableApi(IterableInAppManager inAppManager, IterableEmbeddedManager embeddedManager,
IterablePushRegistration pushRegistration) {
config = new IterableConfig.Builder().build();
this.inAppManager = inAppManager;
this.embeddedManager = embeddedManager;
this.pushRegistration = Objects.requireNonNull(pushRegistration);
}
void setRequestDispatcher(IterableRequestDispatcher requestDispatcher) {
apiClient = new IterableApiClient(new IterableApiAuthProvider(),
IterableRequestDispatchers.same(Objects.requireNonNull(requestDispatcher)));
}
//endregion
//region SDK public functions