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

[MOB-2959] Braze IAM for Newsletter NTP card #812

Merged
merged 19 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
75 changes: 62 additions & 13 deletions Client.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/braze-inc/braze-swift-sdk",
"state" : {
"revision" : "66bf1d9b55ec697c82eaa9b499296aa317de26b4",
"version" : "11.1.1"
"revision" : "36481467bc4f333a0a2e31bcdbf981ad8e526dd0",
"version" : "11.2.0"
}
},
{
Expand Down Expand Up @@ -59,8 +59,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/ecosia/ios-core.git",
"state" : {
"branch" : "main",
"revision" : "2a957f6fd4fd4a322ec64c05d770d22ea749689a"
"branch" : "ls-mob-2959-braze-ntp-card-newsletter",
"revision" : "c65d3407196a6682b2e5f07ace2d0c0cd3c7c455"
}
},
{
Expand Down Expand Up @@ -113,8 +113,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/SDWebImage/SDWebImage.git",
"state" : {
"revision" : "8a1be70a625683bc04d6903e2935bf23f3c6d609",
"version" : "5.19.7"
"revision" : "10d06f6a33bafae8c164fbfd1f03391f6d4692b3",
"version" : "5.20.0"
}
},
{
Expand Down
4 changes: 2 additions & 2 deletions Client/Application/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Ecosia: Lifecycle tracking. Needs to happen after Unleash start so that the flags are correctly added to the analytics context.
Analytics.shared.activity(.launch)
// Ecosia: Engagement Service Initialization helper
await ClientEngagementService.shared.initializeAndRefreshNotificationRegistration(notificationCenterDelegate: self)
lucaschifino marked this conversation as resolved.
Show resolved Hide resolved
await BrazeService.shared.initialize(notificationCenterDelegate: self)
// Ecosia: Experiment that directly asks for consent
await APNConsentOnLaunchExperiment.requestAPNConsentIfNeeded(delegate: self)
}
Expand Down Expand Up @@ -402,6 +402,6 @@ extension AppDelegate: UNUserNotificationCenterDelegate {}

extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
ClientEngagementService.shared.registerDeviceToken(deviceToken)
BrazeService.shared.registerDeviceToken(deviceToken)
}
}
24 changes: 22 additions & 2 deletions Client/Ecosia/Analytics/Analytics.Values.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ extension Analytics {
case
activity,
bookmarks,
brazeIAM = "braze_iam",
browser,
external,
intro,
Expand All @@ -17,6 +18,7 @@ extension Analytics {
menuStatus = "menu_status",
migration,
navigation,
newsletterExperiment = "newsletter_experiment",
ntp,
pushNotificationConsent = "push_notification_consent",
settings
Expand Down Expand Up @@ -85,6 +87,11 @@ extension Analytics {
terms
}

enum NewsletterCardExperiment: String {
case
ntpCard = "ntp_card"
}

enum NTP: String {
case
about,
Expand Down Expand Up @@ -137,8 +144,7 @@ extension Analytics {
case
allow,
deny,
dismiss,
skip,
error,
view
}

Expand All @@ -147,6 +153,20 @@ extension Analytics {
`import`
}

enum BrazeIAM: String {
case
click,
dismiss,
view
}

enum NewsletterCardExperiment: String {
case
click,
dismiss,
view
}

enum NTPCustomization: String {
case
click,
Expand Down
14 changes: 14 additions & 0 deletions Client/Ecosia/Analytics/Analytics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ open class Analytics {
track(event)
}

// MARK: Braze IAM
func brazeIAM(action: Action.BrazeIAM, messageOrButtonId: String?) {
track(Structured(category: Category.brazeIAM.rawValue,
action: action.rawValue)
.property(messageOrButtonId))
}

// MARK: Default Browser
func appOpenAsDefaultBrowser() {
let event = Structured(category: Category.external.rawValue,
Expand Down Expand Up @@ -178,6 +185,13 @@ open class Analytics {
.property(new))
}

// MARK: `NewsletterCardExperiment`
func newsletterCardExperiment(action: Action.NewsletterCardExperiment) {
track(Structured(category: Category.newsletterExperiment.rawValue,
action: action.rawValue)
.label(Label.NewsletterCardExperiment.ntpCard.rawValue))
}

// MARK: NTP
func ntpCustomisation(_ action: Action.NTPCustomization, label: Label.NTP) {
track(Structured(category: Category.ntp.rawValue,
Expand Down
161 changes: 161 additions & 0 deletions Client/Ecosia/Braze/BrazeService.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/

import Foundation
import BrazeKit
import BrazeUI
import Core

final class BrazeService {
private init() {}

private var braze: Braze?
private var userId: String {
User.shared.analyticsId.uuidString
}
private(set) var notificationAuthorizationStatus: UNAuthorizationStatus?
private static var apiKey = EnvironmentFetcher.valueFromMainBundleOrProcessInfo(forKey: "BRAZE_API_KEY") ?? ""
static let shared = BrazeService()

enum Error: Swift.Error {
case invalidConfiguration
case generic(description: String)
}

enum CustomEvent: String {
case newsletterCardClick = "newsletter_card_click"
}

// TODO: Make `BrazeService` directly `UNUserNotificationCenterDelegate`
lucaschifino marked this conversation as resolved.
Show resolved Hide resolved
func initialize(notificationCenterDelegate: UNUserNotificationCenterDelegate) async {
do {
try await initBraze(userId: userId)
await refreshAPNRegistrationIfNeeded(notificationCenterDelegate: notificationCenterDelegate)
} catch {
debugPrint(error)
}
}

func registerDeviceToken(_ deviceToken: Data) {
braze?.notifications.register(deviceToken: deviceToken)
Task.detached(priority: .medium) { [weak self] in
await self?.updateID(self?.userId)
}
}

func logCustomEvent(_ event: CustomEvent) {
self.braze?.logCustomEvent(name: event.rawValue)
}

// MARK: - APN Consent

func requestAPNConsent(notificationCenterDelegate: UNUserNotificationCenterDelegate) async throws -> Bool {
await UIApplication.shared.registerForRemoteNotifications()
let notificationCenter = makeNotificationCenter(notificationCenterDelegate: notificationCenterDelegate)
let granted = try await notificationCenter.requestAuthorization()
await retrieveUserCurrentNotificationAuthStatus() // Make sure status is always updated
return granted
}

func refreshAPNRegistrationIfNeeded(notificationCenterDelegate: UNUserNotificationCenterDelegate) async {
let notificationCenter = UNUserNotificationCenter.current()
let currentStatus = await notificationCenter.notificationSettings().authorizationStatus
switch currentStatus {
case .authorized, .ephemeral, .provisional:
_ = try? await requestAPNConsent(notificationCenterDelegate: notificationCenterDelegate)
default:
break
}
}
}

extension BrazeService {
// MARK: - Init Braze

@MainActor
private func initBraze(userId: String) throws {
self.braze = Braze(configuration: try getBrazeConfiguration())
let inAppMessageUI = BrazeInAppMessageUI()
inAppMessageUI.delegate = self
self.braze?.inAppMessagePresenter = inAppMessageUI
Task.detached(priority: .medium) { [weak self] in
await self?.updateID(self?.userId)
}
}
}

extension BrazeService {
// MARK: - Notification Center

private func makeNotificationCenter(notificationCenterDelegate: UNUserNotificationCenterDelegate) -> UNUserNotificationCenter {
let center = UNUserNotificationCenter.current()
center.setNotificationCategories(BrazeKit.Braze.Notifications.categories)
center.delegate = notificationCenterDelegate
return center
}

private func retrieveUserCurrentNotificationAuthStatus() async {
let notificationCenter = UNUserNotificationCenter.current()
let currentStatus = await notificationCenter.notificationSettings().authorizationStatus
notificationAuthorizationStatus = currentStatus
}
}

extension BrazeService {
// MARK: - ID Update

private func updateID(_ id: String?) async {
guard let id else { return }
#if MOZ_CHANNEL_FENNEC
print("📣🆔 Braze Identifier Updating To: \(id)")
#endif
let brazeID = await braze?.user.id()
guard id != brazeID else { return }
braze?.changeUser(userId: id)
}
}

extension BrazeService {
// MARK: - Environment Configuration

/// Retrieves the Braze configuration based on the provided parameters.
///
/// - Parameters:
/// - apiKey: The Braze API key to be used for configuration.
/// - environment: The target environment for which the Braze configuration is requested.
/// Defaults to the current environment.
/// - Returns: A Braze configuration if the required parameters are present.
/// - Throws: An `Error.invalidConfiguration` if the API key is empty.
///
/// - Note: The `environment` parameter allows customization of the target environment.
/// If not provided, it defaults to the current environment.
///
/// - Warning: Ensure that the provided API key is not empty to avoid invalid configurations.
func getBrazeConfiguration(apiKey: String = BrazeService.apiKey,
environment: Environment = Environment.current) throws -> BrazeKit.Braze.Configuration {
guard !apiKey.isEmpty else { throw Error.invalidConfiguration }

let brazeConfiguration = BrazeKit.Braze.Configuration(apiKey: apiKey, endpoint: environment.urlProvider.brazeEndpoint)
#if MOZ_CHANNEL_FENNEC
brazeConfiguration.logger.level = .debug
#endif
return brazeConfiguration
}
}

extension BrazeService: BrazeInAppMessageUIDelegate {
lucaschifino marked this conversation as resolved.
Show resolved Hide resolved

func inAppMessage(_ ui: BrazeInAppMessageUI, didPresent message: Braze.InAppMessage, view: any InAppMessageView) {
Analytics.shared.brazeIAM(action: .view, messageOrButtonId: message.id)
}

func inAppMessage(_ ui: BrazeInAppMessageUI, didDismiss message: Braze.InAppMessage, view: any InAppMessageView) {
Analytics.shared.brazeIAM(action: .dismiss, messageOrButtonId: message.id)
}

func inAppMessage(_ ui: BrazeInAppMessageUI, shouldProcess clickAction: Braze.InAppMessage.ClickAction, buttonId: String?, message: Braze.InAppMessage, view: any InAppMessageView) -> Bool {
Analytics.shared.brazeIAM(action: .click, messageOrButtonId: buttonId)
return true
}
}
66 changes: 0 additions & 66 deletions Client/Ecosia/EngagementService/EngagementService.swift

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ struct APNConsentOnLaunchExperiment {
}

static func requestAPNConsentIfNeeded(delegate: UNUserNotificationCenterDelegate) async {
guard isEnabled, ClientEngagementService.shared.notificationAuthorizationStatus == .notDetermined else {
guard isEnabled, BrazeService.shared.notificationAuthorizationStatus == .notDetermined else {
return
}
Analytics.shared.apnConsentOnLaunchExperiment(.view)
ClientEngagementService.shared.requestAPNConsent(notificationCenterDelegate: delegate) { granted, error in
do {
let granted = try await BrazeService.shared.requestAPNConsent(notificationCenterDelegate: delegate)
Analytics.shared.apnConsentOnLaunchExperiment(granted ? .allow : .deny)
} catch {
Analytics.shared.apnConsentOnLaunchExperiment(.error)
}
}
}
Loading
Loading