Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subscription attribution #2761

Merged
merged 22 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e79fa38
Make InstallationAttributionPixelHandler more generic
alessandroboron May 9, 2024
e68a299
Add URL methods to get and add URLQueryItems
alessandroboron May 9, 2024
2d34cbe
Add helpers to initialise attributed pixel handler
alessandroboron May 9, 2024
56281ae
Extract logic to redirect privacy pro URL and store attribution origin
alessandroboron May 9, 2024
67af303
Add new pixel to track successful subscription attribution
alessandroboron May 9, 2024
5dcf4a3
Add extensions to GenericAttributionPixelHandler to track attribution…
alessandroboron May 9, 2024
21b7f6c
Fire the Pixel for successful subscription attribution
alessandroboron May 9, 2024
04a04a6
Import SubscriptionAttributionPixelHandler.swift
alessandroboron May 9, 2024
cf87ec8
Update BrowserServiceKit version
alessandroboron May 9, 2024
583b3c2
Add unit tests for redirect logic
alessandroboron May 9, 2024
5efff88
Add tests for SubscriptionAttributionPixelHandler
alessandroboron May 9, 2024
0df9711
Clean up code
alessandroboron May 9, 2024
f9ea5e4
Manually delete origin attribution from the SubscriptionStorage upon …
alessandroboron May 10, 2024
4334f12
Move URL extensions to browser service kit
alessandroboron May 10, 2024
6704f58
Updated BSK version
alessandroboron May 10, 2024
641fc31
Update BSK and move SubscriptionOrigin within macOS repo
alessandroboron May 13, 2024
8f768b9
Clean up code
alessandroboron May 13, 2024
2de3349
Fix sandbox tests
alessandroboron May 13, 2024
c1e473b
Fix PR comments
alessandroboron May 15, 2024
a61db4e
Update BSK to 145.2.0
alessandroboron May 16, 2024
e29c3d1
Add comments to purchasePageRedirectURL
alessandroboron May 16, 2024
d5ca770
Move logic to append query items to a private URL extension
alessandroboron May 16, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion DuckDuckGo.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/duckduckgo/BrowserServicesKit",
"state" : {
"revision" : "739e7a89f1ddf18d2fe83e94a83892e248f60668",
"version" : "145.1.0"
"revision" : "c69a664b58cb351ccb73aa548726854a2861c0ed",
"version" : "145.2.0"
}
},
{
Expand Down
97 changes: 97 additions & 0 deletions DuckDuckGo/Common/Attribution/AttributionPixelHandler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//
// AttributionPixelHandler.swift
//
// 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 PixelKit

// A type that send pixels that needs attributions parameters.
protocol AttributionPixelHandler {
func fireAttributionPixel(
event: PixelKit.Event,
frequency: PixelKit.Frequency,
origin: String?,
additionalParameters: [String: String]?
)
}

final class GenericAttributionPixelHandler: AttributionPixelHandler {
enum Parameters {
static let origin = "origin"
static let locale = "locale"
}

private let fireRequest: FireRequest
private let locale: Locale

/// Creates an instance with the specified fire request, origin provider and locale.
/// - Parameters:
/// - fireRequest: A function for sending the Pixel request.
/// - locale: The locale of the device.
init(
fireRequest: @escaping FireRequest = PixelKit.fire,
locale: Locale = .current
) {
self.fireRequest = fireRequest
self.locale = locale
}

func fireAttributionPixel(
event: PixelKit.Event,
frequency: PixelKit.Frequency,
origin: String?,
additionalParameters: [String: String]?
) {
fireRequest(
event,
frequency,
[:],
self.parameters(additionalParameters, withOrigin: origin, locale: locale.identifier),
nil,
nil,
true, { _, _ in }
)
}
}

// MARK: - Parameter

private extension GenericAttributionPixelHandler {
func parameters(_ parameters: [String: String]?, withOrigin origin: String?, locale: String) -> [String: String] {
var parameters = parameters ?? [:]
parameters[Self.Parameters.locale] = locale
if let origin {
parameters[Self.Parameters.origin] = origin
}
return parameters
}
}

// MARK: - FireRequest

extension GenericAttributionPixelHandler {
typealias FireRequest = (
_ event: PixelKit.Event,
_ frequency: PixelKit.Frequency,
_ headers: [String: String],
_ parameters: [String: String]?,
_ error: Error?,
_ allowedQueryReservedCharacters: CharacterSet?,
_ includeAppVersionParameter: Bool,
_ onComplete: @escaping (Bool, Error?) -> Void
) -> Void
}
1 change: 1 addition & 0 deletions DuckDuckGo/Common/Extensions/URLExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -581,4 +581,5 @@ extension URL {
return false
}
}

}
63 changes: 10 additions & 53 deletions DuckDuckGo/Statistics/ATB/InstallationAttributionPixelHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,72 +20,29 @@ import Foundation
import PixelKit

