-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathOSSubscriptionModel.swift
More file actions
494 lines (426 loc) · 19 KB
/
Copy pathOSSubscriptionModel.swift
File metadata and controls
494 lines (426 loc) · 19 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
/*
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 Foundation
import OneSignalCore
import OneSignalOSCore
import OneSignalNotifications
// MARK: - Push Subscription Specific
@objc public protocol OSPushSubscriptionObserver { // TODO: weak reference?
@objc func onPushSubscriptionDidChange(state: OSPushSubscriptionChangedState)
}
@objc
public class OSPushSubscriptionState: NSObject {
@objc public let id: String?
@objc public let token: String?
@objc public let optedIn: Bool
@objc public override var description: String {
return "<OSPushSubscriptionState: id: \(id ?? "nil"), token: \(token ?? "nil"), optedIn: \(optedIn)>"
}
init(id: String?, token: String?, optedIn: Bool) {
self.id = id
self.token = token
self.optedIn = optedIn
}
@objc public func jsonRepresentation() -> NSDictionary {
let id = self.id ?? ""
let token = self.token ?? ""
return [
"id": id,
"token": token,
"optedIn": optedIn
]
}
func equals(_ state: OSPushSubscriptionState) -> Bool {
return self.id == state.id && self.token == state.token && self.optedIn == state.optedIn
}
}
@objc
public class OSPushSubscriptionChangedState: NSObject {
@objc public let current: OSPushSubscriptionState
@objc public let previous: OSPushSubscriptionState
@objc public override var description: String {
return "<OSPushSubscriptionChangedState:\nprevious: \(self.previous),\ncurrent: \(self.current)\n>"
}
init(current: OSPushSubscriptionState, previous: OSPushSubscriptionState) {
self.current = current
self.previous = previous
}
@objc public func jsonRepresentation() -> NSDictionary {
return ["previous": previous.jsonRepresentation(), "current": current.jsonRepresentation()]
}
}
// MARK: - Subscription Model
enum OSSubscriptionType: String {
case push = "iOSPush"
case email = "Email"
case sms = "SMS"
}
/**
Internal subscription model.
*/
class OSSubscriptionModel: OSModel {
var type: OSSubscriptionType
var address: String? { // This is token on push subs so must remain Optional
didSet {
guard address != oldValue else {
return
}
self.set(property: "address", newValue: address)
guard self.type == .push else {
return
}
updateNotificationTypes()
firePushSubscriptionChanged(.address(oldValue))
}
}
/**
Typically, the subscription ID is set via server response, so don't trigger a server update call when it changes.
It can also be set to null by the SDK when the user or subscription is detected as missing.
Setting the subscription ID to null will serve as a "reset" and will later hydrate a value from a user create rquest.
*/
var subscriptionId: String? {
didSet {
guard subscriptionId != oldValue else {
return
}
// If the ID has changed, don't trigger a server call, since it can be set to null
self.set(property: "subscriptionId", newValue: subscriptionId, preventServerUpdate: true)
guard self.type == .push else {
return
}
// Cache the subscriptionId as it persists across users on the device??
OneSignalUserDefaults.initShared().saveString(forKey: OSUD_PUSH_SUBSCRIPTION_ID, withValue: subscriptionId)
firePushSubscriptionChanged(.subscriptionId(oldValue))
}
}
// Internal property to send to server, not meant for outside access
var enabled: Bool { // Does not consider subscription_id in the calculation
get {
return calculateIsEnabled(address: address, reachable: _reachable, isDisabled: _isDisabled)
}
}
var optedIn: Bool {
// optedIn = permission + userPreference
get {
return calculateIsOptedIn(reachable: _reachable, isDisabled: _isDisabled)
}
}
// Push Subscription Only
// Initialize to be -1, so not to deal with unwrapping every time, and simplifies caching
var notificationTypes = -1 {
didSet {
guard self.type == .push && notificationTypes != oldValue else {
return
}
// If _isDisabled is set, this supersedes as the value to send to server.
if _isDisabled && notificationTypes != -2 {
notificationTypes = -2
return
}
_reachable = notificationTypes > 0
self.set(property: "notificationTypes", newValue: notificationTypes)
}
}
// swiftlint:disable identifier_name
/**
This is set by the permission state changing.
Defaults to true for email & SMS, defaults to false for push.
Note that this property reflects the `reachable` property of a permission state. As provisional permission is considered to be `optedIn` and `enabled`.
*/
var _reachable: Bool {
didSet {
guard self.type == .push && _reachable != oldValue else {
return
}
firePushSubscriptionChanged(.reachable(oldValue))
}
}
// Set by the app developer when they call User.pushSubscription.optOut()
var _isDisabled: Bool { // Default to false for all subscriptions
didSet {
guard self.type == .push && _isDisabled != oldValue else {
return
}
firePushSubscriptionChanged(.isDisabled(oldValue))
notificationTypes = -2
}
}
// Properties for push subscription
var testType: Int? {
didSet {
guard testType != oldValue else {
return
}
self.set(property: "testType", newValue: testType)
}
}
var deviceOs = UIDevice.current.systemVersion {
didSet {
guard deviceOs != oldValue else {
return
}
self.set(property: "deviceOs", newValue: deviceOs)
}
}
var sdk = OneSignalVersion.numeric() {
didSet {
guard sdk != oldValue else {
return
}
self.set(property: "sdk", newValue: sdk)
}
}
var deviceModel: String? = OSDeviceUtils.getDeviceVariant() {
didSet {
guard deviceModel != oldValue else {
return
}
self.set(property: "deviceModel", newValue: deviceModel)
}
}
var appVersion: String? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
didSet {
guard appVersion != oldValue else {
return
}
self.set(property: "appVersion", newValue: appVersion)
}
}
var netType: Int? = OSNetworkingUtils.getNetType() as? Int {
didSet {
guard netType != oldValue else {
return
}
self.set(property: "netType", newValue: netType)
}
}
// When a Subscription is initialized, it may not have a subscriptionId until a request to the backend is made.
init(type: OSSubscriptionType,
address: String?,
subscriptionId: String?,
reachable: Bool,
isDisabled: Bool,
changeNotifier: OSEventProducer<OSModelChangedHandler>) {
self.type = type
self.address = address
self.subscriptionId = subscriptionId
_reachable = reachable
_isDisabled = isDisabled
// Set test_type if subscription model is PUSH, and update notificationTypes
if type == .push {
let releaseMode: OSUIApplicationReleaseMode = OneSignalMobileProvision.releaseMode()
#if targetEnvironment(simulator)
if releaseMode == OSUIApplicationReleaseMode.UIApplicationReleaseUnknown {
self.testType = OSUIApplicationReleaseMode.UIApplicationReleaseDev.rawValue
}
#endif
// Workaround to unsure how to extract the Int value in 1 step...
if releaseMode == .UIApplicationReleaseDev {
self.testType = OSUIApplicationReleaseMode.UIApplicationReleaseDev.rawValue
}
if releaseMode == .UIApplicationReleaseAdHoc {
self.testType = OSUIApplicationReleaseMode.UIApplicationReleaseAdHoc.rawValue
}
if releaseMode == .UIApplicationReleaseWildcard {
self.testType = OSUIApplicationReleaseMode.UIApplicationReleaseWildcard.rawValue
}
notificationTypes = Int(OSNotificationsManager.getNotificationTypes(_isDisabled))
}
super.init(changeNotifier: changeNotifier)
}
override func encode(with coder: NSCoder) {
super.encode(with: coder)
coder.encode(type.rawValue, forKey: "type") // Encodes as String
coder.encode(address, forKey: "address")
coder.encode(subscriptionId, forKey: "subscriptionId")
coder.encode(_reachable, forKey: "_reachable")
coder.encode(_isDisabled, forKey: "_isDisabled")
coder.encode(notificationTypes, forKey: "notificationTypes")
coder.encode(testType, forKey: "testType")
coder.encode(deviceOs, forKey: "deviceOs")
coder.encode(sdk, forKey: "sdk")
coder.encode(deviceModel, forKey: "deviceModel")
coder.encode(appVersion, forKey: "appVersion")
coder.encode(netType, forKey: "netType")
}
required init?(coder: NSCoder) {
guard
let rawType = coder.decodeObject(forKey: "type") as? String,
let type = OSSubscriptionType(rawValue: rawType)
else {
// Log error
return nil
}
self.type = type
self.address = coder.decodeObject(forKey: "address") as? String
self.subscriptionId = coder.decodeObject(forKey: "subscriptionId") as? String
self._reachable = coder.decodeBool(forKey: "_reachable")
self._isDisabled = coder.decodeBool(forKey: "_isDisabled")
self.notificationTypes = coder.decodeInteger(forKey: "notificationTypes")
self.testType = coder.decodeObject(forKey: "testType") as? Int
self.deviceOs = coder.decodeObject(forKey: "deviceOs") as? String ?? UIDevice.current.systemVersion
self.sdk = coder.decodeObject(forKey: "sdk") as? String ?? OneSignalVersion.numeric()
self.deviceModel = coder.decodeObject(forKey: "deviceModel") as? String
self.appVersion = coder.decodeObject(forKey: "appVersion") as? String
self.netType = coder.decodeObject(forKey: "netType") as? Int
super.init(coder: coder)
}
public override func hydrateModel(_ response: [String: Any]) {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSSubscriptionModel hydrateModel()")
for property in response {
switch property.key {
case "id":
self.subscriptionId = property.value as? String
case "type":
if let type = OSSubscriptionType(rawValue: property.value as? String ?? "") {
self.type = type
}
// case "token":
// TODO: For now, don't hydrate token
// self.address = property.value as? String
case "enabled":
if let enabled = property.value as? Bool {
if self.enabled != enabled { // TODO: Is this right?
_isDisabled = !enabled
}
}
case "notification_types":
if let notificationTypes = property.value as? Int {
self.notificationTypes = notificationTypes
}
default:
OneSignalLog.onesignalLog(.LL_DEBUG, message: "Unused property on subscription model")
}
}
}
// Using snake_case so we can use this in request bodies
public func jsonRepresentation() -> [String: Any] {
var json: [String: Any] = [:]
json["id"] = self.subscriptionId
json["type"] = self.type.rawValue
json["token"] = self.address
json["enabled"] = self.enabled
json["test_type"] = self.testType
json["device_os"] = self.deviceOs
json["sdk"] = self.sdk
json["device_model"] = self.deviceModel
json["app_version"] = self.appVersion
json["net_type"] = self.netType
// notificationTypes defaults to -1 instead of nil, don't send if it's -1
if self.notificationTypes != -1 {
json["notification_types"] = self.notificationTypes
}
return json
}
}
// Push Subscription related
extension OSSubscriptionModel {
// Only used for the push subscription model
var currentPushSubscriptionState: OSPushSubscriptionState {
return OSPushSubscriptionState(id: self.subscriptionId,
token: self.address,
optedIn: self.optedIn
)
}
// Calculates if the device is opted in to push notification.
// Must have permission and not be opted out.
func calculateIsOptedIn(reachable: Bool, isDisabled: Bool) -> Bool {
return reachable && !isDisabled
}
// Calculates if push notifications are enabled on the device.
// Does not consider the existence of the subscription_id, as we send this in the request to create a push subscription.
func calculateIsEnabled(address: String?, reachable: Bool, isDisabled: Bool) -> Bool {
return address != nil && reachable && !isDisabled
}
func updateNotificationTypes() {
notificationTypes = Int(OSNotificationsManager.getNotificationTypes(_isDisabled))
}
func updateTestType() {
let releaseMode: OSUIApplicationReleaseMode = OneSignalMobileProvision.releaseMode()
// Workaround to unsure how to extract the Int value in 1 step...
if releaseMode == .UIApplicationReleaseDev {
self.testType = OSUIApplicationReleaseMode.UIApplicationReleaseDev.rawValue
}
if releaseMode == .UIApplicationReleaseAdHoc {
self.testType = OSUIApplicationReleaseMode.UIApplicationReleaseAdHoc.rawValue
}
if releaseMode == .UIApplicationReleaseWildcard {
self.testType = OSUIApplicationReleaseMode.UIApplicationReleaseWildcard.rawValue
}
}
func update() {
updateTestType()
deviceOs = UIDevice.current.systemVersion
sdk = OneSignalVersion.numeric()
deviceModel = OSDeviceUtils.getDeviceVariant()
appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
netType = OSNetworkingUtils.getNetType() as? Int
// sdkType ??
// isRooted ??
if type == .push && !(subscriptionId ?? "").isEmpty {
OneSignalUserDefaults.initShared().saveString(forKey: OSUD_PUSH_SUBSCRIPTION_ID, withValue: subscriptionId)
}
}
enum OSPushPropertyChanged {
case subscriptionId(String?)
case reachable(Bool)
case isDisabled(Bool)
case address(String?)
}
func firePushSubscriptionChanged(_ changedProperty: OSPushPropertyChanged) {
var prevIsOptedIn = true
var prevIsEnabled = true
var prevSubscriptionState = OSPushSubscriptionState(id: "", token: "", optedIn: true)
switch changedProperty {
case .subscriptionId(let oldValue):
prevIsEnabled = calculateIsEnabled(address: address, reachable: _reachable, isDisabled: _isDisabled)
prevIsOptedIn = calculateIsOptedIn(reachable: _reachable, isDisabled: _isDisabled)
prevSubscriptionState = OSPushSubscriptionState(id: oldValue, token: address, optedIn: prevIsOptedIn)
case .reachable(let oldValue):
prevIsEnabled = calculateIsEnabled(address: address, reachable: oldValue, isDisabled: _isDisabled)
prevIsOptedIn = calculateIsOptedIn(reachable: oldValue, isDisabled: _isDisabled)
prevSubscriptionState = OSPushSubscriptionState(id: subscriptionId, token: address, optedIn: prevIsOptedIn)
case .isDisabled(let oldValue):
prevIsEnabled = calculateIsEnabled(address: address, reachable: _reachable, isDisabled: oldValue)
prevIsOptedIn = calculateIsOptedIn(reachable: _reachable, isDisabled: oldValue)
prevSubscriptionState = OSPushSubscriptionState(id: subscriptionId, token: address, optedIn: prevIsOptedIn)
case .address(let oldValue):
prevIsEnabled = calculateIsEnabled(address: oldValue, reachable: _reachable, isDisabled: _isDisabled)
prevIsOptedIn = calculateIsOptedIn(reachable: _reachable, isDisabled: _isDisabled)
prevSubscriptionState = OSPushSubscriptionState(id: subscriptionId, token: oldValue, optedIn: prevIsOptedIn)
}
let newIsOptedIn = calculateIsOptedIn(reachable: _reachable, isDisabled: _isDisabled)
let newIsEnabled = calculateIsEnabled(address: address, reachable: _reachable, isDisabled: _isDisabled)
if prevIsEnabled != newIsEnabled {
self.set(property: "enabled", newValue: newIsEnabled)
}
let newSubscriptionState = OSPushSubscriptionState(id: subscriptionId, token: address, optedIn: newIsOptedIn)
// TODO: Make this method less hacky, this is a final check before firing push observer
guard !prevSubscriptionState.equals(newSubscriptionState) else {
return
}
let stateChanges = OSPushSubscriptionChangedState(current: newSubscriptionState, previous: prevSubscriptionState)
// TODO: Don't fire observer until server is udated
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "firePushSubscriptionChanged from \(prevSubscriptionState.jsonRepresentation()) to \(newSubscriptionState.jsonRepresentation())")
OneSignalUserManagerImpl.sharedInstance.pushSubscriptionImpl.pushSubscriptionStateChangesObserver.notifyChange(stateChanges)
}
}