-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSPConsentManager.swift
372 lines (343 loc) · 13.3 KB
/
SPConsentManager.swift
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
//
// SPConsentManager.swift
// cmp-app-test-app
//
// Created by Andre Herculano on 12/16/19.
// Copyright © 2019 Sourcepoint. All rights reserved.
//
import Foundation
@objcMembers public class SPConsentManager: NSObject, SPSDK {
static public let VERSION = "6.0.2"
static public var shouldCallErrorMetrics = true
weak var delegate: SPDelegate?
let accountId: Int
let propertyName: SPPropertyName
let campaigns: SPCampaigns
var authId: String?
let spClient: SourcePointProtocol
let deviceManager: SPDeviceManager
var cleanUserDataOnError = true
var storage: SPLocalStorage
public var userData: SPUserData { storage.userData }
var messageControllersStack: [SPMessageViewController] = []
var idfaStatus: SPIDFAStatus { SPIDFAStatus.current() }
static let DefaultTimeout = TimeInterval(30)
var ccpaUUID: String { storage.localState["ccpa"]?.dictionaryValue?["uuid"] as? String ?? "" }
var gdprUUID: String { storage.localState["gdpr"]?.dictionaryValue?["uuid"] as? String ?? "" }
var propertyId: Int?
public static func clearAllData() {
SPUserDefaults(storage: UserDefaults.standard).clear()
}
/// The timeout interval in seconds for the message being displayed
public var messageTimeoutInSeconds = SPConsentManager.DefaultTimeout {
didSet {
spClient.setRequestTimeout(self.messageTimeoutInSeconds)
}
}
public convenience init(accountId: Int, propertyName: SPPropertyName, campaigns: SPCampaigns, delegate: SPDelegate?) {
self.init(
accountId: accountId,
propertyName: propertyName,
campaigns: campaigns,
delegate: delegate,
spClient: SourcePointClient(accountId: accountId, propertyName: propertyName, timeout: SPConsentManager.DefaultTimeout),
storage: SPUserDefaults(storage: UserDefaults.standard)
)
}
init(
accountId: Int,
propertyName: SPPropertyName,
campaigns: SPCampaigns,
delegate: SPDelegate?,
spClient: SourcePointProtocol,
storage: SPLocalStorage,
deviceManager: SPDeviceManager = SPDevice()
) {
self.accountId = accountId
self.propertyName = propertyName
self.campaigns = campaigns
self.delegate = delegate
self.spClient = spClient
self.storage = storage
self.deviceManager = deviceManager
}
/// Instructs the privacy manager to be displayed with this tab.
/// By default the SDK will use the defult tab of PM
public var privacyManagerTab = SPPrivacyManagerTab.Default
/// Instructs the message to be displayed in this language. If the translation is missing, the fallback will be English.
/// By default the SDK will use the locale defined by the WebView
public var messageLanguage = SPMessageLanguage.BrowserDefault
func renderNextMessageIfAny () {
DispatchQueue.main.async { [weak self] in
if let ui = self?.messageControllersStack.popLast() {
ui.loadMessage()
}
}
}
func messageToViewController (_ url: URL, _ messageId: Int, _ message: Message?, _ type: SPCampaignType) -> SPMessageViewController? {
switch message {
case .native:
/// TODO: Initialise the Native Message object
/// Call a delegate Method to get the Message controller
/// Pass the native message object to it
return nil
#if os(tvOS)
case .nativePM(let content): return SPNativePrivacyManagerViewController(
messageId: messageId,
contents: content,
campaignType: type,
delegate: self
)
#endif
#if os(iOS)
case .web(let content): return GenericWebMessageViewController(
url: url,
messageId: messageId,
contents: content,
campaignType: type,
timeout: messageTimeoutInSeconds,
delegate: self
)
#endif
default:
return nil
}
}
func storeData(localState: SPJson, userData: SPUserData) {
storage.localState = localState
storage.userData = userData
if let tcData = userData.gdpr?.consents?.tcfData {
storage.tcfData = tcData.dictionaryValue
}
if let uspString = userData.ccpa?.consents?.uspstring {
storage.usPrivacyString = uspString
}
}
public func loadMessage(forAuthId authId: String? = nil) {
self.authId = authId
spClient.getMessages(
campaigns: campaigns,
authId: authId,
localState: storage.localState,
idfaStaus: idfaStatus
) { [weak self] result in
switch result {
case .success(let messagesResponse):
self?.storeData(
localState: messagesResponse.localState,
userData: SPUserData(from: messagesResponse)
)
self?.propertyId = messagesResponse.propertyId
self?.messageControllersStack = messagesResponse.campaigns
.filter { $0.message != nil }
.filter { $0.messageMetaData != nil }
.filter { $0.url != nil }
.compactMap { self?.messageToViewController(
$0.url!,
$0.messageMetaData!.messageId,
$0.message,
$0.type
)}
.reversed()
if self?.messageControllersStack.isEmpty ?? true {
self?.delegate?.onConsentReady?(userData: self?.storage.userData ?? SPUserData())
} else {
self?.renderNextMessageIfAny()
}
case .failure(let error):
self?.onError(error)
}
}
}
func report(action: SPAction) {
switch action.campaignType {
case .ccpa:
spClient.postCCPAAction(authId: authId, action: action, localState: storage.localState, idfaStatus: idfaStatus) { [weak self] result in
switch result {
case .success(let consentsResponse):
let userData = SPUserData(
gdpr: self?.storage.userData.gdpr,
ccpa: SPConsent(consents: consentsResponse.userConsent, applies: true)
)
self?.storeData(
localState: consentsResponse.localState,
userData: userData
)
self?.delegate?.onConsentReady?(userData: userData)
case .failure(let error):
self?.onError(error)
}
}
case .gdpr:
spClient.postGDPRAction(authId: authId, action: action, localState: storage.localState, idfaStatus: idfaStatus) { [weak self] result in
switch result {
case .success(let consentsResponse):
let userData = SPUserData(
gdpr: SPConsent(consents: consentsResponse.userConsent, applies: true),
ccpa: self?.storage.userData.ccpa
)
self?.storeData(
localState: consentsResponse.localState,
userData: userData
)
self?.delegate?.onConsentReady?(userData: userData)
case .failure(let error):
self?.onError(error)
}
}
default: break
}
}
public func loadGDPRPrivacyManager(withId id: String, tab: SPPrivacyManagerTab = .Default) {
#if os(iOS)
let pmUrl = URL(string: "https://cdn.privacy-mgmt.com/privacy-manager/index.html?&message_id=\(id)&pmTab=\(tab.rawValue)&consentUUID=\(gdprUUID)&idfaStatus=\(idfaStatus)")!
loadWebPrivacyManager(.gdpr, pmUrl)
#elseif os(tvOS)
spClient.getNativePrivacyManager(withId: id) { result in
switch result {
case .success(let pmContent):
self.loaded(SPNativePrivacyManagerViewController(
messageId: nil, // TODO: make sure PM comes with message id
contents: pmContent,
campaignType: .gdpr,
delegate: self
))
case .failure(let error):
self.onError(error)
}
}
#endif
}
public func loadCCPAPrivacyManager(withId id: String, tab: SPPrivacyManagerTab = .Default) {
#if os(iOS)
let pmUrl = URL(string: "https://ccpa-inapp-pm.sp-prod.net/ccpa_pm/index.html?&message_id=\(id)&pmTab=\(tab.rawValue)&ccpaUUID=\(ccpaUUID)&idfaStatus=\(idfaStatus)")!
loadWebPrivacyManager(.ccpa, pmUrl)
#elseif os(tvOS)
/// TODO: load NativePM
#endif
}
public func gdprApplies() -> Bool {
storage.userData.gdpr?.applies ?? false
}
public func ccpaApplies() -> Bool {
storage.userData.ccpa?.applies ?? false
}
public func customConsentGDPR(vendors: [String], categories: [String], legIntCategories: [String], handler: @escaping (SPGDPRConsent) -> Void) {
guard let propertyId = propertyId, !gdprUUID.isEmpty else {
onError(PostingConsentWithoutConsentUUID())
return
}
spClient.customConsentGDPR(
toConsentUUID: gdprUUID,
vendors: vendors,
categories: categories,
legIntCategories: legIntCategories,
propertyId: propertyId
) { [weak self] result in
switch result {
case .success(let consents):
let newGDPRConsents = SPGDPRConsent(
vendorGrants: consents.grants,
euconsent: self?.storage.userData.gdpr?.consents?.euconsent ?? "",
tcfData: self?.storage.userData.gdpr?.consents?.tcfData ?? SPJson()
)
self?.storage.userData = SPUserData(
gdpr: SPConsent<SPGDPRConsent>(consents: newGDPRConsents, applies: self?.storage.userData.gdpr?.applies ?? false),
ccpa: self?.storage.userData.ccpa
)
handler(newGDPRConsents)
case .failure(let error):
self?.onError(error)
}
}
}
#if os(iOS)
func loadWebPrivacyManager(_ campaignType: SPCampaignType, _ pmURL: URL) {
let messageId = Int(
URLComponents(url: pmURL, resolvingAgainstBaseURL: false)?
.queryItems?
.first { $0.name == "message_id"}?
.value ?? ""
)
GenericWebMessageViewController(
url: pmURL,
messageId: messageId,
contents: SPJson(),
campaignType: campaignType,
timeout: messageTimeoutInSeconds,
delegate: self
).loadPrivacyManager(url: pmURL)
}
#endif
public func onError(_ error: SPError) {
spClient.errorMetrics(
error,
propertyId: propertyId,
sdkVersion: SPConsentManager.VERSION,
OSVersion: deviceManager.osVersion(),
deviceFamily: deviceManager.osVersion(),
campaignType: error.campaignType
)
if cleanUserDataOnError {
SPConsentManager.clearAllData()
}
delegate?.onError?(error: error)
}
}
extension SPConsentManager: SPMessageUIDelegate {
func loaded(_ controller: SPMessageViewController) {
DispatchQueue.main.async {
self.delegate?.onSPUIReady(controller)
}
}
func finished(_ vcFinished: SPMessageViewController) {
DispatchQueue.main.async {
self.delegate?.onSPUIFinished(vcFinished)
}
}
func finishAndNextIfAny(_ vcFinished: SPMessageViewController) {
finished(vcFinished)
renderNextMessageIfAny()
}
func reportIdfaStatus(status: SPIDFAStatus, messageId: Int?) {
var uuid = ""
var uuidType: SPCampaignType?
if !gdprUUID.isEmpty {
uuid = gdprUUID
uuidType = .gdpr
} else if !ccpaUUID.isEmpty {
uuid = ccpaUUID
uuidType = .ccpa
}
spClient.reportIdfaStatus(
propertyId: propertyId,
uuid: uuid,
uuidType: uuidType,
messageId: messageId,
idfaStatus: status
)
}
func action(_ action: SPAction, from controller: SPMessageViewController) {
self.delegate?.onAction(action, from: controller)
switch action.type {
case .AcceptAll, .RejectAll, .SaveAndExit:
report(action: action)
finishAndNextIfAny(controller)
case .ShowPrivacyManager:
if let url = action.pmURL {
controller.loadPrivacyManager(url: url)
}
case .PMCancel:
controller.closePrivacyManager()
case .Dismiss:
finishAndNextIfAny(controller)
case .RequestATTAccess:
SPIDFAStatus.requestAuthorisation { status in
self.reportIdfaStatus(status: status, messageId: controller.messageId)
self.finishAndNextIfAny(controller)
}
default:
print("[SDK] UNKNOWN Action")
}
}
}