-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathOneSignalUserManagerImpl.swift
More file actions
896 lines (762 loc) · 37 KB
/
Copy pathOneSignalUserManagerImpl.swift
File metadata and controls
896 lines (762 loc) · 37 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
/*
Modified MIT License
Copyright 2022 OneSignal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import OneSignalCore
import OneSignalOSCore
import OneSignalNotifications
/**
Public-facing API to access the User Manager.
*/
@objc protocol OneSignalUserManager {
// swiftlint:disable identifier_name
var User: OSUser { get }
func login(externalId: String, token: String?)
func logout()
// Location
func setLocation(latitude: Float, longitude: Float)
// Purchase Tracking
func sendPurchases(_ purchases: [[String: AnyObject]])
}
/**
This is the user interface exposed to the public.
*/
@objc public protocol OSUser {
var pushSubscription: OSPushSubscription { get }
var onesignalId: String? { get }
var externalId: String? { get }
/**
Add an observer to the user state, allowing the provider to be notified when the user state has changed.
Important: When using the observer to retrieve the `onesignalId`, check the `externalId` as well to confirm the values are associated with the expected user.
*/
func addObserver(_ observer: OSUserStateObserver)
func removeObserver(_ observer: OSUserStateObserver)
// Aliases
func addAlias(label: String, id: String)
func addAliases(_ aliases: [String: String])
func removeAlias(_ label: String)
func removeAliases(_ labels: [String])
// Tags
func addTag(key: String, value: String)
func addTags(_ tags: [String: String])
func removeTag(_ tag: String)
func removeTags(_ tags: [String])
func getTags() -> [String: String]
// Email
func addEmail(_ email: String)
func removeEmail(_ email: String)
// SMS
func addSms(_ number: String)
func removeSms(_ number: String)
// Language
func setLanguage(_ language: String)
// JWT Token Expire
typealias OSJwtCompletionBlock = (_ newJwtToken: String) -> Void
typealias OSJwtExpiredHandler = (_ externalId: String, _ completion: OSJwtCompletionBlock) -> Void
func onJwtExpired(expiredHandler: @escaping OSJwtExpiredHandler)
}
/**
This is the push subscription interface exposed to the public.
*/
@objc public protocol OSPushSubscription {
var id: String? { get }
var token: String? { get }
var optedIn: Bool { get }
func optIn()
func optOut()
func addObserver(_ observer: OSPushSubscriptionObserver)
func removeObserver(_ observer: OSPushSubscriptionObserver)
}
@objc
public class OneSignalUserManagerImpl: NSObject, OneSignalUserManager {
@objc public static let sharedInstance = OneSignalUserManagerImpl()
/**
Convenience accessor. We access the push subscription model via the model store instead of via`user.pushSubscriptionModel`.
If privacy consent is set in a wrong order, we may have sent requests, but hydrate on a mock user.
However, we want to set tokens and subscription ID on the actual push subscription model.
*/
var pushSubscriptionModel: OSSubscriptionModel? {
return pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)
}
@objc public var pushSubscriptionId: String? {
return _user?.pushSubscriptionModel.subscriptionId
}
@objc public var language: String? {
return _user?.propertiesModel.language
}
@objc public let pushSubscriptionImpl: OSPushSubscriptionImpl
var identityModelRepo = OSIdentityModelRepo()
let newRecordsState = OSNewRecordsState()
private let startQueue = DispatchQueue(label: "com.onesignal.user.start")
var hasCalledStart = false
private var jwtExpiredHandler: OSJwtExpiredHandler?
var user: OSUserInternal {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return _mockUser
}
start()
if let user = _user {
return user
}
// There is no user instance, initialize a "guest user"
return createNewUser(externalId: nil, token: nil)
}
var _user: OSUserInternal?
// This is a user instance to operate on when there is no app_id and/or privacy consent yet, effectively no-op.
// The models are not added to any model stores.
private let _mockUser = OSUserInternalImpl(
identityModel: OSIdentityModel(aliases: nil, changeNotifier: OSEventProducer()),
propertiesModel: OSPropertiesModel(changeNotifier: OSEventProducer()),
pushSubscriptionModel: OSSubscriptionModel(type: .push, address: nil, subscriptionId: nil, reachable: false, isDisabled: true, changeNotifier: OSEventProducer()))
@objc public var requiresUserAuth = false
// User State Observer
private var _userStateChangesObserver: OSObservable<OSUserStateObserver, OSUserChangedState>?
var userStateChangesObserver: OSObservable<OSUserStateObserver, OSUserChangedState> {
if let observer = _userStateChangesObserver {
return observer
}
let userStateChangesObserver = OSObservable<OSUserStateObserver, OSUserChangedState>(change: #selector(OSUserStateObserver.onUserStateDidChange(state:)))
_userStateChangesObserver = userStateChangesObserver
return userStateChangesObserver
}
// Model Stores
let identityModelStore = OSModelStore<OSIdentityModel>(changeSubscription: OSEventProducer(), storeKey: OS_IDENTITY_MODEL_STORE_KEY).registerAsUserObserver()
let propertiesModelStore = OSModelStore<OSPropertiesModel>(changeSubscription: OSEventProducer(), storeKey: OS_PROPERTIES_MODEL_STORE_KEY).registerAsUserObserver()
// Holds email and sms subscription models
let subscriptionModelStore = OSModelStore<OSSubscriptionModel>(changeSubscription: OSEventProducer(), storeKey: OS_SUBSCRIPTION_MODEL_STORE_KEY).registerAsUserObserver()
// Holds a single push subscription model
let pushSubscriptionModelStore = OSModelStore<OSSubscriptionModel>(changeSubscription: OSEventProducer(), storeKey: OS_PUSH_SUBSCRIPTION_MODEL_STORE_KEY)
// These must be initialized in init()
let identityModelStoreListener: OSIdentityModelStoreListener
let propertiesModelStoreListener: OSPropertiesModelStoreListener
let subscriptionModelStoreListener: OSSubscriptionModelStoreListener
let pushSubscriptionModelStoreListener: OSSubscriptionModelStoreListener
// Executors must be initialize after sharedInstance is initialized
var userExecutor: OSUserExecutor?
var propertyExecutor: OSPropertyOperationExecutor?
var identityExecutor: OSIdentityOperationExecutor?
var subscriptionExecutor: OSSubscriptionOperationExecutor?
private override init() {
self.identityModelStoreListener = OSIdentityModelStoreListener(store: identityModelStore)
self.propertiesModelStoreListener = OSPropertiesModelStoreListener(store: propertiesModelStore)
self.subscriptionModelStoreListener = OSSubscriptionModelStoreListener(store: subscriptionModelStore)
self.pushSubscriptionModelStoreListener = OSSubscriptionModelStoreListener(store: pushSubscriptionModelStore)
self.pushSubscriptionImpl = OSPushSubscriptionImpl(pushSubscriptionModelStore: pushSubscriptionModelStore)
}
@objc
public func start() {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return
}
// Use a serial queue to make the start process atomic
startQueue.sync {
guard !hasCalledStart else {
return
}
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignalUserManager calling start")
OSNotificationsManager.delegate = self
var hasCachedUser = false
// Path 1. Load user from cache, if any
// Corrupted state if any of these models exist without the others
if let identityModel = identityModelStore.getModels()[OS_IDENTITY_MODEL_KEY],
let propertiesModel = propertiesModelStore.getModels()[OS_PROPERTIES_MODEL_KEY],
let pushSubscription = pushSubscriptionModelStore.getModels()[OS_PUSH_SUBSCRIPTION_MODEL_KEY] {
hasCachedUser = true
_user = OSUserInternalImpl(identityModel: identityModel, propertiesModel: propertiesModel, pushSubscriptionModel: pushSubscription)
addIdentityModelToRepo(identityModel)
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignalUserManager.start called, loaded the user from cache.")
}
// TODO: Update the push sub model with any new state from NotificationsManager
// Setup the executors
// The OSUserExecutor has to run first, before other executors
self.userExecutor = OSUserExecutor(newRecordsState: newRecordsState)
OSOperationRepo.sharedInstance.start()
// Cannot initialize these executors in `init` as they reference the sharedInstance
let propertyExecutor = OSPropertyOperationExecutor(newRecordsState: newRecordsState)
let identityExecutor = OSIdentityOperationExecutor(newRecordsState: newRecordsState)
let subscriptionExecutor = OSSubscriptionOperationExecutor(newRecordsState: newRecordsState)
self.propertyExecutor = propertyExecutor
self.identityExecutor = identityExecutor
self.subscriptionExecutor = subscriptionExecutor
OSOperationRepo.sharedInstance.addExecutor(identityExecutor)
OSOperationRepo.sharedInstance.addExecutor(propertyExecutor)
OSOperationRepo.sharedInstance.addExecutor(subscriptionExecutor)
// Path 2. There is a legacy player to migrate
if let legacyPlayerId = OneSignalUserDefaults.initShared().getSavedString(forKey: OSUD_LEGACY_PLAYER_ID, defaultValue: nil) {
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OneSignalUserManager: creating user linked to legacy subscription \(legacyPlayerId)")
createUserFromLegacyPlayer(legacyPlayerId)
OneSignalUserDefaults.initShared().saveString(forKey: OSUD_PUSH_SUBSCRIPTION_ID, withValue: legacyPlayerId)
OneSignalUserDefaults.initStandard().removeValue(forKey: OSUD_LEGACY_PLAYER_ID)
OneSignalUserDefaults.initShared().removeValue(forKey: OSUD_LEGACY_PLAYER_ID)
} else {
// Path 3. Creates an anonymous user if there isn't one in the cache nor a legacy player
if _user == nil {
// There is no user instance, initialize a "guest user"
_ = createNewUser(externalId: nil, token: nil)
}
}
// Model store listeners subscribe to their models
identityModelStoreListener.start()
propertiesModelStoreListener.start()
subscriptionModelStoreListener.start()
pushSubscriptionModelStoreListener.start()
if hasCachedUser {
_user?.update()
}
hasCalledStart = true
}
}
func addIdentityModelToRepo(_ model: OSIdentityModel) {
self.identityModelRepo.add(model: model)
}
func getIdentityModel(_ modelId: String) -> OSIdentityModel? {
return identityModelRepo.get(modelId: modelId)
}
@objc
public func login(externalId: String, token: String?) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return
}
start()
guard externalId != "" else {
OneSignalLog.onesignalLog(.LL_ERROR, message: "OneSignal.User login called with empty externalId. This is not allowed.")
return
}
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.User login called with externalId: \(externalId)")
// Logging into an identified user from an anonymous user
if let user = _user, user.isAnonymous {
user.identityModel.jwtBearerToken = token
identifyUser(externalId: externalId, currentUser: user)
} else {
// Logging into identified -> anon, identified -> identified, or nil -> identified
_ = createNewUser(externalId: externalId, token: token)
}
}
/**
Converting a 3.x player to a 5.x user. There is a cached legacy player, so we will create the user based on the legacy player ID.
*/
private func createUserFromLegacyPlayer(_ playerId: String) {
// 1. Create the Push Subscription Model
let pushSubscriptionModel = createDefaultPushSubscription(subscriptionId: playerId)
// 2. Set the internal user
let newUser = setNewInternalUser(externalId: nil, pushSubscriptionModel: pushSubscriptionModel)
// 3. Make the request
userExecutor!.fetchIdentityBySubscription(newUser)
// 4. Send any updates to sync the local state
updateLegacyPlayer(newUser)
}
/**
Migrating a legacy player does not result in a Create User call, but certain local data should be sent manually.
*/
private func updateLegacyPlayer(_ user: OSUserInternal) {
if let timezoneId = _user?.propertiesModel.timezoneId {
updatePropertiesDeltas(property: .timezone_id, value: timezoneId)
}
}
private func createNewUser(externalId: String?, token: String?) -> OSUserInternal {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return _mockUser
}
// Check if the existing user is the same one being logged in. If so, return.
if let user = _user {
guard user.identityModel.externalId != externalId || externalId == nil else {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignalUserManager.createNewUser: not creating new user due to logging into the same user.)")
return user
}
}
let pushSubscriptionModel = pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)
// prepareForNewUser may be already called by logout, so we don't want to call it again. Also, there should be no need to call this method if there is no user.
if _user != nil {
prepareForNewUser()
}
let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel)
newUser.identityModel.jwtBearerToken = token
userExecutor!.createUser(newUser)
return newUser
}
/**
The current user in the SDK is an anonymous user, and we are logging in with an externalId.
There are two scenarios addressed:
1. This externalId already exists on another user. We create a new SDK user and fetch that user's information.
2. This externalId doesn't exist on any users. We successfully identify the user, but we still create a new SDK user and fetch to update it.
*/
private func identifyUser(externalId: String, currentUser: OSUserInternal) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return
}
// Get the identity model of the current user
let identityModelToIdentify = currentUser.identityModel
// Immediately drop the old user and set a new user in the SDK
let pushSubscriptionModel = pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)
prepareForNewUser()
let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel)
// Now proceed to identify the previous user
userExecutor!.identifyUser(
externalId: externalId,
identityModelToIdentify: identityModelToIdentify,
identityModelToUpdate: newUser.identityModel
)
}
/**
Returns if the OSIdentityModel passed in belongs to the current user. This method is used in deciding whether or not to hydrate via a server response, for example.
*/
func isCurrentUser(_ identityModel: OSIdentityModel) -> Bool {
return self.identityModelStore.getModel(modelId: identityModel.modelId) != nil
}
func isCurrentUser(_ externalId: String) -> Bool {
guard let userInstance = _user, !externalId.isEmpty else {
OneSignalLog.onesignalLog(.LL_ERROR, message: "isCurrentUser called with empty externalId or no user instance")
return false
}
return userInstance.identityModel.externalId == externalId
}
/**
Clears the existing user's data in preparation for hydration via a fetch user call.
*/
func clearUserData() {
// Identity and property models should still be the same instances, but with data cleared
_user?.identityModel.clearData()
_user?.propertiesModel.clearData()
// Subscription model store should be cleared completely
OneSignalUserManagerImpl.sharedInstance.subscriptionModelStore.clearModelsFromStore()
}
/**
The SDK needs to have a user at all times, so this method will create a new anonymous user. If the current user is already anonymous, calling `logout` results in a no-op.
*/
@objc
public func logout() {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "logout") else {
return
}
guard user.identityModel.externalId != nil else {
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OneSignal.User logout called, but the user is currently anonymous, so not logging out.")
return
}
_logout()
}
public func _logout() {
prepareForNewUser()
_user = nil
createUserIfNil()
}
@objc
public func clearAllModelsFromStores() {
prepareForNewUser()
}
private func createUserIfNil() {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return
}
_ = self.user
}
/**
Notifies observers that the user will be changed. Responses include model stores clearing their User Defaults
and the operation repo flushing the current (soon to be old) user's operations.
*/
private func prepareForNewUser() {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignalUserManagerImpl prepareForNewUser called")
NotificationCenter.default.post(name: Notification.Name(OS_ON_USER_WILL_CHANGE), object: nil)
// This store MUST be cleared, Identity and Properties do not.
subscriptionModelStore.clearModelsFromStore()
}
/**
Creates and sets a blank new SDK user with the provided externalId, if any.
*/
func setNewInternalUser(externalId: String?, pushSubscriptionModel: OSSubscriptionModel?) -> OSUserInternal {
let aliases: [String: String]?
if let externalIdToUse = externalId {
aliases = [OS_EXTERNAL_ID: externalIdToUse]
} else {
aliases = nil
}
let identityModel = OSIdentityModel(aliases: aliases, changeNotifier: OSEventProducer())
self.identityModelStore.add(id: OS_IDENTITY_MODEL_KEY, model: identityModel, hydrating: false)
self.addIdentityModelToRepo(identityModel)
let propertiesModel = OSPropertiesModel(changeNotifier: OSEventProducer())
self.propertiesModelStore.add(id: OS_PROPERTIES_MODEL_KEY, model: propertiesModel, hydrating: false)
// TODO: We will have to save subscription_id and push_token to user defaults when we get them
let pushSubscription = pushSubscriptionModel ?? createDefaultPushSubscription(subscriptionId: nil)
// Add pushSubscription to store if not present
if !pushSubscriptionModelStore.getModels().keys.contains(OS_PUSH_SUBSCRIPTION_MODEL_KEY) {
pushSubscriptionModelStore.add(id: OS_PUSH_SUBSCRIPTION_MODEL_KEY, model: pushSubscription, hydrating: false)
}
let newUser = OSUserInternalImpl(identityModel: identityModel, propertiesModel: propertiesModel, pushSubscriptionModel: pushSubscription)
_user = newUser
return newUser
}
/**
Creates a default Push Subscription Model using the optionally passed in subscriptionId. An scenario where the subscriptionId will be passed in is when we are converting a legacy player's information from 3.x into a Push Subscription Model.
*/
func createDefaultPushSubscription(subscriptionId: String?) -> OSSubscriptionModel {
let sharedUserDefaults = OneSignalUserDefaults.initShared()
let reachable = OSNotificationsManager.currentPermissionState.reachable
let token = sharedUserDefaults.getSavedString(forKey: OSUD_PUSH_TOKEN, defaultValue: nil)
let subscriptionId = subscriptionId ?? sharedUserDefaults.getSavedString(forKey: OSUD_PUSH_SUBSCRIPTION_ID, defaultValue: nil)
return OSSubscriptionModel(type: .push,
address: token,
subscriptionId: subscriptionId,
reachable: reachable,
isDisabled: false,
changeNotifier: OSEventProducer())
}
func createPushSubscriptionRequest() {
// subscriptionExecutor should exist as this should be called after `start()` has been called
if let subscriptionExecutor = self.subscriptionExecutor,
let subscriptionModel = pushSubscriptionModel {
subscriptionExecutor.createPushSubscription(subscriptionModel: subscriptionModel, identityModel: user.identityModel)
} else {
OneSignalLog.onesignalLog(.LL_ERROR, message: "OneSignalUserManagerImpl.createPushSubscriptionRequest cannot be executed due to missing subscriptionExecutor.")
}
}
@objc
public func getTagsInternal() -> [String: String]? {
guard let user = _user else {
return nil
}
return user.propertiesModel.tags
}
@objc
public func setLocation(latitude: Float, longitude: Float) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "setLocation") else {
return
}
guard let user = _user else {
OneSignalLog.onesignalLog(ONE_S_LOG_LEVEL.LL_DEBUG, message: "Failed to set location because User is nil")
return
}
user.setLocation(lat: latitude, long: longitude)
}
@objc
public func sendPurchases(_ purchases: [[String: AnyObject]]) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "sendPurchases") else {
return
}
updatePropertiesDeltas(property: .purchases, value: purchases)
}
private func fireJwtExpired() {
guard let externalId = user.identityModel.externalId, let jwtExpiredHandler = self.jwtExpiredHandler else {
return
}
jwtExpiredHandler(externalId) { [self] (newToken) in
guard user.identityModel.externalId == externalId else {
return
}
user.identityModel.jwtBearerToken = newToken
}
}
}
// MARK: - Sessions
extension OneSignalUserManagerImpl {
@objc
public func startNewSession() {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignalUserManagerImpl starting new session")
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "_startNewSession") else {
return
}
start()
userExecutor!.executePendingRequests()
OSOperationRepo.sharedInstance.paused = false
updatePropertiesDeltas(property: .session_count, value: 1, flush: true)
// Fetch the user's data if there is a onesignal_id
if let onesignalId = onesignalId {
userExecutor!.fetchUser(aliasLabel: OS_ONESIGNAL_ID, aliasId: onesignalId, identityModel: user.identityModel, onNewSession: true)
} else {
// It is possible to init a user from cache who is missing the onesignalId
// This can happen if any createUser or identifyUser requests are cached
OneSignalLog.onesignalLog(.LL_WARN, message: "OneSignalUserManagerImpl.startNewSession() is unable to fetch user with External ID \(externalId ?? "nil") due to null OneSignal ID")
}
}
/// This method accepts properties updates that not driven by model changes.
/// It enqueues an OSDelta to the Operation Repo.
///
/// - Parameter property:Expected inputs are `.session_time"`, `.session_count"`, and `.purchases"`.
/// May be `.timezone_id` or others if the SDK is sending an update for a legacy player.
func updatePropertiesDeltas(property: OSPropertiesSupportedProperty, value: Any, flush: Bool = false) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "updatePropertiesDeltas") else {
return
}
guard let user = _user else {
return
}
// Get the identity and properties model of the current user
let identityModel = user.identityModel
let propertiesModel = user.propertiesModel
let delta = OSDelta(
name: OS_UPDATE_PROPERTIES_DELTA,
identityModelId: identityModel.modelId,
model: propertiesModel,
property: property.rawValue,
value: value
)
OSOperationRepo.sharedInstance.enqueueDelta(delta, flush: flush)
}
/// Time processors forward the session time to this method.
@objc
public func sendSessionTime(_ sessionTime: NSNumber) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "sendSessionTime") else {
return
}
updatePropertiesDeltas(property: .session_time, value: sessionTime.intValue)
}
/**
App has been backgrounded. Run background tasks such to flush the operation repo and hydrating models.
Need to consider app killed vs app backgrounded and handle gracefully.
*/
@objc
public func runBackgroundTasks() {
OSOperationRepo.sharedInstance.addFlushDeltaQueueToDispatchQueue(inBackground: true)
}
}
extension OneSignalUserManagerImpl: OSUser {
public func onJwtExpired(expiredHandler: @escaping OSJwtExpiredHandler) {
jwtExpiredHandler = expiredHandler
}
public var User: OSUser {
start()
return self
}
public var pushSubscription: OSPushSubscription {
start()
return pushSubscriptionImpl
}
public var externalId: String? {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "externalId") else {
return nil
}
return _user?.identityModel.externalId
}
public var onesignalId: String? {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "onesignalId") else {
return nil
}
return _user?.identityModel.onesignalId
}
public func addObserver(_ observer: OSUserStateObserver) {
// This is a method in the User namespace that doesn't require privacy consent first
self.userStateChangesObserver.addObserver(observer)
}
public func removeObserver(_ observer: OSUserStateObserver) {
self.userStateChangesObserver.removeObserver(observer)
}
public func addAlias(label: String, id: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "addAlias") else {
return
}
user.addAliases([label: id])
}
public func addAliases(_ aliases: [String: String]) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "addAliases") else {
return
}
user.addAliases(aliases)
}
public func removeAlias(_ label: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "removeAlias") else {
return
}
user.removeAliases([label])
}
public func removeAliases(_ labels: [String]) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "removeAliases") else {
return
}
user.removeAliases(labels)
}
public func addTag(key: String, value: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "addTag") else {
return
}
user.addTags([key: value])
}
public func addTags(_ tags: [String: String]) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "addTags") else {
return
}
user.addTags(tags)
}
public func removeTag(_ tag: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "removeTag") else {
return
}
user.removeTags([tag])
}
public func removeTags(_ tags: [String]) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "removeTags") else {
return
}
user.removeTags(tags)
}
public func getTags() -> [String: String] {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "getTags") else {
return [:]
}
return user.propertiesModel.tags
}
public func addEmail(_ email: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "addEmail") else {
return
}
// Check if is valid email?
// Check if this email already exists on this User?
createUserIfNil()
let model = OSSubscriptionModel(
type: .email,
address: email,
subscriptionId: nil,
reachable: true,
isDisabled: false,
changeNotifier: OSEventProducer()
)
self.subscriptionModelStore.add(id: email, model: model, hydrating: false)
}
/**
If this email doesn't already exist on the user, it cannot be removed.
This will be a no-op and no request will be made.
Error handling needs to be implemented in the future.
*/
public func removeEmail(_ email: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "removeEmail") else {
return
}
// Check if is valid email?
createUserIfNil()
self.subscriptionModelStore.remove(email)
}
public func addSms(_ number: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "addSmsNumber") else {
return
}
// Check if is valid SMS?
// Check if this SMS already exists on this User?
createUserIfNil()
let model = OSSubscriptionModel(
type: .sms,
address: number,
subscriptionId: nil,
reachable: true,
isDisabled: false,
changeNotifier: OSEventProducer()
)
self.subscriptionModelStore.add(id: number, model: model, hydrating: false)
}
/**
If this email doesn't already exist on the user, it cannot be removed.
This will be a no-op and no request will be made.
Error handling needs to be implemented in the future.
*/
public func removeSms(_ number: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "removeSmsNumber") else {
return
}
// Check if is valid SMS?
createUserIfNil()
self.subscriptionModelStore.remove(number)
}
public func setLanguage(_ language: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "setLanguage") else {
return
}
if language == "" {
OneSignalLog.onesignalLog(.LL_ERROR, message: "OneSignal.User.setLanguage cannot be called with an empty language code.")
return
}
user.setLanguage(language)
}
}
extension OneSignalUserManagerImpl {
@objc
public class OSPushSubscriptionImpl: NSObject, OSPushSubscription {
let pushSubscriptionModelStore: OSModelStore<OSSubscriptionModel>
private var _pushSubscriptionStateChangesObserver: OSObservable<OSPushSubscriptionObserver, OSPushSubscriptionChangedState>?
var pushSubscriptionStateChangesObserver: OSObservable<OSPushSubscriptionObserver, OSPushSubscriptionChangedState> {
if let observer = _pushSubscriptionStateChangesObserver {
return observer
}
let pushSubscriptionStateChangesObserver = OSObservable<OSPushSubscriptionObserver, OSPushSubscriptionChangedState>(change: #selector(OSPushSubscriptionObserver.onPushSubscriptionDidChange(state:)))
_pushSubscriptionStateChangesObserver = pushSubscriptionStateChangesObserver
return pushSubscriptionStateChangesObserver
}
init(pushSubscriptionModelStore: OSModelStore<OSSubscriptionModel>) {
self.pushSubscriptionModelStore = pushSubscriptionModelStore
}
public func addObserver(_ observer: OSPushSubscriptionObserver) {
// This is a method in the User namespace that doesn't require privacy consent first
self.pushSubscriptionStateChangesObserver.addObserver(observer)
}
public func removeObserver(_ observer: OSPushSubscriptionObserver) {
self.pushSubscriptionStateChangesObserver.removeObserver(observer)
}
public var id: String? {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "pushSubscription.id") else {
return nil
}
return pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)?.subscriptionId
}
public var token: String? {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "pushSubscription.token") else {
return nil
}
return pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)?.address
}
public var optedIn: Bool {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "pushSubscription.optedIn") else {
return false
}
return pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)?.optedIn ?? false
}
/**
Enable the push subscription, and prompts if needed. `optedIn` can still be `false` after `optIn()` is called if permission is not granted.
*/
public func optIn() {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "pushSubscription.optIn") else {
return
}
pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)?._isDisabled = false
OSNotificationsManager.requestPermission(nil, fallbackToSettings: true)
}
public func optOut() {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: "pushSubscription.optOut") else {
return
}
pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY)?._isDisabled = true
}
}
}
extension OneSignalUserManagerImpl: OneSignalNotificationsDelegate {
// While we await app_id and privacy consent, these methods are a no-op
// Once the UserManager is started in `init`, it calls these to set the state of the pushSubscriptionModel
public func setNotificationTypes(_ notificationTypes: Int32) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return
}
user.pushSubscriptionModel.notificationTypes = Int(notificationTypes)
}
public func setPushToken(_ pushToken: String) {
guard !OneSignalConfigManager.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
return
}
user.pushSubscriptionModel.address = pushToken
}
}
extension OneSignalUserManagerImpl: OSLoggable {
@objc public func logSelf() {
// TODO: You fill in
}
}