-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathOSModelStore.swift
More file actions
203 lines (179 loc) · 7.91 KB
/
Copy pathOSModelStore.swift
File metadata and controls
203 lines (179 loc) · 7.91 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
/*
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
open class OSModelStore<TModel: OSModel>: NSObject {
let storeKey: String
let changeSubscription: OSEventProducer<OSModelStoreChangedHandler>
var models: [String: TModel]
let lock = NSLock()
public init(changeSubscription: OSEventProducer<OSModelStoreChangedHandler>, storeKey: String) {
self.storeKey = storeKey
self.changeSubscription = changeSubscription
// read models from cache, if any
if let models = OneSignalUserDefaults.initShared().getSavedCodeableData(forKey: self.storeKey, defaultValue: [:]) as? [String: TModel] {
self.models = models
} else {
// log error
self.models = [:]
}
super.init()
// listen for changes to the models
for model in self.models.values {
model.changeNotifier.subscribe(self)
}
}
public func registerAsUserObserver() -> OSModelStore {
// This method was taken out of the initializer as the push subscription model store should not be clearing its user defaults
NotificationCenter.default.addObserver(self, selector: #selector(self.removeModelsFromUserDefaults),
name: Notification.Name(OS_ON_USER_WILL_CHANGE), object: nil)
return self
}
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name(OS_ON_USER_WILL_CHANGE), object: nil)
}
/**
Uses the ID that is used as the key to store models in the store's models dictionary.
Examples: "person@example.com" for a subscription model or `OS_IDENTITY_MODEL_KEY` for an identity model.
*/
public func getModel(key: String) -> TModel? {
lock.withLock {
return self.models[key]
}
}
/**
Uses the `modelId` to get the corresponding model in the store's models dictionary.
*/
public func getModel(modelId: String) -> TModel? {
lock.withLock {
for model in models.values {
if model.modelId == modelId {
return model
}
}
return nil
}
}
public func getModels() -> [String: TModel] {
lock.withLock {
return self.models
}
}
/// Re-read this store's backing UserDefaults entry and hydrate `models` from disk.
/// No-op when `models` is already non-empty — we never clobber in-memory state.
///
/// Motivation: model stores load their `models` dict once in `init()` from shared UserDefaults.
/// If `init()` runs while protected data is unavailable (iOS app prewarm, NSE before first
/// unlock), that read returns nil and the dict stays empty for the lifetime of the singleton —
/// it is never re-read. After protected data becomes available, callers can call `refresh()`
/// so the store reflects what's actually on disk. Does not fire listener events.
public func refresh() {
lock.withLock {
guard models.isEmpty else { return }
guard let stored = OneSignalUserDefaults.initShared().getSavedCodeableData(forKey: self.storeKey, defaultValue: [:]) as? [String: TModel],
!stored.isEmpty else {
return
}
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSModelStore[\(self.storeKey)] refresh hydrated \(stored.count) model(s) from UserDefaults")
self.models = stored
for model in stored.values {
model.changeNotifier.subscribe(self)
}
}
}
public func add(id: String, model: TModel, hydrating: Bool) {
// TODO: Check if we are adding the same model? Do we replace?
// For example, calling addEmail multiple times with the same email
// Check API endpoint for behavior
lock.withLock {
models[id] = model
// persist the models (including new model) to storage
OneSignalUserDefaults.initShared().saveCodeableData(forKey: self.storeKey, withValue: self.models)
// listen for changes to this model
model.changeNotifier.subscribe(self)
}
guard !hydrating else {
return
}
self.changeSubscription.fire { modelStoreListener in
modelStoreListener.onAdded(model)
}
}
/**
Nothing will happen if this model does not exist in the store.
This can happen if remove email or SMS is called and it doesn't exist in the store.
*/
public func remove(_ id: String) {
var model: TModel?
lock.withLock {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSModelStore remove() called with model \(id)")
if let foundModel = models[id] {
model = foundModel
models.removeValue(forKey: id)
// persist the models (with removed model) to storage
OneSignalUserDefaults.initShared().saveCodeableData(forKey: self.storeKey, withValue: self.models)
} else {
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSModelStore cannot remove \(id) because it doesn't exist in the store.")
return
}
}
guard let model = model else {
return
}
// no longer listen for changes to this model
model.changeNotifier.unsubscribe(self)
self.changeSubscription.fire { modelStoreListener in
modelStoreListener.onRemoved(model)
}
}
/**
We remove this store's models from UserDefaults but not from the store itself.
We may still need references to model(s) in this store!
*/
@objc func removeModelsFromUserDefaults() {
// Clear the UserDefaults models cache when OS_ON_USER_WILL_CHANGEclearModelsFromStore() called
OneSignalUserDefaults.initShared().removeValue(forKey: self.storeKey)
}
/**
We clear this store's models but not from the UserDefaults cache.
When the User changes, the Subscription Model Store must remove all models.
In contrast, it is not necessary for the Identity or Properties Model Stores to do so.
*/
public func clearModelsFromStore() {
lock.withLock {
self.models = [:]
}
}
}
extension OSModelStore: OSModelChangedHandler {
public func onModelUpdated(args: OSModelChangedArgs, hydrating: Bool) {
// persist the changed models to storage
lock.withLock {
OneSignalUserDefaults.initShared().saveCodeableData(forKey: self.storeKey, withValue: self.models)
}
guard !hydrating else {
return
}
self.changeSubscription.fire { modelStoreListener in
modelStoreListener.onUpdated(args)
}
}
}