-
Notifications
You must be signed in to change notification settings - Fork 969
[ads] Search result attribution on iOS #21974
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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
73 changes: 73 additions & 0 deletions
73
ios/brave-ios/Sources/Brave/Frontend/Browser/Search/BraveSearchResultAdManager.swift
This file contains hidden or 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,73 @@ | ||
// Copyright 2024 The Brave Authors. All rights reserved. | ||
// 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 BraveCore | ||
|
||
// A helper class to handle Brave Search Result Ads. | ||
class BraveSearchResultAdManager: NSObject { | ||
private let searchResultAdClickedUrlPath = "/a/redirect" | ||
|
||
private let placementId = "placement_id" | ||
|
||
private let rewards: BraveRewards | ||
|
||
private var searchResultAds = [String: BraveAds.SearchResultAdInfo]() | ||
|
||
init?(url: URL, rewards: BraveRewards, isPrivateBrowsing: Bool) { | ||
if !BraveAds.shouldSupportSearchResultAds() || | ||
!BraveSearchManager.isValidURL(url) || | ||
isPrivateBrowsing || | ||
rewards.isEnabled { | ||
return nil | ||
} | ||
|
||
self.rewards = rewards | ||
} | ||
|
||
func isSearchResultAdClickedURL(_ url: URL) -> Bool { | ||
return getPlacementID(url) != nil | ||
} | ||
|
||
func triggerSearchResultAdViewedEvent( | ||
placementId: String, | ||
searchResultAd: BraveAds.SearchResultAdInfo) { | ||
searchResultAds[placementId] = searchResultAd | ||
|
||
guard let searchResultAd = searchResultAds[placementId] else { | ||
return | ||
} | ||
|
||
rewards.ads.triggerSearchResultAdEvent( | ||
searchResultAd, | ||
eventType: .viewed, | ||
completion: { _ in }) | ||
} | ||
|
||
func maybeTriggerSearchResultAdClickedEvent(_ url: URL) { | ||
guard let placementId = getPlacementID(url) else { | ||
return | ||
} | ||
|
||
guard let searchResultAd = searchResultAds[placementId] else { | ||
return | ||
} | ||
|
||
rewards.ads.triggerSearchResultAdEvent( | ||
searchResultAd, | ||
eventType: .clicked, | ||
completion: { _ in }) | ||
} | ||
|
||
private func getPlacementID(_ url: URL) -> String? { | ||
if !BraveSearchManager.isValidURL(url) || | ||
url.path != searchResultAdClickedUrlPath { | ||
return nil | ||
} | ||
guard let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else { | ||
return nil | ||
} | ||
return queryItems.first(where: { $0.name == placementId })?.value | ||
} | ||
} |
This file contains hidden or 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 hidden or 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
123 changes: 123 additions & 0 deletions
123
...t/UserScripts/Scripts_Dynamic/ScriptHandlers/Paged/BraveSearchResultAdScriptHandler.swift
This file contains hidden or 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,123 @@ | ||
// Copyright 2024 The Brave Authors. All rights reserved. | ||
// 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 BraveCore | ||
import BraveShared | ||
import os.log | ||
import WebKit | ||
|
||
class BraveSearchResultAdScriptHandler: TabContentScript { | ||
private struct SearchResultAdResponse: Decodable { | ||
struct SearchResultAd: Decodable { | ||
let creativeInstanceId: String | ||
let placementId: String | ||
let creativeSetId: String | ||
let campaignId: String | ||
let advertiserId: String | ||
let landingPage: URL | ||
let headlineText: String | ||
let description: String | ||
let rewardsValue: String | ||
let conversionUrlPatternValue: String? | ||
let conversionAdvertiserPublicKeyValue: String? | ||
let conversionObservationWindowValue: Int? | ||
} | ||
|
||
let creatives: [SearchResultAd] | ||
} | ||
|
||
fileprivate weak var tab: Tab? | ||
|
||
init(tab: Tab) { | ||
self.tab = tab | ||
} | ||
|
||
static let scriptName = "BraveSearchResultAdScript" | ||
static let scriptId = UUID().uuidString | ||
static let messageHandlerName = "\(scriptName)_\(messageUUID)" | ||
static let scriptSandbox: WKContentWorld = .defaultClient | ||
static let userScript: WKUserScript? = { | ||
guard var script = loadUserScript(named: scriptName) else { | ||
return nil | ||
} | ||
return WKUserScript(source: secureScript(handlerName: messageHandlerName, | ||
securityToken: scriptId, | ||
script: script), | ||
injectionTime: .atDocumentEnd, | ||
forMainFrameOnly: true, | ||
in: scriptSandbox) | ||
}() | ||
|
||
func userContentController( | ||
_ userContentController: WKUserContentController, | ||
didReceiveScriptMessage message: WKScriptMessage, | ||
replyHandler: (Any?, String?) -> Void | ||
) { | ||
defer { replyHandler(nil, nil) } | ||
|
||
if !verifyMessage(message: message) { | ||
assertionFailure("Missing required security token.") | ||
return | ||
} | ||
|
||
guard let tab = tab, | ||
let braveSearchResultAdManager = tab.braveSearchResultAdManager | ||
else { | ||
Logger.module.error("Failed to get brave search result ad handler") | ||
return | ||
} | ||
|
||
guard JSONSerialization.isValidJSONObject(message.body), | ||
let messageData = try? JSONSerialization.data(withJSONObject: message.body, options: []), | ||
let searchResultAds = try? JSONDecoder().decode(SearchResultAdResponse.self, from: messageData) | ||
else { | ||
Logger.module.error("Failed to parse search result ads response") | ||
return | ||
} | ||
|
||
processSearchResultAds(searchResultAds, braveSearchResultAdManager: braveSearchResultAdManager) | ||
} | ||
|
||
private func processSearchResultAds( | ||
_ searchResultAds: SearchResultAdResponse, | ||
braveSearchResultAdManager: BraveSearchResultAdManager | ||
) { | ||
for ad in searchResultAds.creatives { | ||
guard let rewardsValue = Double(ad.rewardsValue) | ||
else { | ||
Logger.module.error("Failed to process search result ads JSON-LD") | ||
return | ||
} | ||
|
||
var conversion: BraveAds.ConversionInfo? | ||
if let conversionUrlPatternValue = ad.conversionUrlPatternValue, | ||
let conversionObservationWindowValue = ad.conversionObservationWindowValue { | ||
let timeInterval = TimeInterval(conversionObservationWindowValue) * 1.days | ||
conversion = .init( | ||
urlPattern: conversionUrlPatternValue, | ||
verifiableAdvertiserPublicKeyBase64: ad.conversionAdvertiserPublicKeyValue, | ||
observationWindow: Date(timeIntervalSince1970: timeInterval) | ||
) | ||
} | ||
|
||
let searchResultAd: BraveAds.SearchResultAdInfo = .init( | ||
type: .searchResultAd, | ||
placementId: ad.placementId, | ||
creativeInstanceId: ad.creativeInstanceId, | ||
creativeSetId: ad.creativeSetId, | ||
campaignId: ad.campaignId, | ||
advertiserId: ad.advertiserId, | ||
targetUrl: ad.landingPage, | ||
headlineText: ad.headlineText, | ||
description: ad.description, | ||
value: rewardsValue, | ||
conversion: conversion | ||
) | ||
|
||
braveSearchResultAdManager.triggerSearchResultAdViewedEvent( | ||
placementId: ad.placementId, searchResultAd:searchResultAd) | ||
} | ||
} | ||
} |
64 changes: 64 additions & 0 deletions
64
...ent/UserScripts/Scripts_Dynamic/Scripts/DomainSpecific/Paged/BraveSearchResultAdScript.js
This file contains hidden or 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,64 @@ | ||
// Copyright (c) 2024 The Brave Authors. All rights reserved. | ||
// 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 https://mozilla.org/MPL/2.0/. | ||
|
||
'use strict'; | ||
|
||
window.__firefox__.includeOnce('BraveSearchResultAdScript', function($) { | ||
let sendMessage = $(function(creatives) { | ||
$.postNativeMessage('$<message_handler>', { | ||
"securityToken": SECURITY_TOKEN, | ||
"creatives": creatives | ||
}); | ||
}); | ||
|
||
let getJsonLdCreatives = () => { | ||
const scripts = | ||
document.querySelectorAll('script[type="application/ld+json"]'); | ||
const jsonLdList = | ||
Array.from(scripts).map(script => JSON.parse(script.textContent)); | ||
|
||
if (!jsonLdList) { | ||
return []; | ||
} | ||
|
||
const creativeFieldNamesMapping = { | ||
'data-creative-instance-id': 'creativeInstanceId', | ||
'data-placement-id': 'placementId', | ||
'data-creative-set-id': 'creativeSetId', | ||
'data-campaign-id': 'campaignId', | ||
'data-advertiser-id': 'advertiserId', | ||
'data-landing-page': 'landingPage', | ||
'data-headline-text': 'headlineText', | ||
'data-description': 'description', | ||
'data-rewards-value': 'rewardsValue', | ||
'data-conversion-url-pattern-value': 'conversionUrlPatternValue', | ||
'data-conversion-advertiser-public-key-value': | ||
'conversionAdvertiserPublicKeyValue', | ||
'data-conversion-observation-window-value': | ||
'conversionObservationWindowValue' | ||
}; | ||
|
||
let jsonLdCreatives = []; | ||
jsonLdList.forEach(jsonLd => { | ||
if (jsonLd['@type'] === 'Product' && jsonLd.creatives) { | ||
jsonLd.creatives.forEach(creative => { | ||
if (creative['@type'] === 'SearchResultAd') { | ||
let jsonLdCreative = {}; | ||
for (let key in creative) { | ||
if (creativeFieldNamesMapping[key]) { | ||
jsonLdCreative[creativeFieldNamesMapping[key]] = creative[key]; | ||
} | ||
} | ||
jsonLdCreatives.push(jsonLdCreative); | ||
} | ||
}); | ||
} | ||
}); | ||
|
||
return jsonLdCreatives; | ||
}; | ||
|
||
sendMessage(getJsonLdCreatives()); | ||
}); |
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.