-
Notifications
You must be signed in to change notification settings - Fork 94
/
Targeting.swift
671 lines (537 loc) · 23.2 KB
/
Targeting.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
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
/* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import CoreLocation
import MapKit
fileprivate let PrebidTargetingKey_AGE = "age"
fileprivate let PrebidTargetingKey_GENDER = "gen"
fileprivate let PrebidTargetingKey_USER_ID = "xid"
fileprivate let PrebidTargetingKey_PUB_PROVIDED_PREFIX = "c."
/// A class that manages targeting information for ads.
///
/// This class provides properties and methods for setting and retrieving
/// user-specific targeting information, such as user ID, gender, and custom
/// data. It also includes details for OMID (Open Measurement Interface Definition)
/// partner and supports managing user identity links and custom extensions.
///
@objcMembers
public class Targeting: NSObject {
/// A shared instance of the `Targeting` class.
public static var shared = Targeting()
// MARK: - OMID Partner
/// The name of the OMID partner.
public var omidPartnerName: String?
/// The version of the OMID partner.
public var omidPartnerVersion: String?
// MARK: - User Information
/// Indicates user birth year.
public var yearOfBirth: Int {
get { yearofbirth }
set { setYearOfBirth(yob: newValue) }
}
/// This method set the year of birth value
public func setYearOfBirth(yob: Int) {
if AgeUtils.isYOBValid(yob) {
yearofbirth = yob
} else {
Log.error("Incorrect birth year. It will be ignored.")
}
}
/// Objective C API
public func getYearOfBirth() -> NSNumber {
NSNumber(value: yearOfBirth)
}
/// This method clears year of birth value set by the application developer
public func clearYearOfBirth() {
yearofbirth = 0
}
/// Indicates the end-user's gender.
public var userGender: Gender {
get {
guard let currentValue = parameterDictionary[PrebidTargetingKey_GENDER] else {
return .unknown
}
return GenderFromDescription(currentValue)
}
set {
parameterDictionary[PrebidTargetingKey_GENDER] = DescriptionOfGender(newValue)
}
}
/// String representation of the users gender,
/// where “M” = male, “F” = female, “O” = known to be other (i.e., omitted is unknown)
public func userGenderDescription() -> String? {
guard let currentValue = parameterDictionary[PrebidTargetingKey_GENDER] else {
return nil
}
return GenderDescription(rawValue: currentValue)?.rawValue
}
/// Indicates the customer-provided user ID, if different from the Device ID.
public var userID: String? {
get { parameterDictionary[PrebidTargetingKey_USER_ID] }
set { parameterDictionary[PrebidTargetingKey_USER_ID] = newValue }
}
/// Buyer-specific ID for the user as mapped by the exchange for the buyer.
public var buyerUID: String?
/// Optional feature to pass bidder data that was set in the
/// exchange’s cookie. The string must be in base85 cookie safe
/// characters and be in any format. Proper JSON encoding must
/// be used to include “escaped” quotation marks.
public var userCustomData: String?
/// Placeholder for User Identity Links.
/// The data from this property will be added to usr.ext.eids
public var eids: [[String : AnyHashable]]?
/// Placeholder for exchange-specific extensions to OpenRTB.
public var userExt: [String : AnyHashable]?
// MARK: - COPPA
/// Objective C analog of subjectToCOPPA
public var coppa: NSNumber? {
set { UserConsentDataManager.shared.subjectToCOPPA = newValue.boolValue }
get { UserConsentDataManager.shared.subjectToCOPPA.nsNumberValue }
}
/// Integer flag indicating if this request is subject to the COPPA regulations
/// established by the USA FTC, where 0 = no, 1 = yes
public var subjectToCOPPA: Bool? {
set { UserConsentDataManager.shared.subjectToCOPPA = newValue}
get { UserConsentDataManager.shared.subjectToCOPPA }
}
// MARK: - GDPR
/// The boolean value set by the user to collect user data
public var subjectToGDPR: Bool? {
set { UserConsentDataManager.shared.subjectToGDPR = newValue }
get { UserConsentDataManager.shared.subjectToGDPR }
}
/// Objective-C API
public func setSubjectToGDPR(_ newValue: NSNumber?) {
UserConsentDataManager.shared.subjectToGDPR = newValue?.boolValue
}
/// Objective-C API
public func getSubjectToGDPR() -> NSNumber? {
return UserConsentDataManager.shared.subjectToGDPR_NSNumber
}
// MARK: - GDPR Consent
/// The consent string for sending the GDPR consent
public var gdprConsentString: String? {
set { UserConsentDataManager.shared.gdprConsentString = newValue }
get { UserConsentDataManager.shared.gdprConsentString }
}
// MARK: - TCFv2
/// The consent string for purposes consent as per TCFv2.
public var purposeConsents: String? {
set { UserConsentDataManager.shared.purposeConsents = newValue }
get { UserConsentDataManager.shared.purposeConsents }
}
/// Purpose 1 - Store and/or access information on a device
public func getDeviceAccessConsent() -> Bool? {
UserConsentDataManager.shared.getDeviceAccessConsent()
}
/// Returns whether the user has consented to access device data as an `NSNumber`.
public func getDeviceAccessConsentObjc() -> NSNumber? {
UserConsentDataManager.shared.getDeviceAccessConsent() as NSNumber?
}
/// Returns the user's consent for a specific purpose by index.
public func getPurposeConsent(index: Int) -> Bool? {
UserConsentDataManager.shared.getPurposeConsent(index: index)
}
/// Checks if access to device data is allowed.
public func isAllowedAccessDeviceData() -> Bool {
UserConsentDataManager.shared.isAllowedAccessDeviceData()
}
// MARK: - External User Ids
/// Array of external user IDs.
///
/// This property holds the external user IDs associated with the user.
public var externalUserIds = [ExternalUserId]()
/// This method allows to save External User Id in the User Defaults
public func storeExternalUserId(_ externalUserId: ExternalUserId) {
if let index = externalUserIds.firstIndex(where: {$0.source == externalUserId.source}) {
externalUserIds[index] = externalUserId
} else {
externalUserIds.append(externalUserId)
}
StorageUtils.setExternalUserIds(value: externalUserIds)
}
/// This method allows to get All External User Ids from User Defaults
public func fetchStoredExternalUserIds()->[ExternalUserId]? {
return StorageUtils.getExternalUserIds()
}
/// This method allows to get External User Id from User Defaults by passing respective 'source' string as param
public func fetchStoredExternalUserId(_ source : String)->ExternalUserId? {
guard let array = StorageUtils.getExternalUserIds(), let externalUserId = array.first(where: {$0.source == source}) else{
return nil
}
return externalUserId
}
/// This method allows to remove specific External User Id from User Defaults by passing respective 'source' string as param
public func removeStoredExternalUserId(_ source : String) {
if let index = externalUserIds.firstIndex(where: {$0.source == source}) {
externalUserIds.remove(at: index)
StorageUtils.setExternalUserIds(value: externalUserIds)
}
}
/// This method allows to remove all the External User Ids from User Defaults
public func removeStoredExternalUserIds() {
if var arrayExternalUserIds = StorageUtils.getExternalUserIds(){
arrayExternalUserIds.removeAll()
StorageUtils.setExternalUserIds(value: arrayExternalUserIds)
}
}
public func getExternalUserIds() -> [[AnyHashable: Any]]? {
var externalUserIdArray = [ExternalUserId]()
if Prebid.shared.externalUserIdArray.count != 0 {
externalUserIdArray = Prebid.shared.externalUserIdArray
} else {
externalUserIdArray = externalUserIds
}
var transformedUserIdArray = [[AnyHashable: Any]]()
for externalUserId in externalUserIdArray {
transformedUserIdArray.append(externalUserId.toJSONDictionary())
}
if let eids = eids {
transformedUserIdArray.append(contentsOf: eids)
}
return transformedUserIdArray.isEmpty ? nil : transformedUserIdArray
}
// MARK: - Application Information
/// This is the deep-link URL for the app screen that is displaying the ad. This can be an iOS universal link.
public var contentUrl: String?
/// App's publisher name.
public var publisherName: String?
/// ID of publisher app in Apple’s App Store.
public var sourceapp: String?
/// App store URL for an installed app
public var storeURL: String? {
get { parameterDictionary[PBMParameterKeys.APP_STORE_URL.rawValue] }
set { parameterDictionary[PBMParameterKeys.APP_STORE_URL.rawValue] = newValue }
}
/// Domain name of the app
public var domain: String?
/// The itunes app id for targeting
public var itunesID: String?
/// The application location for targeting
public var location: CLLocation?
/// The application location precision for targeting
public var locationPrecision: Int?
/// Objective-C API
public func setLocationPrecision(_ newValue: NSNumber?) {
locationPrecision = newValue?.intValue
}
/// Objective-C API
public func getLocationPrecision() -> NSNumber? {
return locationPrecision as NSNumber?
}
// MARK: - Location and connection information
/// CLLocationCoordinate2D.
/// See CoreLocation framework documentation.
public var coordinate: NSValue?
// MARK: - Public Methods
// MARK: Arbitrary ORTB Configuration
/// Sets the global-level OpenRTB configuration string.
///
/// - Parameter ortbObject: The global-level OpenRTB configuration string to set. Can be `nil` to clear the configuration.
public func setGlobalORTBConfig(_ ortbConfig: String?) {
globalORTBConfig = ortbConfig
}
/// Returns the global-level OpenRTB configuration string.
public func getGlobalORTBConfig() -> String? {
globalORTBConfig
}
/// Adds a parameter to the parameter dictionary with a specified name.
///
/// - Parameters:
/// - value: The value of the parameter.
/// - withName: The name of the parameter. If `nil`, the parameter is not added.
public func addParam(_ value: String, withName: String?) {
guard let name = withName else {
Log.error("Invalid user parameter.")
return
}
if value.isEmpty {
parameterDictionary.removeValue(forKey: name)
} else {
parameterDictionary[name] = value
}
}
/// Sets custom parameters by adding each key-value pair to the parameter dictionary.
///
/// - Parameter params: A dictionary of parameters to set. If `nil`, no parameters are added.
public func setCustomParams(_ params: [String : String]?) {
guard let params = params else {
return
}
params.keys.forEach { key in
if let value = params[key] {
addCustomParam(value, withName: key)
}
}
}
/// Adds a custom parameter to the parameter dictionary with a prefixed name.
///
/// - Parameters:
/// - value: The value of the custom parameter.
/// - withName: The name of the custom parameter. If `nil`, the parameter is not added.
public func addCustomParam(_ value: String, withName: String?) {
guard let name = withName else {
return
}
let prefixedName = makeCustomParamFromName(name)
addParam(value, withName:prefixedName)
}
/// Store location in the user's section
public func setLatitude(_ latitude: Double, longitude: Double) {
coordinate = NSValue(mkCoordinate: CLLocationCoordinate2DMake(latitude, longitude))
}
// MARK: - Access Control List (ext.prebid.data)
/// Adds a bidder to the access control list.
///
/// - Parameter bidderName: The name of the bidder to add.
public func addBidderToAccessControlList(_ bidderName: String) {
rawAccessControlList.insert(bidderName)
}
/// Removes a bidder from the access control list.
///
/// - Parameter bidderName: The name of the bidder to remove.
public func removeBidderFromAccessControlList(_ bidderName: String) {
rawAccessControlList.remove(bidderName)
}
/// Clears all bidders from the access control list.
public func clearAccessControlList() {
rawAccessControlList.removeAll()
}
/// Retrieves the current access control list.
///
/// - Returns: An array of bidder names in the access control list.
public func getAccessControlList() -> [String] {
Array(rawAccessControlList)
}
/// Access control list for external use.
///
/// - Returns: An array of bidder names in the access control list.
public var accessControlList: [String] {
Array(rawAccessControlList)
}
// MARK: - Global User Data (user.ext.data)
/// Adds user data for a specified key.
///
/// - Parameters:
/// - key: The key for the user data.
/// - value: The value to add for the specified key.
public func addUserData(key: String, value: String) {
var values = rawUserDataDictionary[key] ?? Set<String>()
values.insert(value)
rawUserDataDictionary[key] = values
}
/// Updates user data for a specified key with a new set of values.
///
/// - Parameters:
/// - key: The key for the user data.
/// - value: The set of values to update for the specified key.
public func updateUserData(key: String, value: Set<String>) {
rawUserDataDictionary[key] = value
}
/// Removes user data for a specified key.
///
/// - Parameter key: The key for the user data to remove.
public func removeUserData(for key: String) {
rawUserDataDictionary.removeValue(forKey: key)
}
/// Clears all user data.
public func clearUserData() {
rawUserDataDictionary.removeAll()
}
/// Retrieves all user data.
///
/// - Returns: A dictionary mapping keys to arrays of values.
public func getUserData() -> [String: [String]] {
rawUserDataDictionary.mapValues { Array($0) }
}
/// User data dictionary for external use.
///
/// - Returns: A dictionary mapping keys to arrays of values.
public var userDataDictionary: [String : [String]] {
rawUserDataDictionary.mapValues { Array($0) }
}
// MARK: - Global User Keywords (user.keywords)
/// Adds a user keyword.
///
/// - Parameter newElement: The keyword to add.
public func addUserKeyword(_ newElement: String) {
userKeywordsSet.insert(newElement)
}
/// Adds multiple user keywords.
///
/// - Parameter newElements: A set of keywords to add.
public func addUserKeywords(_ newElements: Set<String>) {
userKeywordsSet.formUnion(newElements)
}
/// Removes a user keyword.
///
/// - Parameter element: The keyword to remove.
public func removeUserKeyword(_ element: String) {
userKeywordsSet.remove(element)
}
/// Clears all user keywords.
public func clearUserKeywords() {
userKeywordsSet.removeAll()
}
/// Retrieves all user keywords.
///
/// - Returns: An array of user keywords.
public func getUserKeywords() -> [String] {
return Array(userKeywordsSet)
}
/// Deprecated. Use `getUserKeywords` method instead.
@available(*, deprecated, message: "This property is deprecated. Please, use getUserKeywords method instead.")
public var userKeywords: [String] {
Array(userKeywordsSet)
}
// MARK: - Global Data (app.ext.data)
/// Deprecated. Use `addAppExtData` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use addAppExtData method instead.")
public func addContextData(key: String, value: String) {
addAppExtData(key: key, value: value)
}
/// Deprecated. Use `updateAppExtData` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use updateAppExtData method instead.")
public func updateContextData(key: String, value: Set<String>) {
updateAppExtData(key: key, value: value)
}
/// Deprecated. Use `removeAppExtData` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use removeAppExtData method instead.")
public func removeContextData(for key: String) {
removeAppExtData(for: key)
}
/// Deprecated. Use `clearAppExtData` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use clearAppExtData method instead.")
public func clearContextData() {
clearAppExtData()
}
/// Deprecated. Use `getAppExtData` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use getAppExtData method instead.")
public func getContextData() -> [String: [String]] {
getAppExtData()
}
/// Deprecated. Use `getAppExtData` method instead.
@available(*, deprecated, message: "This property is deprecated. Please, use getAppExtData method instead.")
public var contextDataDictionary: [String: [String]] {
getAppExtData()
}
/// Adds application-specific data for a specified key.
///
/// - Parameters:
/// - key: The key for the application data.
/// - value: The value to add for the specified key.
public func addAppExtData(key: String, value: String) {
var values = rawAppExtDataDictionary[key] ?? Set<String>()
values.insert(value)
rawAppExtDataDictionary[key] = values
}
/// Updates application-specific data for a specified key with a new set of values.
///
/// - Parameters:
/// - key: The key for the application data.
/// - value: The set of values to update for the specified key.
public func updateAppExtData(key: String, value: Set<String>) {
rawAppExtDataDictionary[key] = value
}
/// Removes application-specific data for a specified key.
///
/// - Parameter key: The key for the application data to remove.
public func removeAppExtData(for key: String) {
rawAppExtDataDictionary.removeValue(forKey: key)
}
/// Clears all application-specific data.
public func clearAppExtData() {
rawAppExtDataDictionary.removeAll()
}
/// Retrieves all application-specific data.
///
/// - Returns: A dictionary mapping keys to arrays of values.
public func getAppExtData() -> [String: [String]] {
rawAppExtDataDictionary.mapValues { Array($0) }
}
// MARK: - Global Keywords (app.keywords)
/// Deprecated. Use `addAppKeyword` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use addAppKeyword method instead.")
public func addContextKeyword(_ newElement: String) {
addAppKeyword(newElement)
}
/// Deprecated. Use `addAppKeywords` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use addAppKeywords method instead.")
public func addContextKeywords(_ newElements: Set<String>) {
addAppKeywords(newElements)
}
/// Deprecated. Use `removeAppKeyword` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use removeAppKeyword method instead.")
public func removeContextKeyword(_ element: String) {
removeAppKeyword(element)
}
/// Deprecated. Use `clearAppKeywords` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use clearAppKeywords method instead.")
public func clearContextKeywords() {
clearAppKeywords()
}
/// Deprecated. Use `getAppKeywords` method instead.
@available(*, deprecated, message: "This method is deprecated. Please, use getAppKeywords method instead.")
public func getContextKeywords() -> [String] {
getAppKeywords()
}
/// Deprecated. Use `getAppKeywords` method instead.
@available(*, deprecated, message: "This property is deprecated. Please, use getAppKeywords method instead.")
public var contextKeywords: [String] {
getAppKeywords()
}
/// Adds an application keyword.
///
/// - Parameter newElement: The keyword to add.
public func addAppKeyword(_ newElement: String) {
appKeywordsSet.insert(newElement)
}
/// Adds multiple application keywords.
///
/// - Parameter newElements: A set of keywords to add.
public func addAppKeywords(_ newElements: Set<String>) {
appKeywordsSet.formUnion(newElements)
}
/// Removes an application keyword.
///
/// - Parameter element: The keyword to remove.
public func removeAppKeyword(_ element: String) {
appKeywordsSet.remove(element)
}
/// Clears all application keywords.
public func clearAppKeywords() {
appKeywordsSet.removeAll()
}
/// Retrieves all application keywords.
///
/// - Returns: An array of application keywords.
public func getAppKeywords() -> [String] {
return Array(appKeywordsSet)
}
// MARK: - Internal Properties
/// Dictionary of parameters.
public var parameterDictionary = [String : String]()
private var userKeywordsSet = Set<String>()
private var appKeywordsSet = Set<String>()
private var rawAccessControlList = Set<String>()
private var rawUserDataDictionary = [String : Set<String>]()
private var rawAppExtDataDictionary = [String : Set<String>]()
private var yearofbirth = 0
private var globalORTBConfig: String?
// MARK: - Internal Methods
func makeCustomParamFromName(_ name: String) -> String {
if name.hasPrefix(PrebidTargetingKey_PUB_PROVIDED_PREFIX) {
return name
}
return PrebidTargetingKey_PUB_PROVIDED_PREFIX + name
}
}