/// A type that handles Pixels for acquisition attributions.
protocol AttributionsPixelHandler: AnyObject {
protocol InstallationAttributionsPixelHandler: AnyObject {
/// Fire the Pixel to track the App install.
func fireInstallationAttributionPixel()
}

final class InstallationAttributionPixelHandler: AttributionsPixelHandler {
enum Parameters {
static let origin = "origin"
static let locale = "locale"
}

private let fireRequest: FireRequest
final class AppInstallationAttributionPixelHandler: InstallationAttributionsPixelHandler {
private let originProvider: AttributionOriginProvider
private let locale: Locale
private let decoratedAttributionPixelHandler: AttributionPixelHandler

/// Creates an instance with the specified fire request, origin provider and locale.
/// - Parameters:
/// - fireRequest: A function for sending the Pixel request.
/// - originProvider: A provider for the origin used to track the acquisition funnel.
/// - locale: The locale of the device.
init(
fireRequest: @escaping FireRequest = PixelKit.fire,
originProvider: AttributionOriginProvider = AttributionOriginFileProvider(),
locale: Locale = .current
attributionPixelHandler: AttributionPixelHandler = GenericAttributionPixelHandler()
) {
self.fireRequest = fireRequest
self.originProvider = originProvider
self.locale = locale
decoratedAttributionPixelHandler = attributionPixelHandler
}

func fireInstallationAttributionPixel() {
fireRequest(
GeneralPixel.installationAttribution,
.legacyInitial,
[:],
additionalParameters(origin: originProvider.origin, locale: locale.identifier),
nil,
nil,
true, { _, _ in }
decoratedAttributionPixelHandler.fireAttributionPixel(
event: GeneralPixel.installationAttribution,
frequency: .legacyInitial,
origin: originProvider.origin,
additionalParameters: nil
)
}
}

// MARK: - Parameter

private extension InstallationAttributionPixelHandler {
func additionalParameters(origin: String?, locale: String) -> [String: String] {
var dictionary = [Self.Parameters.locale: locale]
if let origin {
dictionary[Self.Parameters.origin] = origin
}
return dictionary
}
}

// MARK: - FireRequest

extension InstallationAttributionPixelHandler {
typealias FireRequest = (
_ event: PixelKit.Event,
_ frequency: PixelKit.Frequency,
_ headers: [String: String],
_ parameters: [String: String]?,
_ error: Error?,
_ allowedQueryReservedCharacters: CharacterSet?,
_ includeAppVersionParameter: Bool,
_ onComplete: @escaping (Bool, Error?) -> Void
) -> Void
}
4 changes: 2 additions & 2 deletions DuckDuckGo/Statistics/ATB/StatisticsLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ final class StatisticsLoader {

private let statisticsStore: StatisticsStore
private let emailManager: EmailManager
private let attributionPixelHandler: AttributionsPixelHandler
private let attributionPixelHandler: InstallationAttributionsPixelHandler
private let parser = AtbParser()
private var isAppRetentionRequestInProgress = false

init(
statisticsStore: StatisticsStore = LocalStatisticsStore(),
emailManager: EmailManager = EmailManager(),
attributionPixelHandler: AttributionsPixelHandler = InstallationAttributionPixelHandler()
attributionPixelHandler: InstallationAttributionsPixelHandler = AppInstallationAttributionPixelHandler()
) {
self.statisticsStore = statisticsStore
self.emailManager = emailManager
Expand Down
2 changes: 2 additions & 0 deletions DuckDuckGo/Statistics/PrivacyProPixel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ enum PrivacyProPixel: PixelKitEventV2 {
case privacyProSubscriptionManagementPlanBilling
case privacyProSubscriptionManagementRemoval
case privacyProPurchaseStripeSuccess
case privacyProSuccessfulSubscriptionAttribution
// Web pixels
case privacyProOfferMonthlyPriceClick
case privacyProOfferYearlyPriceClick
Expand Down Expand Up @@ -110,6 +111,7 @@ enum PrivacyProPixel: PixelKitEventV2 {
case .privacyProSubscriptionManagementPlanBilling: return "m_mac_\(appDistribution)_privacy-pro_settings_change-plan-or-billing_click"
case .privacyProSubscriptionManagementRemoval: return "m_mac_\(appDistribution)_privacy-pro_settings_remove-from-device_click"
case .privacyProPurchaseStripeSuccess: return "m_mac_\(appDistribution)_privacy-pro_app_subscription-purchase_stripe_success"
case .privacyProSuccessfulSubscriptionAttribution: return "m_mac_\(appDistribution)_subscribe"
// Web
case .privacyProOfferMonthlyPriceClick: return "m_mac_\(appDistribution)_privacy-pro_offer_monthly-price_click"
case .privacyProOfferYearlyPriceClick: return "m_mac_\(appDistribution)_privacy-pro_offer_yearly-price_click"
Expand Down
46 changes: 46 additions & 0 deletions DuckDuckGo/Subscription/SubscriptionAttributionPixelHandler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// SubscriptionAttributionPixelHandler.swift
//
// 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 Subscription

protocol SubscriptionAttributionPixelHandler: AnyObject {
var origin: String? { get set }
func fireSuccessfulSubscriptionAttributionPixel()
}

// MARK: - SubscriptionAttributionPixelHandler

final class PrivacyProSubscriptionAttributionPixelHandler: SubscriptionAttributionPixelHandler {
var origin: String?
private let decoratedAttributionPixelHandler: AttributionPixelHandler

init(attributionPixelHandler: AttributionPixelHandler = GenericAttributionPixelHandler()) {
decoratedAttributionPixelHandler = attributionPixelHandler
}

func fireSuccessfulSubscriptionAttributionPixel() {
decoratedAttributionPixelHandler.fireAttributionPixel(
event: PrivacyProPixel.privacyProSuccessfulSubscriptionAttribution,
frequency: .standard,
origin: origin,
additionalParameters: nil
)
}

}
66 changes: 66 additions & 0 deletions DuckDuckGo/Subscription/SubscriptionRedirectManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
//
// SubscriptionRedirectManager.swift
//
// 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 Subscription
import BrowserServicesKit

protocol SubscriptionRedirectManager: AnyObject {
func redirectURL(for url: URL) -> URL?
}

final class PrivacyProSubscriptionRedirectManager: SubscriptionRedirectManager {
private let featureAvailabiltyProvider: () -> Bool

init(featureAvailabiltyProvider: @escaping @autoclosure () -> Bool = DefaultSubscriptionFeatureAvailability().isFeatureAvailable) {
self.featureAvailabiltyProvider = featureAvailabiltyProvider
}

func redirectURL(for url: URL) -> URL? {
guard url.isPart(ofDomain: "duckduckgo.com") else { return nil }

if url.pathComponents == URL.privacyPro.pathComponents {
let isFeatureAvailable = featureAvailabiltyProvider()
let shouldHidePrivacyProDueToNoProducts = SubscriptionPurchaseEnvironment.current == .appStore && SubscriptionPurchaseEnvironment.canPurchase == false
let isPurchasePageRedirectActive = isFeatureAvailable && !shouldHidePrivacyProDueToNoProducts
// Redirect the `/pro` URL to `/subscriptions` URL. If there are any query items in the original URL it appends to the `/subscriptions` URL.
return isPurchasePageRedirectActive ? URL.subscriptionBaseURL.addingQueryItems(from: url) : nil
}

return nil
}

}

private extension URL {

func addingQueryItems(from url: URL) -> URL {
// If the origin value is of type "do+something" appending the percentEncodedQueryItem crashes the browser as + is replaced by a space.
// Perform encoding on the value to avoid the crash.
guard let queryItems = url.getQueryItems()?
.compactMap({ queryItem -> URLQueryItem? in
guard let value = queryItem.value else { return nil }
let encodedValue = value.percentEncoded(withAllowedCharacters: .urlQueryParameterAllowed)
return URLQueryItem(name: queryItem.name, value: encodedValue)
})
else { return self }

return self.appending(percentEncodedQueryItems: queryItems)
}

}
23 changes: 7 additions & 16 deletions DuckDuckGo/Tab/Navigation/RedirectNavigationResponder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@

import Navigation
import Foundation
import Subscription
import BrowserServicesKit

struct RedirectNavigationResponder: NavigationResponder {

private let redirectManager: SubscriptionRedirectManager

init(redirectManager: SubscriptionRedirectManager = PrivacyProSubscriptionRedirectManager()) {
self.redirectManager = redirectManager
}

func decidePolicy(for navigationAction: NavigationAction, preferences: inout NavigationPreferences) async -> NavigationActionPolicy? {
guard let mainFrame = navigationAction.mainFrameTarget, let redirectURL = redirectURL(for: navigationAction.url) else { return .next }
guard let mainFrame = navigationAction.mainFrameTarget, let redirectURL = redirectManager.redirectURL(for: navigationAction.url) else { return .next }

return .redirect(mainFrame) { navigator in
var request = navigationAction.request
Expand All @@ -33,17 +37,4 @@ struct RedirectNavigationResponder: NavigationResponder {
}
}

private func redirectURL(for url: URL) -> URL? {
guard url.isPart(ofDomain: "duckduckgo.com") else { return nil }

if url.pathComponents == URL.privacyPro.pathComponents {
let isFeatureAvailable = DefaultSubscriptionFeatureAvailability().isFeatureAvailable
let shouldHidePrivacyProDueToNoProducts = SubscriptionPurchaseEnvironment.current == .appStore && SubscriptionPurchaseEnvironment.canPurchase == false
let isPurchasePageRedirectActive = isFeatureAvailable && !shouldHidePrivacyProDueToNoProducts

return isPurchasePageRedirectActive ? URL.subscriptionBaseURL : nil
}

return nil
}
}
Loading
Loading