-
Notifications
You must be signed in to change notification settings - Fork 424
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'main' into sam/improve-vpn-metadata
- Loading branch information
Showing
47 changed files
with
1,831 additions
and
322 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
15.1 | ||
15.2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
// | ||
// AdAttributionFetcher.swift | ||
// DuckDuckGo | ||
// | ||
// Copyright © 2024 DuckDuckGo. All rights reserved. | ||
// | ||
// 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 AdServices | ||
import Common | ||
|
||
protocol AdAttributionFetcher { | ||
func fetch() async -> AdServicesAttributionResponse? | ||
} | ||
|
||
/// Fetches ad attribution data for from Apple. | ||
/// | ||
/// DuckDuckGo uses the AdServices framework to fetch and monitor anonymous install attribution data from Apple. No personally identifiable data is involved. | ||
/// DuckDuckGo does not use the App Tracking Transparency framework at any point, and only uses the “standard” attribution payload. | ||
/// See https://developer.apple.com/documentation/adservices/aaattribution/attributiontoken()#Attribution-payload-descriptions for details. | ||
struct DefaultAdAttributionFetcher: AdAttributionFetcher { | ||
|
||
typealias TokenGetter = () throws -> String | ||
|
||
private let tokenGetter: TokenGetter | ||
private let urlSession: URLSession | ||
private let retryInterval: TimeInterval | ||
|
||
init(tokenGetter: @escaping TokenGetter = Self.fetchAttributionToken, | ||
urlSession: URLSession = .shared, | ||
retryInterval: TimeInterval = .seconds(5)) { | ||
self.tokenGetter = tokenGetter | ||
self.urlSession = urlSession | ||
self.retryInterval = retryInterval | ||
} | ||
|
||
func fetch() async -> AdServicesAttributionResponse? { | ||
guard #available(iOS 14.3, *) else { | ||
return nil | ||
} | ||
|
||
var lastToken: String? | ||
|
||
for _ in 0..<Constant.maxRetries { | ||
do { | ||
try Task.checkCancellation() | ||
|
||
let token = try (lastToken ?? tokenGetter()) | ||
lastToken = token | ||
return try await fetchAttributionData(using: token) | ||
} catch let error as AdAttributionFetcherError { | ||
os_log("AdAttributionFetcher failed to fetch attribution data: %@. Retrying.", log: .adAttributionLog, error.localizedDescription) | ||
|
||
if error == .invalidToken { | ||
lastToken = nil | ||
} | ||
|
||
if error.allowsRetry { | ||
try? await Task.sleep(interval: retryInterval) | ||
continue | ||
} else { | ||
break | ||
} | ||
} catch { | ||
os_log("AdAttributionFetcher failed to fetch attribution data: %@", log: .adAttributionLog, error.localizedDescription) | ||
|
||
// Do not retry | ||
break | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
private func fetchAttributionData(using token: String) async throws -> AdServicesAttributionResponse { | ||
let request = createAttributionDataRequest(with: token) | ||
let (data, response) = try await urlSession.data(for: request) | ||
|
||
guard let response = response as? HTTPURLResponse else { | ||
throw AdAttributionFetcherError.invalidResponse | ||
} | ||
|
||
switch response.statusCode { | ||
case 200: | ||
let decoder = JSONDecoder() | ||
let decoded = try decoder.decode(AdServicesAttributionResponse.self, from: data) | ||
|
||
return decoded | ||
case 400: | ||
throw AdAttributionFetcherError.invalidToken | ||
case 404: | ||
throw AdAttributionFetcherError.invalidResponse | ||
default: | ||
throw AdAttributionFetcherError.unknown | ||
} | ||
} | ||
|
||
private func createAttributionDataRequest(with token: String) -> URLRequest { | ||
var request = URLRequest(url: Constant.attributionServiceURL) | ||
request.httpMethod = "POST" | ||
request.setValue("text/plain", forHTTPHeaderField: "Content-Type") | ||
request.httpBody = token.data(using: .utf8) | ||
|
||
return request | ||
} | ||
|
||
private struct Constant { | ||
static let attributionServiceURL = URL(string: "https://api-adservices.apple.com/api/v1/")! | ||
static let maxRetries = 3 | ||
} | ||
} | ||
|
||
extension AdAttributionFetcher { | ||
static func fetchAttributionToken() throws -> String { | ||
if #available(iOS 14.3, *) { | ||
return try AAAttribution.attributionToken() | ||
} else { | ||
throw AdAttributionFetcherError.attributionUnsupported | ||
} | ||
} | ||
} | ||
|
||
struct AdServicesAttributionResponse: Decodable { | ||
let attribution: Bool | ||
let orgId: Int? | ||
let campaignId: Int? | ||
let conversionType: String? | ||
let adGroupId: Int? | ||
let countryOrRegion: String? | ||
let keywordId: Int? | ||
let adId: Int? | ||
} | ||
|
||
enum AdAttributionFetcherError: Error { | ||
case attributionUnsupported | ||
case invalidResponse | ||
case invalidToken | ||
case unknown | ||
|
||
var allowsRetry: Bool { | ||
switch self { | ||
case .invalidToken, .invalidResponse: | ||
return true | ||
case .unknown, .attributionUnsupported: | ||
return false | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
// | ||
// AdAttributionPixelReporter.swift | ||
// DuckDuckGo | ||
// | ||
// Copyright © 2024 DuckDuckGo. All rights reserved. | ||
// | ||
// 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 Core | ||
|
||
protocol PixelFiring { | ||
static func fire(pixel: Pixel.Event, withAdditionalParameters params: [String: String]) async throws | ||
} | ||
|
||
final class AdAttributionPixelReporter { | ||
|
||
static var shared = AdAttributionPixelReporter() | ||
|
||
private var fetcherStorage: AdAttributionReporterStorage | ||
private let attributionFetcher: AdAttributionFetcher | ||
private let pixelFiring: PixelFiring.Type | ||
|
||
init(fetcherStorage: AdAttributionReporterStorage = UserDefaultsAdAttributionReporterStorage(), | ||
attributionFetcher: AdAttributionFetcher = DefaultAdAttributionFetcher(), | ||
pixelFiring: PixelFiring.Type = Pixel.self) { | ||
self.fetcherStorage = fetcherStorage | ||
self.attributionFetcher = attributionFetcher | ||
self.pixelFiring = pixelFiring | ||
} | ||
|
||
@discardableResult | ||
func reportAttributionIfNeeded() async -> Bool { | ||
guard await fetcherStorage.wasAttributionReportSuccessful == false else { | ||
return false | ||
} | ||
|
||
if let attributionData = await self.attributionFetcher.fetch() { | ||
if attributionData.attribution { | ||
let parameters = self.pixelParametersForAttribution(attributionData) | ||
do { | ||
try await pixelFiring.fire(pixel: .appleAdAttribution, withAdditionalParameters: parameters) | ||
} catch { | ||
return false | ||
} | ||
} | ||
|
||
await fetcherStorage.markAttributionReportSuccessful() | ||
|
||
return true | ||
} | ||
|
||
return false | ||
} | ||
|
||
private func pixelParametersForAttribution(_ attribution: AdServicesAttributionResponse) -> [String: String] { | ||
var params: [String: String] = [:] | ||
|
||
params[PixelParameters.adAttributionAdGroupID] = attribution.adGroupId.map(String.init) | ||
params[PixelParameters.adAttributionOrgID] = attribution.orgId.map(String.init) | ||
params[PixelParameters.adAttributionCampaignID] = attribution.campaignId.map(String.init) | ||
params[PixelParameters.adAttributionConversionType] = attribution.conversionType | ||
params[PixelParameters.adAttributionAdGroupID] = attribution.adGroupId.map(String.init) | ||
params[PixelParameters.adAttributionCountryOrRegion] = attribution.countryOrRegion | ||
params[PixelParameters.adAttributionKeywordID] = attribution.keywordId.map(String.init) | ||
params[PixelParameters.adAttributionAdID] = attribution.adId.map(String.init) | ||
|
||
return params | ||
} | ||
} | ||
|
||
extension Pixel: PixelFiring { | ||
static func fire(pixel: Event, withAdditionalParameters params: [String: String]) async throws { | ||
|
||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in | ||
Pixel.fire(pixel: pixel, withAdditionalParameters: params) { error in | ||
if let error { | ||
continuation.resume(throwing: error) | ||
} else { | ||
continuation.resume() | ||
} | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.