Merge branch 'master' into migrate_NTP_SI_2

This commit is contained in:
Deep Pandya
2020-03-17 19:30:08 -04:00
committed by GitHub
51 changed files with 962 additions and 547 deletions
+1 -1
View File
@@ -79,7 +79,7 @@ if (is_android) {
"//brave/android/sync/android_sync.js",
"//brave/android/sync/android_sync_words.js",
"//brave/android/sync/crypto.js",
"//brave/components/brave_sync/extension/brave-sync/bundles/bundle.js",
"//brave/components/brave_sync/extension/brave-sync-android/bundles/bundle.js",
"//brave/LICENSE.html",
]
deps = [
+16 -2
View File
@@ -2,7 +2,6 @@ use_relative_paths = True
deps = {
"vendor/adblock_rust_ffi": "https://github.com/brave/adblock-rust-ffi.git@5c9ed5ab387cb14e9c9af41d3d9b5eb4fc71f3e4",
"vendor/autoplay-whitelist": "https://github.com/brave/autoplay-whitelist.git@ea527a4d36051daedb34421e129c98eda06cb5d3",
"vendor/extension-whitelist": "https://github.com/brave/extension-whitelist.git@7843f62e26a23c51336330e220e9d7992680aae9",
"vendor/hashset-cpp": "https://github.com/brave/hashset-cpp.git@6eab0271d014ff09bd9f38abe1e0c117e13e9aa9",
"vendor/requests": "https://github.com/kennethreitz/requests@e4d59bedfd3c7f4f254f4f5d036587bcd8152458",
@@ -15,7 +14,14 @@ deps = {
"vendor/bip39wally-core-native": "https://github.com/brave-intl/bip39wally-core-native.git@13bb40a215248cfbdd87d0a6b425c8397402e9e6",
"vendor/bat-native-anonize": "https://github.com/brave-intl/bat-native-anonize.git@e3742ba3e8942eea9e4755d91532491871bd3116",
"vendor/bat-native-tweetnacl": "https://github.com/brave-intl/bat-native-tweetnacl.git@800f9d40b7409239ff192e0be634764e747c7a75",
"components/brave_sync/extension/brave-sync": "https://github.com/brave/sync.git@4428f605acd31542387bfa8956dda28becaec650",
"components/brave_sync/extension/brave-sync": {
'url': 'https://github.com/brave/sync.git@4428f605acd31542387bfa8956dda28becaec650',
'condition': 'not checkout_android',
},
"components/brave_sync/extension/brave-sync-android": {
'url': 'https://github.com/brave/sync.git@4098493496b19f46c33a66b8867c69ee6d1a4568',
'condition': 'checkout_android',
},
"vendor/bat-native-usermodel": "https://github.com/brave-intl/bat-native-usermodel.git@45e32155af9897dbe1d5534dd36697ec4728bb75",
"vendor/challenge_bypass_ristretto_ffi": "https://github.com/brave-intl/challenge-bypass-ristretto-ffi.git@c396fb4eb9e9bf63b89ae5a0ec0b5f201d43c7c5",
}
@@ -45,5 +51,13 @@ hooks = [
'name': 'build_brave_sync',
'pattern': '.',
'action': ['python', 'src/brave/script/build-simple-js-bundle.py', '--repo_dir_path', 'src/brave/components/brave_sync/extension/brave-sync'],
'condition': 'not checkout_android',
},
{
# Build brave-sync android
'name': 'build_brave_sync',
'pattern': '.',
'action': ['python', 'src/brave/script/build-simple-js-bundle.py', '--repo_dir_path', 'src/brave/components/brave_sync/extension/brave-sync-android'],
'condition': 'checkout_android',
}
]
@@ -6,6 +6,6 @@
package org.chromium.chrome.browser.preferences;
public final class BravePreferenceKeys {
public static final String BRAVE_BOTTOM_TOOLBAR_SET_KEY = "brave_bottom_toolbar_set";
public static final String BRAVE_BOTTOM_TOOLBAR_ENABLED_KEY = "brave_bottom_toolbar_enabled";
public static final String BRAVE_BOTTOM_TOOLBAR_ENABLED_KEY = "brave_bottom_toolbar_enabled_key";
public static final String BRAVE_BOTTOM_TOOLBAR_SET_KEY = "brave_bottom_toolbar_enabled";
}
@@ -94,6 +94,7 @@ public class BraveMainPreferencesBase extends BravePreferenceFragment {
if (!ChromeFeatureList.isEnabled(BraveFeatureList.BRAVE_REWARDS) ||
BravePrefServiceBridge.getInstance().getSafetynetCheckFailed()) {
removePreferenceIfPresent(PREF_BRAVE_REWARDS);
removePreferenceIfPresent(PREF_WELCOME_TOUR);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
@@ -18,6 +18,7 @@ import org.chromium.base.library_loader.LibraryProcessType;
import org.chromium.base.task.PostTask;
import org.chromium.chrome.browser.BraveHelper;
import org.chromium.chrome.browser.preferences.BravePref;
import org.chromium.chrome.browser.preferences.BravePreferenceKeys;
import org.chromium.chrome.browser.preferences.BravePrefServiceBridge;
import org.chromium.chrome.browser.preferences.website.BraveShieldsContentSettings;
import org.chromium.chrome.browser.profiles.Profile;
@@ -57,12 +58,51 @@ public class BraveUpgradeJobIntentService extends JobIntentService {
private static final String DSE_NAME = "Google";
private static final String DSE_KEYWORD = "google.com";
// Old tabs bottom toolbar settings
private static final String BOTTOM_TOOLBAR_ENABLED_KEY = "bottom_toolbar_enabled";
// To detect update from tabs
private static final String PREF_STATS_PREFERENCES_NAME = "StatsPreferences";
private static final String PREF_WEEK_OF_INSTALLATION_NAME = "WeekOfInstallation";
public static void startMigrationIfNecessary(Context context) {
if (BraveUpgradeJobIntentService.needToMigratePreferences()) {
// Migrate bottom toolbar settings
SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences();
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putBoolean(BravePreferenceKeys.BRAVE_BOTTOM_TOOLBAR_ENABLED_KEY,
sharedPreferences.getBoolean(BOTTOM_TOOLBAR_ENABLED_KEY, true));
sharedPreferencesEditor.apply();
}
// Start migration in any case as we can have only partial data
// to migrate available
BraveUpgradeJobIntentService.enqueueWork(context, new Intent());
}
private static boolean needToMigratePreferences() {
SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences();
boolean migrated = sharedPreferences.getBoolean(BraveHelper.PREF_TABS_SETTINGS_MIGRATED, false);
if (migrated) {
// Everything was already migrated
return false;
}
// Detect whether it is update from tabs
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
SharedPreferences prefStatsFromTabs = ContextUtils.getApplicationContext()
.getSharedPreferences(PREF_STATS_PREFERENCES_NAME, 0);
boolean updateFormTabs = prefStatsFromTabs.contains(PREF_WEEK_OF_INSTALLATION_NAME);
if (!updateFormTabs) {
// We assume that everything was migrated in that case
sharedPreferencesEditor.putBoolean(BraveHelper.PREF_TABS_SETTINGS_MIGRATED, true);
sharedPreferencesEditor.apply();
return false;
}
return true;
}
private static void enqueueWork(Context context, Intent work) {
enqueueWork(context, BraveUpgradeJobIntentService.class, JOB_ID, work);
}
@@ -188,12 +228,10 @@ public class BraveUpgradeJobIntentService extends JobIntentService {
}
private void migrateTotalStatsAndPreferences() {
SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences();
boolean migrated = sharedPreferences.getBoolean(BraveHelper.PREF_TABS_SETTINGS_MIGRATED, false);
if (migrated) {
// Everything was already migrated
if (!BraveUpgradeJobIntentService.needToMigratePreferences()) {
return;
}
SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences();
// Total stats migration
long trackersBlockedCount = sharedPreferences.getLong(PREF_TRACKERS_BLOCKED_COUNT, 0);
long adsBlockedCount = sharedPreferences.getLong(PREF_ADS_BLOCKED_COUNT, 0);
@@ -209,15 +247,6 @@ public class BraveUpgradeJobIntentService extends JobIntentService {
BravePrefServiceBridge.getInstance().setOldHttpsUpgradesCount(profile, httpsUpgradesCount);
}
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
if (trackersBlockedCount == 0 &&
adsBlockedCount == 0 &&
httpsUpgradesCount == 0) {
// We assume that everything was migrated in that case
sharedPreferencesEditor.putBoolean(BraveHelper.PREF_TABS_SETTINGS_MIGRATED, true);
sharedPreferencesEditor.apply();
return;
}
sharedPreferencesEditor.putLong(PREF_TRACKERS_BLOCKED_COUNT, 0);
sharedPreferencesEditor.putLong(PREF_ADS_BLOCKED_COUNT, 0);
sharedPreferencesEditor.putLong(PREF_HTTPS_UPGRADES_COUNT, 0);
@@ -12,7 +12,7 @@
android:summaryOff="@string/hide_brave_rewards_icon_description" />
<org.chromium.chrome.browser.settings.ChromeSwitchPreference
android:key="brave_bottom_toolbar_enabled"
android:key="brave_bottom_toolbar_enabled_key"
android:title="@string/bottom_toolbar_enable"
android:summaryOn="@string/text_on"
android:summaryOff="@string/text_off" />
@@ -8,7 +8,6 @@
#include <utility>
#include "brave/browser/brave_browser_process_impl.h"
#include "brave/components/brave_shields/browser/autoplay_whitelist_service.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/permissions/permission_request_id.h"
#include "chrome/common/chrome_features.h"
@@ -23,18 +22,6 @@ AutoplayPermissionContext::AutoplayPermissionContext(Profile* profile)
AutoplayPermissionContext::~AutoplayPermissionContext() = default;
ContentSetting AutoplayPermissionContext::GetPermissionStatusInternal(
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const GURL& embedding_origin) const {
if (g_brave_browser_process &&
g_brave_browser_process->autoplay_whitelist_service()
->ShouldAllowAutoplay(requesting_origin))
return CONTENT_SETTING_ALLOW;
return PermissionContextBase::GetPermissionStatusInternal(
render_frame_host, requesting_origin, embedding_origin);
}
void AutoplayPermissionContext::UpdateTabContext(
const PermissionRequestID& id,
const GURL& requesting_frame,
@@ -16,10 +16,6 @@ class AutoplayPermissionContext : public PermissionContextBase {
private:
// PermissionContextBase:
ContentSetting GetPermissionStatusInternal(
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const GURL& embedding_origin) const override;
void UpdateTabContext(const PermissionRequestID& id,
const GURL& requesting_frame,
bool allowed) override;
@@ -13,7 +13,6 @@
#include "brave/common/brave_paths.h"
#include "brave/common/pref_names.h"
#include "brave/components/brave_component_updater/browser/local_data_files_service.h"
#include "brave/components/brave_shields/browser/autoplay_whitelist_service.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/ui/browser.h"
@@ -33,7 +32,6 @@ const char kVideoPlaying[] = "Video playing";
const char kVideoPlayingDetect[] =
"window.domAutomationController.send(document.getElementById('status')."
"textContent);";
const char kTestDataDirectory[] = "autoplay-whitelist-data";
const char kEmbeddedTestServerDirectory[] = "autoplay";
class AutoplayPermissionContextBrowserTest : public InProcessBrowserTest {
@@ -143,57 +141,6 @@ class AutoplayPermissionContextBrowserTest : public InProcessBrowserTest {
std::unique_ptr<BraveContentBrowserClient> browser_content_client_;
};
class AutoplayWhitelistServiceTest : public BaseLocalDataFilesBrowserTest {
public:
AutoplayWhitelistServiceTest() {}
void SetUpOnMainThread() override {
BaseLocalDataFilesBrowserTest::SetUpOnMainThread();
// exact host match
whitelist_autoplay_urls_.push_back(embedded_test_server()->GetURL(
"example.com", "/autoplay_by_attr.html"));
// eTLD+1 match
whitelist_autoplay_urls_.push_back(embedded_test_server()->GetURL(
"sub.example.com", "/autoplay_by_attr.html"));
// exact host match with subdomain
whitelist_autoplay_urls_.push_back(embedded_test_server()->GetURL(
"sandbox.uphold.com", "/autoplay_by_attr.html"));
}
// BaseLocalDataFilesBrowserTest overrides
const char* test_data_directory() override { return kTestDataDirectory; }
const char* embedded_test_server_directory() override {
return kEmbeddedTestServerDirectory;
}
LocalDataFilesObserver* service() override {
return g_brave_browser_process->autoplay_whitelist_service();
}
// functions used by autoplay whitelist service tests
content::WebContents* contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
bool NavigateToURLUntilLoadStop(const GURL& url) {
ui_test_utils::NavigateToURL(browser(), url);
return WaitForLoadStop(contents());
}
void WaitForPlaying() {
std::string msg_from_renderer;
ASSERT_TRUE(ExecuteScriptAndExtractString(
contents(), "notifyWhenPlaying();", &msg_from_renderer));
ASSERT_EQ("PLAYING", msg_from_renderer);
}
const GURL& whitelist_autoplay_url(int index) {
return whitelist_autoplay_urls_[index];
}
private:
std::vector<GURL> whitelist_autoplay_urls_;
};
// Autoplay blocks by default, no bubble is shown
IN_PROC_BROWSER_TEST_F(AutoplayPermissionContextBrowserTest,
DISABLED_BlockByDefault) {
@@ -273,7 +220,7 @@ IN_PROC_BROWSER_TEST_F(AutoplayPermissionContextBrowserTest,
EXPECT_NE(result, kVideoPlaying);
}
// Click allow from promt
// Click allow from prompt
IN_PROC_BROWSER_TEST_F(AutoplayPermissionContextBrowserTest, ClickAllow) {
std::string result;
AskAutoplay();
@@ -561,65 +508,3 @@ IN_PROC_BROWSER_TEST_F(AutoplayPermissionContextBrowserTest, FileAutoplay) {
ExecuteScriptAndExtractString(contents(), kVideoPlayingDetect, &result));
EXPECT_EQ(result, kVideoPlaying);
}
// Default allow autoplay on URLs in whitelist if host matches exactly
IN_PROC_BROWSER_TEST_F(AutoplayWhitelistServiceTest, AllowIfExactHostMatch) {
ASSERT_TRUE(InstallMockExtension());
std::string result;
PermissionRequestManager* manager =
PermissionRequestManager::FromWebContents(contents());
auto popup_prompt_factory =
std::make_unique<MockPermissionPromptFactory>(manager);
NavigateToURLUntilLoadStop(whitelist_autoplay_url(0));
EXPECT_FALSE(popup_prompt_factory->is_visible());
EXPECT_FALSE(popup_prompt_factory->RequestTypeSeen(
PermissionRequestType::PERMISSION_AUTOPLAY));
EXPECT_EQ(0, popup_prompt_factory->TotalRequestCount());
WaitForPlaying();
EXPECT_TRUE(
ExecuteScriptAndExtractString(contents(), kVideoPlayingDetect, &result));
EXPECT_EQ(result, kVideoPlaying);
}
// Default allow autoplay on URLs in whitelist if eTLD+1 matches
IN_PROC_BROWSER_TEST_F(AutoplayWhitelistServiceTest, AllowIfETLDPlusOneMatch) {
ASSERT_TRUE(InstallMockExtension());
std::string result;
PermissionRequestManager* manager =
PermissionRequestManager::FromWebContents(contents());
auto popup_prompt_factory =
std::make_unique<MockPermissionPromptFactory>(manager);
NavigateToURLUntilLoadStop(whitelist_autoplay_url(1));
EXPECT_FALSE(popup_prompt_factory->is_visible());
EXPECT_FALSE(popup_prompt_factory->RequestTypeSeen(
PermissionRequestType::PERMISSION_AUTOPLAY));
EXPECT_EQ(0, popup_prompt_factory->TotalRequestCount());
WaitForPlaying();
EXPECT_TRUE(
ExecuteScriptAndExtractString(contents(), kVideoPlayingDetect, &result));
EXPECT_EQ(result, kVideoPlaying);
}
// Default allow autoplay on URLs in whitelist if multi-domain host matches
// exactly
IN_PROC_BROWSER_TEST_F(AutoplayWhitelistServiceTest,
AllowIfExactSubdomainAndHostMatch) {
ASSERT_TRUE(InstallMockExtension());
std::string result;
PermissionRequestManager* manager =
PermissionRequestManager::FromWebContents(contents());
auto popup_prompt_factory =
std::make_unique<MockPermissionPromptFactory>(manager);
NavigateToURLUntilLoadStop(whitelist_autoplay_url(2));
EXPECT_FALSE(popup_prompt_factory->is_visible());
EXPECT_FALSE(popup_prompt_factory->RequestTypeSeen(
PermissionRequestType::PERMISSION_AUTOPLAY));
EXPECT_EQ(0, popup_prompt_factory->TotalRequestCount());
WaitForPlaying();
EXPECT_TRUE(
ExecuteScriptAndExtractString(contents(), kVideoPlayingDetect, &result));
EXPECT_EQ(result, kVideoPlaying);
}
@@ -84,37 +84,36 @@ class AutoplayPermissionContextTests
DISALLOW_COPY_AND_ASSIGN(AutoplayPermissionContextTests);
};
// Autoplay permission status should still be default(block) even for
// insecure origin
// Autoplay permission status should be default even for insecure origin
TEST_F(AutoplayPermissionContextTests, TestInsecureQueryingUrl) {
AutoplayPermissionContextTest permission_context(profile());
GURL insecure_url("http://www.example.com");
GURL secure_url("https://www.example.com");
// Check that there is no saved content settings.
EXPECT_EQ(CONTENT_SETTING_BLOCK,
EXPECT_EQ(CONTENT_SETTING_ALLOW,
HostContentSettingsMapFactory::GetForProfile(profile())
->GetContentSetting(
insecure_url.GetOrigin(), insecure_url.GetOrigin(),
ContentSettingsType::AUTOPLAY, std::string()));
EXPECT_EQ(
CONTENT_SETTING_BLOCK,
CONTENT_SETTING_ALLOW,
HostContentSettingsMapFactory::GetForProfile(profile())
->GetContentSetting(secure_url.GetOrigin(), insecure_url.GetOrigin(),
ContentSettingsType::AUTOPLAY, std::string()));
EXPECT_EQ(
CONTENT_SETTING_BLOCK,
CONTENT_SETTING_ALLOW,
HostContentSettingsMapFactory::GetForProfile(profile())
->GetContentSetting(insecure_url.GetOrigin(), secure_url.GetOrigin(),
ContentSettingsType::AUTOPLAY, std::string()));
EXPECT_EQ(CONTENT_SETTING_BLOCK,
EXPECT_EQ(CONTENT_SETTING_ALLOW,
permission_context
.GetPermissionStatus(nullptr /* render_frame_host */,
insecure_url, insecure_url)
.content_setting);
EXPECT_EQ(CONTENT_SETTING_BLOCK,
EXPECT_EQ(CONTENT_SETTING_ALLOW,
permission_context
.GetPermissionStatus(nullptr /* render_frame_host */,
insecure_url, secure_url)
-12
View File
@@ -25,7 +25,6 @@
#include "brave/components/brave_shields/browser/ad_block_custom_filters_service.h"
#include "brave/components/brave_shields/browser/ad_block_regional_service_manager.h"
#include "brave/components/brave_shields/browser/ad_block_service.h"
#include "brave/components/brave_shields/browser/autoplay_whitelist_service.h"
#include "brave/components/brave_shields/browser/https_everywhere_service.h"
#include "brave/components/brave_shields/browser/referrer_whitelist_service.h"
#include "brave/components/brave_shields/browser/tracking_protection_service.h"
@@ -182,7 +181,6 @@ void BraveBrowserProcessImpl::StartBraveServices() {
ad_block_regional_service_manager()->Start();
https_everywhere_service()->Start();
autoplay_whitelist_service();
#if BUILDFLAG(ENABLE_EXTENSIONS)
extension_whitelist_service();
#endif
@@ -238,16 +236,6 @@ BraveBrowserProcessImpl::ntp_sponsored_images_service() {
return ntp_sponsored_images_service_.get();
}
brave_shields::AutoplayWhitelistService*
BraveBrowserProcessImpl::autoplay_whitelist_service() {
if (!autoplay_whitelist_service_) {
autoplay_whitelist_service_ =
brave_shields::AutoplayWhitelistServiceFactory(
local_data_files_service());
}
return autoplay_whitelist_service_.get();
}
#if BUILDFLAG(ENABLE_EXTENSIONS)
brave_component_updater::ExtensionWhitelistService*
BraveBrowserProcessImpl::extension_whitelist_service() {
-4
View File
@@ -39,7 +39,6 @@ namespace brave_shields {
class AdBlockService;
class AdBlockCustomFiltersService;
class AdBlockRegionalServiceManager;
class AutoplayWhitelistService;
class HTTPSEverywhereService;
class ReferrerWhitelistService;
class TrackingProtectionService;
@@ -78,7 +77,6 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl {
brave_shields::AdBlockCustomFiltersService* ad_block_custom_filters_service();
brave_shields::AdBlockRegionalServiceManager*
ad_block_regional_service_manager();
brave_shields::AutoplayWhitelistService* autoplay_whitelist_service();
#if BUILDFLAG(ENABLE_EXTENSIONS)
brave_component_updater::ExtensionWhitelistService*
extension_whitelist_service();
@@ -132,8 +130,6 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl {
ad_block_custom_filters_service_;
std::unique_ptr<brave_shields::AdBlockRegionalServiceManager>
ad_block_regional_service_manager_;
std::unique_ptr<brave_shields::AutoplayWhitelistService>
autoplay_whitelist_service_;
#if BUILDFLAG(ENABLE_EXTENSIONS)
std::unique_ptr<brave_component_updater::ExtensionWhitelistService>
extension_whitelist_service_;
@@ -4,10 +4,10 @@
* You can obtain one at https://mozilla.org/MPL/2.0/. */
#define BRAVE_INIT { \
/* Add CONTENT_SETTING_ASK and make it default for autoplay*/ \
/* Add CONTENT_SETTING_ASK for autoplay*/ \
content_settings_info_.erase(ContentSettingsType::AUTOPLAY); \
website_settings_registry_->UnRegister(ContentSettingsType::AUTOPLAY); \
Register(ContentSettingsType::AUTOPLAY, "autoplay", CONTENT_SETTING_BLOCK, \
Register(ContentSettingsType::AUTOPLAY, "autoplay", CONTENT_SETTING_ALLOW, \
WebsiteSettingsInfo::UNSYNCABLE, WhitelistedSchemes(), \
ValidSettings(CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK, \
CONTENT_SETTING_ASK), \
@@ -5,27 +5,21 @@
#include "third_party/blink/public/platform/web_content_settings_client.h"
#define BRAVE_AUTOPLAY_POLICY_DOCUMENT_SHOULD_AUTOPLAY_MUTED_VIDEOS \
if (GetAutoplayPolicyForDocument(document) == \
AutoplayPolicy::Type::kUserGestureRequired) \
return false;
#define BRAVE_AUTOPLAY_POLICY_IS_GESTURE_NEEDED_FOR_PLAYBACK \
if (IsAutoplayAllowedPerSettings()) \
return false;
#define BRAVE_AUTOPLAY_POLICY_IS_AUTOPLAY_ALLOWED_PER_SETTINGS \
bool AutoplayPolicy::IsAutoplayAllowedPerSettings() const { \
LocalFrame* frame = element_->GetDocument().GetFrame(); \
if (!frame) \
return false; \
if (auto* settings_client = frame->GetContentSettingsClient()) \
return settings_client->AllowAutoplay(false /* default_value */); \
return true; \
#define BRAVE_AUTOPLAY_POLICY_IS_AUTOPLAY_ALLOWED_PER_SETTINGS \
bool AutoplayPolicy::IsAutoplayAllowedPerSettings() const { \
LocalFrame* frame = element_->GetDocument().GetFrame(); \
if (!frame) \
return false; \
if (auto* settings_client = frame->GetContentSettingsClient()) \
return settings_client->AllowAutoplay(true /* default_value */); \
return true; \
}
#include "../../../../../third_party/blink/renderer/core/html/media/autoplay_policy.cc" // NOLINT
#undef BRAVE_AUTOPLAY_POLICY_DOCUMENT_SHOULD_AUTOPLAY_MUTED_VIDEOS
#undef BRAVE_AUTOPLAY_POLICY_IS_GESTURE_NEEDED_FOR_PLAYBACK
#undef BRAVE_AUTOPLAY_POLICY_IS_AUTOPLAY_ALLOWED_PER_SETTINGS
@@ -16,7 +16,7 @@ namespace brave_component_updater {
// The abstract base class for observers of the local data files service,
// which is the component that arbitrates access to various DAT files
// like tracking protection, video autoplay whitelist, etc.
// like tracking protection.
class LocalDataFilesObserver {
public:
explicit LocalDataFilesObserver(
@@ -29,7 +29,7 @@ const char kLocalDataFilesComponentBase64PublicKey[] =
"xQIDAQAB";
// The component in charge of delegating access to different DAT files
// such as tracking protection and video autoplay whitelist
// such as tracking protection.
class LocalDataFilesService : public BraveComponent {
public:
explicit LocalDataFilesService(BraveComponent::Delegate* delegate);
@@ -76,7 +76,7 @@ export class App extends React.Component<Props, State> {
}
render () {
const { walletCreated, walletCreateFailed } = this.props.rewardsData
const { walletCreated, walletCreateFailed, ui } = this.props.rewardsData
let props: {onReTry?: () => void} = {}
@@ -89,7 +89,7 @@ export class App extends React.Component<Props, State> {
return (
<div id='rewardsPage'>
{
!walletCreated
!walletCreated || ui.walletCorrupted
? <WelcomePage
optInAction={this.onCreateWalletClicked}
creating={this.state.creating}
@@ -98,7 +98,7 @@ export class App extends React.Component<Props, State> {
: null
}
{
walletCreated
walletCreated && !ui.walletCorrupted
? <SettingsPage />
: null
}
@@ -110,7 +110,13 @@ class Promotion extends React.Component<Props, State> {
return false
}
return (tokens !== '0.0' && promotion.expiresAt)
// Promotion types other than Rewards.PromotionTypes.ADS must have
// a valid expiration
if (!promotion.expiresAt && promotion.type !== 1) {
return false
}
return tokens !== '0.0'
}
render () {
@@ -26,8 +26,6 @@ source_set("browser") {
"adblock_interceptor.h",
"adblock_stub_response.cc",
"adblock_stub_response.h",
"autoplay_whitelist_service.cc",
"autoplay_whitelist_service.h",
"base_brave_shields_service.cc",
"base_brave_shields_service.h",
"brave_shields_p3a.cc",
@@ -62,7 +60,6 @@ source_set("browser") {
"//brave/components/content_settings/core/browser",
"//brave/content:common",
"//brave/vendor/adblock_rust_ffi:adblock_ffi",
"//brave/vendor/autoplay-whitelist/brave:autoplay-whitelist",
"//chrome/common",
"//components/content_settings/core/common",
"//components/content_settings/core/browser",
@@ -1,87 +0,0 @@
/* Copyright (c) 2019 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/. */
#include "brave/components/brave_shields/browser/autoplay_whitelist_service.h"
#include <utility>
#include "base/bind.h"
#include "base/task/post_task.h"
#include "base/task_runner_util.h"
#include "brave/components/brave_component_updater/browser/local_data_files_service.h"
#include "brave/vendor/autoplay-whitelist/autoplay_whitelist_parser.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
using brave_component_updater::LocalDataFilesObserver;
using brave_component_updater::LocalDataFilesService;
namespace brave_shields {
AutoplayWhitelistService::AutoplayWhitelistService(
LocalDataFilesService* local_data_files_service)
: LocalDataFilesObserver(local_data_files_service),
autoplay_whitelist_client_(new AutoplayWhitelistParser()),
weak_factory_(this) {}
AutoplayWhitelistService::~AutoplayWhitelistService() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
autoplay_whitelist_client_.reset();
}
bool AutoplayWhitelistService::ShouldAllowAutoplay(const GURL& url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// look for exact host match (this is the only way that subdomains
// listed in the autoplay whitelist will match)
if (url.has_host() &&
autoplay_whitelist_client_->matchesHost(url.host().c_str()))
return true;
// look for match of eTLD+1
std::string etld_plus_one =
net::registry_controlled_domains::GetDomainAndRegistry(
url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
return autoplay_whitelist_client_->matchesHost(etld_plus_one.c_str());
}
void AutoplayWhitelistService::OnComponentReady(
const std::string& component_id,
const base::FilePath& install_dir,
const std::string& manifest) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::FilePath dat_file_path =
install_dir.AppendASCII(AUTOPLAY_DAT_FILE_VERSION)
.AppendASCII(AUTOPLAY_DAT_FILE);
base::PostTaskAndReplyWithResult(
local_data_files_service()->GetTaskRunner().get(), FROM_HERE,
base::BindOnce(
&brave_component_updater::LoadDATFileData<AutoplayWhitelistParser>,
dat_file_path),
base::BindOnce(&AutoplayWhitelistService::OnGetDATFileData,
weak_factory_.GetWeakPtr()));
}
void AutoplayWhitelistService::OnGetDATFileData(GetDATFileDataResult result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (result.second.empty()) {
LOG(ERROR) << "Could not obtain autoplay whitelist data";
return;
}
if (!result.first.get()) {
LOG(ERROR) << "Failed to deserialize autoplay whitelist data";
return;
}
autoplay_whitelist_client_ = std::move(result.first);
buffer_ = std::move(result.second);
}
///////////////////////////////////////////////////////////////////////////////
// The autoplay whitelist factory
std::unique_ptr<AutoplayWhitelistService> AutoplayWhitelistServiceFactory(
LocalDataFilesService* local_data_files_service) {
return std::make_unique<AutoplayWhitelistService>(local_data_files_service);
}
} // namespace brave_shields
@@ -1,64 +0,0 @@
/* Copyright (c) 2019 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/. */
#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_AUTOPLAY_WHITELIST_SERVICE_H_
#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_AUTOPLAY_WHITELIST_SERVICE_H_
#include <memory>
#include <string>
#include <utility>
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "brave/components/brave_component_updater/browser/dat_file_util.h"
#include "brave/components/brave_component_updater/browser/local_data_files_observer.h"
#include "url/gurl.h"
class AutoplayWhitelistParser;
class BraveContentSettingsAgentImplAutoplayTest;
using brave_component_updater::LocalDataFilesObserver;
using brave_component_updater::LocalDataFilesService;
namespace brave_shields {
// The brave shields service in charge of autoplay whitelist
class AutoplayWhitelistService : public LocalDataFilesObserver {
public:
using GetDATFileDataResult =
brave_component_updater::LoadDATFileDataResult<AutoplayWhitelistParser>;
explicit AutoplayWhitelistService(
LocalDataFilesService* local_data_files_service);
~AutoplayWhitelistService() override;
bool ShouldAllowAutoplay(const GURL& url);
// implementation of LocalDataFilesObserver
void OnComponentReady(const std::string& component_id,
const base::FilePath& install_dir,
const std::string& manifest) override;
private:
friend class ::BraveContentSettingsAgentImplAutoplayTest;
void OnGetDATFileData(GetDATFileDataResult result);
std::unique_ptr<AutoplayWhitelistParser> autoplay_whitelist_client_;
brave_component_updater::DATFileDataBuffer buffer_;
SEQUENCE_CHECKER(sequence_checker_);
base::WeakPtrFactory<AutoplayWhitelistService> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(AutoplayWhitelistService);
};
// Creates the AutoplayWhitelistService
std::unique_ptr<AutoplayWhitelistService> AutoplayWhitelistServiceFactory(
LocalDataFilesService* local_data_files_service);
} // namespace brave_shields
#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_AUTOPLAY_WHITELIST_SERVICE_H_
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "brave-core",
"version": "1.8.16",
"version": "1.8.19",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "brave-core",
"version": "1.8.16",
"version": "1.8.19",
"description": "Brave Core is a set of changes, APIs, and scripts used for customizing Chromium to make Brave.",
"main": "index.js",
"scripts": {
+1 -1
View File
@@ -9,4 +9,4 @@ index 02faec526acf56c05150c1a87b90e3b57ddefd87..19faa8c75a86e3b39ef606ad0f62f2d7
-PATCH=132
+MINOR=1
+BUILD=8
+PATCH=16
+PATCH=19
@@ -1,5 +1,5 @@
diff --git a/third_party/blink/public/mojom/permissions/permission.mojom b/third_party/blink/public/mojom/permissions/permission.mojom
index cbd5d28c52e220e41356c704aa4b1fde018da370..231ead27186ce5a55b3de8707e0be8fe95af18a6 100644
index cbd5d28c52e220e41356c704aa4b1fde018da370..2edc5901d6b29f52847c4e447b779483c5e6119b 100644
--- a/third_party/blink/public/mojom/permissions/permission.mojom
+++ b/third_party/blink/public/mojom/permissions/permission.mojom
@@ -25,6 +25,7 @@ enum PermissionName {
@@ -10,11 +10,3 @@ index cbd5d28c52e220e41356c704aa4b1fde018da370..231ead27186ce5a55b3de8707e0be8fe
};
// This is similar to WakeLockType in modules/wake_lock/wake_lock.idl.
@@ -70,6 +71,7 @@ interface PermissionObserver {
// methods to check, request, and revoke permissions. It also allows a client to
// start listening to permission changes.
interface PermissionService {
+ [Sync]
HasPermission(PermissionDescriptor permission) => (PermissionStatus status);
RequestPermission(PermissionDescriptor permission, bool user_gesture)
=> (PermissionStatus status);
@@ -1,16 +1,8 @@
diff --git a/third_party/blink/renderer/core/html/media/autoplay_policy.cc b/third_party/blink/renderer/core/html/media/autoplay_policy.cc
index ad5f2bf069270b6ed411e937e762d4d87580a9a7..b93a088be0d14e679730db188544ed061fe3d434 100644
index ad5f2bf069270b6ed411e937e762d4d87580a9a7..837685f44f582addeb8a4eacb3af8e7f817fc7f9 100644
--- a/third_party/blink/renderer/core/html/media/autoplay_policy.cc
+++ b/third_party/blink/renderer/core/html/media/autoplay_policy.cc
@@ -137,6 +137,7 @@ bool AutoplayPolicy::DocumentHasUserExceptionFlag(const Document& document) {
// static
bool AutoplayPolicy::DocumentShouldAutoplayMutedVideos(
const Document& document) {
+ BRAVE_AUTOPLAY_POLICY_DOCUMENT_SHOULD_AUTOPLAY_MUTED_VIDEOS
return GetAutoplayPolicyForDocument(document) !=
AutoplayPolicy::Type::kNoUserGestureRequired;
}
@@ -306,10 +307,12 @@ bool AutoplayPolicy::IsGestureNeededForPlayback() const {
@@ -306,10 +306,12 @@ bool AutoplayPolicy::IsGestureNeededForPlayback() const {
if (!IsLockedPendingUserGesture())
return false;
+37 -37
View File
@@ -244,14 +244,13 @@ bool BraveContentSettingsAgentImpl::AllowAutoplay(bool default_value) {
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
auto origin = frame->GetDocument().GetSecurityOrigin();
// default allow local files
if (origin.IsNull() || origin.Protocol().Ascii() == url::kFileScheme)
return true;
bool allow = ContentSettingsAgentImpl::AllowAutoplay(default_value);
if (allow)
if (origin.IsNull() || origin.Protocol().Ascii() == url::kFileScheme) {
VLOG(1) << "AllowAutoplay=true because no origin or file scheme";
return true;
}
// respect user's site blocklist, if any
bool ask = false;
const GURL& primary_url = GetOriginOrURL(frame);
const GURL& secondary_url =
url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL();
@@ -261,42 +260,43 @@ bool BraveContentSettingsAgentImpl::AllowAutoplay(bool default_value) {
if (rule.primary_pattern.Matches(primary_url) &&
(rule.secondary_pattern == ContentSettingsPattern::Wildcard() ||
rule.secondary_pattern.Matches(secondary_url))) {
if (rule.GetContentSetting() == CONTENT_SETTING_BLOCK)
if (rule.GetContentSetting() == CONTENT_SETTING_BLOCK) {
VLOG(1) << "AllowAutoplay=false because rule=CONTENT_SETTING_BLOCK";
return false;
}
}
mojo::Remote<blink::mojom::PermissionService> permission_service;
render_frame()->GetBrowserInterfaceBroker()
->GetInterface(permission_service.BindNewPipeAndPassReceiver());
if (permission_service.get()) {
// Check (synchronously) whether we already have permission to autoplay.
// This may call the autoplay whitelist service in the UI thread, which
// we need to wait for.
auto has_permission_descriptor =
blink::mojom::PermissionDescriptor::New();
has_permission_descriptor->name =
blink::mojom::PermissionName::AUTOPLAY;
blink::mojom::blink::PermissionStatus status;
if (permission_service->HasPermission(
std::move(has_permission_descriptor), &status)) {
allow = status == blink::mojom::PermissionStatus::GRANTED;
if (!allow) {
// Request permission (asynchronously) but exit this function without
// allowing autoplay. Depending on settings and previous user choices,
// this may display visible permissions UI, or an "autoplay blocked"
// message, or nothing. In any case, we can't wait for it now.
auto request_permission_descriptor =
blink::mojom::PermissionDescriptor::New();
request_permission_descriptor->name =
blink::mojom::PermissionName::AUTOPLAY;
permission_service->RequestPermission(
std::move(request_permission_descriptor), true, base::DoNothing());
} else if (rule.GetContentSetting() == CONTENT_SETTING_ASK) {
VLOG(1) << "AllowAutoplay=ask because rule=CONTENT_SETTING_ASK";
ask = true;
}
}
}
if (ask) {
mojo::Remote<blink::mojom::PermissionService> permission_service;
render_frame()->GetBrowserInterfaceBroker()->GetInterface(
permission_service.BindNewPipeAndPassReceiver());
if (permission_service.get()) {
// Request permission (asynchronously) but exit this function without
// allowing autoplay. Depending on settings and previous user choices,
// this may display visible permissions UI, or an "autoplay blocked"
// message, or nothing. In any case, we can't wait for it now.
auto request_permission_descriptor =
blink::mojom::PermissionDescriptor::New();
request_permission_descriptor->name =
blink::mojom::PermissionName::AUTOPLAY;
permission_service->RequestPermission(
std::move(request_permission_descriptor), true, base::DoNothing());
}
return false;
}
bool allow = ContentSettingsAgentImpl::AllowAutoplay(default_value);
if (allow)
VLOG(1) << "AllowAutoplay=true because "
"ContentSettingsAgentImpl::AllowAutoplay says so";
else
VLOG(1) << "AllowAutoplay=false because "
"ContentSettingsAgentImpl::AllowAutoplay says so";
return allow;
}
@@ -6,9 +6,7 @@
#include "base/path_service.h"
#include "brave/browser/brave_browser_process_impl.h"
#include "brave/browser/brave_content_browser_client.h"
#include "brave/components/brave_shields/browser/autoplay_whitelist_service.h"
#include "brave/common/brave_paths.h"
#include "brave/vendor/autoplay-whitelist/autoplay_whitelist_parser.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/permission_bubble/mock_permission_prompt_factory.h"
@@ -47,8 +45,6 @@ class BraveContentSettingsAgentImplAutoplayTest : public InProcessBrowserTest {
ASSERT_TRUE(embedded_test_server()->Start());
g_brave_browser_process->autoplay_whitelist_service()->
autoplay_whitelist_client_->addHost("example.com");
whitelisted_url_ = embedded_test_server()->GetURL(
"example.com", "/autoplay/autoplay_by_attr.html");
-5
View File
@@ -35,11 +35,6 @@ def AddBraveCredits(prune_paths, special_cases, prune_dirs, additional_paths):
"URL": "https://github.com/brave/adblock-rust-ffi",
"License": "MPL-2.0",
},
os.path.join('brave', 'vendor', 'autoplay-whitelist'): {
"Name": "autoplay-whitelist",
"URL": "https://github.com/brave/autoplay-whitelist",
"License": "MPL-2.0",
},
os.path.join('brave', 'vendor', 'bat-native-anonize'): {
"Name": "bat-native-anonize",
"URL": "https://github.com/brave-intl/bat-native-anonize",
+1 -1
View File
@@ -8,4 +8,4 @@
# it now breaks because of urllib2 and SSL/TLS incompatibility when using Fastly
# RUST_DEPS_PACKAGES_URL = "https://rust-pkg-brave-core.s3.brave.com"
RUST_DEPS_PACKAGES_URL = "https://rust-pkg-brave-core.s3.amazonaws.com"
RUST_DEPS_PACKAGE_VERSION = "0.1.2"
RUST_DEPS_PACKAGE_VERSION = "0.1.3"
+2
View File
@@ -281,6 +281,7 @@ test("brave_unit_tests") {
"//brave/vendor/bat-native-ads/src/bat/ads/internal/client_mock.h",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/client_mock.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/filters/ads_history_confirmation_filter_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/filters/ads_history_conversion_confirmation_type_filter_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/filters/ads_history_date_range_filter_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/frequency_capping/exclusion_rules/daily_cap_frequency_cap_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/frequency_capping/exclusion_rules/per_day_frequency_cap_unittest.cc",
@@ -289,6 +290,7 @@ test("brave_unit_tests") {
"//brave/vendor/bat-native-ads/src/bat/ads/internal/frequency_capping/permission_rules/minimum_wait_time_frequency_cap_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/frequency_capping/permission_rules/ads_per_day_frequency_cap_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/frequency_capping/permission_rules/ads_per_hour_frequency_cap_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/sorts/ad_conversions_sort_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/sorts/ads_history_sort_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/purchase_intent/funnel_sites_unittest.cc",
"//brave/vendor/bat-native-ads/src/bat/ads/internal/purchase_intent/keywords_unittest.cc",
+9
View File
@@ -172,6 +172,8 @@ source_set("ads") {
"src/bat/ads/internal/filters/ads_history_filter.h",
"src/bat/ads/internal/filters/ads_history_confirmation_filter.cc",
"src/bat/ads/internal/filters/ads_history_confirmation_filter.h",
"src/bat/ads/internal/filters/ads_history_conversion_confirmation_type_filter.cc",
"src/bat/ads/internal/filters/ads_history_conversion_confirmation_type_filter.h",
"src/bat/ads/internal/filters/ads_history_date_range_filter.cc",
"src/bat/ads/internal/filters/ads_history_date_range_filter.h",
"src/bat/ads/internal/filters/ads_history_filter_factory.cc",
@@ -209,6 +211,13 @@ source_set("ads") {
"src/bat/ads/internal/search_provider_info.h",
"src/bat/ads/internal/search_providers.cc",
"src/bat/ads/internal/search_providers.h",
"src/bat/ads/internal/sorts/ad_conversions_ascending_sort.cc",
"src/bat/ads/internal/sorts/ad_conversions_ascending_sort.h",
"src/bat/ads/internal/sorts/ad_conversions_descending_sort.cc",
"src/bat/ads/internal/sorts/ad_conversions_descending_sort.h",
"src/bat/ads/internal/sorts/ad_conversions_sort_factory.cc",
"src/bat/ads/internal/sorts/ad_conversions_sort_factory.h",
"src/bat/ads/internal/sorts/ad_conversions_sort.h",
"src/bat/ads/internal/sorts/ads_history_ascending_sort.cc",
"src/bat/ads/internal/sorts/ads_history_ascending_sort.h",
"src/bat/ads/internal/sorts/ads_history_descending_sort.cc",
@@ -20,6 +20,18 @@ struct ADS_EXPORT AdConversionInfo {
const AdConversionInfo& info);
~AdConversionInfo();
bool operator==(
const AdConversionInfo& rhs) const;
bool operator!=(
const AdConversionInfo& rhs) const;
enum class SortType {
kNone = 0,
kAscendingOrder,
kDescendingOrder
};
std::string ToJson() const;
Result FromJson(
const std::string& json,
+2 -1
View File
@@ -23,7 +23,8 @@ struct ADS_EXPORT AdsHistory {
enum class FilterType {
kNone = 0,
kConfirmationType
kConfirmationType,
kAdConversionConfirmationType
};
enum class SortType {
+13
View File
@@ -16,6 +16,19 @@ AdConversionInfo::AdConversionInfo(
AdConversionInfo::~AdConversionInfo() = default;
bool AdConversionInfo::operator==(
const AdConversionInfo& rhs) const {
return creative_set_id == rhs.creative_set_id &&
type == rhs.type &&
url_pattern == rhs.url_pattern &&
observation_window == rhs.observation_window;
}
bool AdConversionInfo::operator!=(
const AdConversionInfo& rhs) const {
return !(*this == rhs);
}
std::string AdConversionInfo::ToJson() const {
std::string json;
SaveToJson(*this, &json);
+148 -38
View File
@@ -4,10 +4,15 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <algorithm>
#include <deque>
#include <memory>
#include <utility>
#include "bat/ads/internal/ad_conversions.h"
#include "bat/ads/internal/filters/ads_history_filter_factory.h"
#include "bat/ads/internal/sorts/ad_conversions_sort_factory.h"
#include "bat/ads/internal/sorts/ads_history_sort_factory.h"
#include "bat/ads/internal/uri_helper.h"
#include "bat/ads/internal/static_values.h"
#include "bat/ads/internal/logging.h"
#include "bat/ads/internal/time.h"
@@ -53,7 +58,23 @@ void AdConversions::Initialize(
LoadState();
}
void AdConversions::ProcessQueue() {
void AdConversions::Check(
const std::string& url) {
DCHECK(is_initialized_);
DCHECK(!url.empty());
if (!ads_client_->ShouldAllowAdConversionTracking()) {
return;
}
BLOG(INFO) << "Checking ad conversions for " << url;
auto callback =
std::bind(&AdConversions::OnGetAdConversions, this, url, _1, _2);
ads_client_->GetAdConversions(callback);
}
void AdConversions::StartTimerIfReady() {
DCHECK(is_initialized_);
if (timer_id_ != 0) {
@@ -69,7 +90,117 @@ void AdConversions::ProcessQueue() {
StartTimer(ad_conversion);
}
void AdConversions::AddToQueue(
bool AdConversions::OnTimer(
const uint32_t timer_id) {
if (timer_id != timer_id_) {
return false;
}
timer_id_ = 0;
DCHECK(!queue_.empty());
if (queue_.empty()) {
return true;
}
AdConversionQueueItemInfo ad_conversion = queue_.front();
ProcessQueueItem(ad_conversion);
return true;
}
///////////////////////////////////////////////////////////////////////////////
void AdConversions::OnGetAdConversions(
const std::string& url,
const Result result,
const AdConversionList& ad_conversions) {
if (result != SUCCESS) {
BLOG(ERROR) << "Failed to check ad conversions";
return;
}
std::deque<AdHistory> ads_history = client_->GetAdsShownHistory();
ads_history = FilterAdsHistory(ads_history);
ads_history = SortAdsHistory(ads_history);
AdConversionList new_ad_conversions = ad_conversions;
new_ad_conversions = FilterAdConversions(url, new_ad_conversions);
new_ad_conversions = SortAdConversions(new_ad_conversions);
for (const auto& ad_conversion : new_ad_conversions) {
for (const auto& ad : ads_history) {
auto ad_conversion_history = client_->GetAdConversionHistory();
if (ad_conversion_history.find(ad_conversion.creative_set_id) !=
ad_conversion_history.end()) {
// Creative set id has already been converted
continue;
}
if (ad_conversion.creative_set_id != ad.ad_content.creative_set_id) {
// Creative set id does not match
continue;
}
const base::Time observation_window = base::Time::Now() -
base::TimeDelta::FromDays(ad_conversion.observation_window);
const base::Time time = Time::FromDoubleT(ad.timestamp_in_seconds);
if (observation_window > time) {
// Observation window has expired
continue;
}
BLOG(INFO) << "Ad conversion for " << url << " with "
<< ad_conversion.creative_set_id << " creative set id for "
<< std::string(ad_conversion.type);
AddItemToQueue(ad.ad_content.creative_instance_id,
ad.ad_content.creative_set_id);
}
}
}
std::deque<AdHistory> AdConversions::FilterAdsHistory(
const std::deque<AdHistory>& ads_history) {
const auto filter = AdsHistoryFilterFactory::Build(
AdsHistory::FilterType::kAdConversionConfirmationType);
DCHECK(filter);
return filter->Apply(ads_history);
}
std::deque<AdHistory> AdConversions::SortAdsHistory(
const std::deque<AdHistory>& ads_history) {
const auto sort = AdsHistorySortFactory::Build(
AdsHistory::SortType::kDescendingOrder);
DCHECK(sort);
return sort->Apply(ads_history);
}
AdConversionList AdConversions::FilterAdConversions(
const std::string& url,
const AdConversionList& ad_conversions) {
AdConversionList new_ad_conversions = ad_conversions;
const auto iter = std::remove_if(new_ad_conversions.begin(),
new_ad_conversions.end(), [&](const AdConversionInfo& info) {
return !helper::Uri::MatchesWildcard(url, info.url_pattern);
});
new_ad_conversions.erase(iter, new_ad_conversions.end());
return new_ad_conversions;
}
AdConversionList AdConversions::SortAdConversions(
const AdConversionList& ad_conversions) {
const auto sort = AdConversionsSortFactory::Build(
AdConversionInfo::SortType::kDescendingOrder);
DCHECK(sort);
return sort->Apply(ad_conversions);
}
void AdConversions::AddItemToQueue(
const std::string& creative_instance_id,
const std::string& creative_set_id) {
DCHECK(is_initialized_);
@@ -102,30 +233,29 @@ void AdConversions::AddToQueue(
SaveState();
ProcessQueue();
StartTimerIfReady();
}
bool AdConversions::OnTimer(
const uint32_t timer_id) {
if (timer_id != timer_id_) {
bool AdConversions::RemoveItemFromQueue(
const std::string& creative_instance_id) {
DCHECK(is_initialized_);
auto iter = std::find_if(queue_.begin(), queue_.end(),
[&creative_instance_id] (const auto& ad_conversion) {
return ad_conversion.creative_instance_id == creative_instance_id;
});
if (iter == queue_.end()) {
return false;
}
timer_id_ = 0;
queue_.erase(iter);
DCHECK(!queue_.empty());
if (queue_.empty()) {
return true;
}
AdConversionQueueItemInfo ad_conversion = queue_.front();
ProcessQueueItem(ad_conversion);
SaveState();
return true;
}
///////////////////////////////////////////////////////////////////////////////
void AdConversions::ProcessQueueItem(
const AdConversionQueueItemInfo& info) {
const uint64_t timestamp_in_seconds = info.timestamp_in_seconds;
@@ -148,9 +278,9 @@ void AdConversions::ProcessQueueItem(
ConfirmationType::kConversion);
}
Remove(creative_instance_id);
RemoveItemFromQueue(creative_instance_id);
ProcessQueue();
StartTimerIfReady();
}
void AdConversions::StartTimer(
@@ -193,26 +323,6 @@ void AdConversions::StopTimer() {
timer_id_ = 0;
}
bool AdConversions::Remove(
const std::string& creative_instance_id) {
DCHECK(is_initialized_);
auto iter = std::find_if(queue_.begin(), queue_.end(),
[&creative_instance_id] (const auto& ad_conversion) {
return ad_conversion.creative_instance_id == creative_instance_id;
});
if (iter == queue_.end()) {
return false;
}
queue_.erase(iter);
SaveState();
return true;
}
void AdConversions::SaveState() {
if (!is_initialized_) {
return;
+25 -8
View File
@@ -6,8 +6,8 @@
#ifndef BAT_ADS_INTERNAL_AD_CONVERSION_TRACKING_H_
#define BAT_ADS_INTERNAL_AD_CONVERSION_TRACKING_H_
#include <deque>
#include <string>
#include <vector>
#include "bat/ads/ads_client.h"
#include "bat/ads/internal/ads_impl.h"
@@ -32,11 +32,10 @@ class AdConversions {
void Initialize(
InitializeCallback callback);
void ProcessQueue();
void Check(
const std::string& url);
void AddToQueue(
const std::string& creative_instance_id,
const std::string& creative_set_id);
void StartTimerIfReady();
bool OnTimer(
const uint32_t timer_id);
@@ -49,6 +48,27 @@ class AdConversions {
uint32_t timer_id_;
void OnGetAdConversions(
const std::string& url,
const Result result,
const AdConversionList& ad_conversions);
std::deque<AdHistory> FilterAdsHistory(
const std::deque<AdHistory>& ads_history);
std::deque<AdHistory> SortAdsHistory(
const std::deque<AdHistory>& ads_history);
AdConversionList FilterAdConversions(
const std::string& url,
const AdConversionList& ad_conversions);
AdConversionList SortAdConversions(
const AdConversionList& ad_conversions);
void AddItemToQueue(
const std::string& creative_instance_id,
const std::string& creative_set_id);
bool RemoveItemFromQueue(
const std::string& creative_instance_id);
void ProcessQueueItem(
const AdConversionQueueItemInfo& info);
@@ -56,9 +76,6 @@ class AdConversions {
const AdConversionQueueItemInfo& info);
void StopTimer();
bool Remove(
const std::string& creative_instance_id);
void SaveState();
void OnStateSaved(
const Result result);
+7 -73
View File
@@ -190,7 +190,7 @@ void AdsImpl::InitializeStep5(
initialize_callback_(SUCCESS);
ad_conversions_->ProcessQueue();
ad_conversions_->StartTimerIfReady();
MaybeServeAdNotification(false);
@@ -661,7 +661,11 @@ void AdsImpl::OnPageLoaded(
return;
}
CheckAdConversion(url);
const bool is_supported_url = IsSupportedUrl(url);
if (is_supported_url) {
ad_conversions_->Check(url);
}
ExtractPurchaseIntentSignal(url);
@@ -691,7 +695,7 @@ void AdsImpl::OnPageLoaded(
<< last_shown_ad_notification_.target_url;
}
if (!IsSupportedUrl(url)) {
if (!is_supported_url) {
BLOG(INFO) << "Site visited " << url << ", unsupported URL";
return;
}
@@ -744,76 +748,6 @@ void AdsImpl::GeneratePurchaseIntentSignalHistoryEntry(
}
}
void AdsImpl::CheckAdConversion(
const std::string& url) {
DCHECK(!url.empty());
if (url.empty()) {
return;
}
if (!ads_client_->ShouldAllowAdConversionTracking()) {
return;
}
auto callback = std::bind(&AdsImpl::OnGetAdConversions, this, url, _1, _2);
ads_client_->GetAdConversions(callback);
}
void AdsImpl::OnGetAdConversions(
const std::string& url,
const Result result,
const AdConversionList& ad_conversions) {
for (const auto& ad_conversion : ad_conversions) {
if (!helper::Uri::MatchesWildcard(url, ad_conversion.url_pattern)) {
continue;
}
ConfirmationType confirmation_type;
if (ad_conversion.type == "postview") {
confirmation_type = ConfirmationType::kViewed;
} else if (ad_conversion.type == "postclick") {
confirmation_type = ConfirmationType::kClicked;
} else {
BLOG(WARNING) << "Unsupported ad conversion type: " << ad_conversion.type;
continue;
}
auto ads_history = client_->GetAdsShownHistory();
const auto sort =
AdsHistorySortFactory::Build(AdsHistory::SortType::kDescendingOrder);
DCHECK(sort);
if (sort) {
ads_history = sort->Apply(ads_history);
}
for (const auto& ad : ads_history) {
auto ad_conversion_history = client_->GetAdConversionHistory();
if (ad_conversion_history.find(ad.ad_content.creative_set_id) !=
ad_conversion_history.end()) {
continue;
}
if (ad_conversion.creative_set_id != ad.ad_content.creative_set_id) {
continue;
}
if (confirmation_type != ad.ad_content.ad_action) {
continue;
}
const base::Time observation_window = base::Time::Now() -
base::TimeDelta::FromDays(ad_conversion.observation_window);
const base::Time time = Time::FromDoubleT(ad.timestamp_in_seconds);
if (observation_window > time) {
continue;
}
ad_conversions_->AddToQueue(ad.ad_content.creative_instance_id,
ad.ad_content.creative_set_id);
}
}
}
void AdsImpl::MaybeClassifyPage(
const std::string& url,
const std::string& content) {
-7
View File
@@ -195,13 +195,6 @@ class AdsImpl : public Ads {
void CheckEasterEgg(
const std::string& url);
void CheckAdConversion(
const std::string& url);
void OnGetAdConversions(
const std::string& url,
const Result result,
const AdConversionList& ad_conversions);
void MaybeServeAdNotification(
const bool should_serve);
void ServeAdNotificationIfReady(
@@ -0,0 +1,55 @@
/* Copyright (c) 2020 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/. */
#include <algorithm>
#include <map>
#include <string>
#include "bat/ads/internal/filters/ads_history_conversion_confirmation_type_filter.h" // NOLINT
#include "bat/ads/ads_history.h"
namespace ads {
AdsHistoryConversionConfirmationTypeFilter::
AdsHistoryConversionConfirmationTypeFilter() = default;
AdsHistoryConversionConfirmationTypeFilter::
~AdsHistoryConversionConfirmationTypeFilter() = default;
std::deque<AdHistory> AdsHistoryConversionConfirmationTypeFilter::Apply(
const std::deque<AdHistory>& history) const {
std::deque<AdHistory> ads = history;
const auto iter = std::remove_if(ads.begin(), ads.end(),
[this](const AdHistory& ad) {
return ShouldFilterConfirmationType(ad.ad_content.ad_action);
});
ads.erase(iter, ads.end());
return ads;
}
bool AdsHistoryConversionConfirmationTypeFilter::ShouldFilterConfirmationType(
const ConfirmationType& type) const {
switch (type.value()) {
case ConfirmationType::kClicked:
case ConfirmationType::kViewed: {
return false;
}
case ConfirmationType::kNone:
case ConfirmationType::kDismissed:
case ConfirmationType::kLanded:
case ConfirmationType::kFlagged:
case ConfirmationType::kUpvoted:
case ConfirmationType::kDownvoted:
case ConfirmationType::kConversion: {
return true;
}
}
}
} // namespace ads
@@ -0,0 +1,33 @@
/* Copyright (c) 2019 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/. */
#ifndef BAT_ADS_INTERNAL_ADS_HISTORY_CONVERSION_CONFIRMATION_TYPE_FILTER_H_
#define BAT_ADS_INTERNAL_ADS_HISTORY_CONVERSION_CONFIRMATION_TYPE_FILTER_H_
#include <deque>
#include "bat/ads/internal/filters/ads_history_filter.h"
namespace ads {
struct AdsHistory;
class ConfirmationType;
class AdsHistoryConversionConfirmationTypeFilter : public AdsHistoryFilter {
public:
AdsHistoryConversionConfirmationTypeFilter();
~AdsHistoryConversionConfirmationTypeFilter() override;
std::deque<AdHistory> Apply(
const std::deque<AdHistory>& history) const override;
private:
bool ShouldFilterConfirmationType(
const ConfirmationType& type) const;
};
} // namespace ads
#endif // BAT_ADS_INTERNAL_ADS_HISTORY_CONVERSION_CONFIRMATION_TYPE_FILTER_H_
@@ -0,0 +1,156 @@
/* Copyright (c) 2019 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/. */
#include <deque>
#include <memory>
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "bat/ads/internal/filters/ads_history_conversion_confirmation_type_filter.h" // NOLINT
#include "bat/ads/internal/client_mock.h"
#include "bat/ads/internal/ads_client_mock.h"
#include "bat/ads/internal/ads_impl.h"
// npm run test -- brave_unit_tests --filter=BatAds*
using std::placeholders::_1;
using ::testing::_;
using ::testing::Invoke;
namespace ads {
class BatAdsHistoryConversionConfirmationTypeFilterTest
: public ::testing::Test {
protected:
BatAdsHistoryConversionConfirmationTypeFilterTest()
: mock_ads_client_(std::make_unique<MockAdsClient>()),
ads_(std::make_unique<AdsImpl>(mock_ads_client_.get())) {
// You can do set-up work for each test here
}
~BatAdsHistoryConversionConfirmationTypeFilterTest() override {
// You can do clean-up work that doesn't throw exceptions here
}
// If the constructor and destructor are not enough for setting up and
// cleaning up each test, you can use the following methods
void SetUp() override {
// Code here will be called immediately after the constructor (right before
// each test)
auto callback = std::bind(
&BatAdsHistoryConversionConfirmationTypeFilterTest::OnAdsImplInitialize,
this, _1);
ads_->Initialize(callback);
ads_history_filter_ =
std::make_unique<AdsHistoryConversionConfirmationTypeFilter>();
}
void OnAdsImplInitialize(const Result result) {
EXPECT_EQ(Result::SUCCESS, result);
}
void TearDown() override {
// Code here will be called immediately after each test (right before the
// destructor)
}
bool CompareUnsortedAdsHistory(
const std::deque<AdHistory> a,
const std::deque<AdHistory> b) const {
const size_t n = a.size();
if (b.size() != n) {
return false;
}
std::vector<bool> visited(n, false);
size_t j;
for (size_t i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (a[i] == b[j] && !visited[j]) {
visited[j] = true;
break;
}
}
if (j == n) {
return false;
}
}
return true;
}
std::unique_ptr<MockAdsClient> mock_ads_client_;
std::unique_ptr<AdsImpl> ads_;
std::unique_ptr<AdsHistoryFilter> ads_history_filter_;
};
TEST_F(BatAdsHistoryConversionConfirmationTypeFilterTest,
FilterUnsupportedActions) {
// Arrange
AdHistory ad1;
ad1.parent_uuid = "69b684d7-d893-4f4e-b156-859919a0fcc9";
ad1.ad_content.ad_action = ConfirmationType::kLanded; // Unsupported
AdHistory ad2;
ad2.parent_uuid = "d3be2e79-ffa8-4b4e-b61e-88545055fbad";
ad2.ad_content.ad_action = ConfirmationType::kFlagged; // Unsupported
AdHistory ad3;
ad3.parent_uuid = "9390f66a-d4f2-4c8a-8315-1baed4aae612";
ad3.ad_content.ad_action = ConfirmationType::kUpvoted; // Unsupported
AdHistory ad4;
ad4.parent_uuid = "47c73793-d1c1-4fdb-8530-4ae478c79783";
ad4.ad_content.ad_action = ConfirmationType::kDownvoted; // Unsupported
AdHistory ad5;
ad5.parent_uuid = "b7e1314c-73b0-4291-9cdd-6c5d2374c28f";
ad5.ad_content.ad_action = ConfirmationType::kConversion; // Unsupported
AdHistory ad6;
ad6.parent_uuid = "ab9deba5-01bf-492b-9bb8-7bc4318fe272";
ad6.ad_content.ad_action = ConfirmationType::kViewed; // Ad 1 (Viewed)
AdHistory ad7;
ad7.parent_uuid = "5da2f2b3-85ca-4ba3-b879-634c5da9bdc6";
ad7.ad_content.ad_action = ConfirmationType::kDismissed; // Unsupported
AdHistory ad8;
ad8.parent_uuid = "ab9deba5-01bf-492b-9bb8-7bc4318fe272";
ad8.ad_content.ad_action = ConfirmationType::kClicked; // Ad 1 (Clicked)
const std::deque<AdHistory> ads_history = {
ad1,
ad2,
ad3,
ad4,
ad5,
ad6,
ad7,
ad8
};
// Act
const std::deque<AdHistory> ads_history_filtered =
ads_history_filter_->Apply(ads_history);
// Assert
const std::deque<AdHistory> expected_ads_history = {
ad6, // Ad 1 (Viewed)
ad8 // Ad 1 (Clicked)
};
EXPECT_TRUE(CompareUnsortedAdsHistory(expected_ads_history,
ads_history_filtered));
}
} // namespace ads
@@ -6,6 +6,7 @@
#include "bat/ads/internal/filters/ads_history_filter_factory.h"
#include "bat/ads/internal/filters/ads_history_date_range_filter.h"
#include "bat/ads/internal/filters/ads_history_confirmation_filter.h"
#include "bat/ads/internal/filters/ads_history_conversion_confirmation_type_filter.h" // NOLINT
namespace ads {
@@ -19,6 +20,10 @@ std::unique_ptr<AdsHistoryFilter> AdsHistoryFilterFactory::Build(
case AdsHistory::FilterType::kConfirmationType: {
return std::make_unique<AdsHistoryConfirmationFilter>();
}
case AdsHistory::FilterType::kAdConversionConfirmationType: {
return std::make_unique<AdsHistoryConversionConfirmationTypeFilter>();
}
}
}
@@ -0,0 +1,28 @@
/* Copyright (c) 2020 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/. */
#include <algorithm>
#include "bat/ads/internal/sorts/ad_conversions_ascending_sort.h"
namespace ads {
AdConversionsAscendingSort::AdConversionsAscendingSort() = default;
AdConversionsAscendingSort::~AdConversionsAscendingSort() = default;
AdConversionList AdConversionsAscendingSort::Apply(
const AdConversionList& list) const {
auto sorted_list = list;
std::sort(sorted_list.begin(), sorted_list.end(),
[](const AdConversionInfo& a, const AdConversionInfo& b) {
return a.type == "postview" && b.type == "postclick";
});
return sorted_list;
}
} // namespace ads
@@ -0,0 +1,24 @@
/* Copyright (c) 2020 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/. */
#ifndef BAT_ADS_INTERNAL_AD_CONVERSIONS_ASCENDING_SORT_H_
#define BAT_ADS_INTERNAL_AD_CONVERSIONS_ASCENDING_SORT_H_
#include "bat/ads/internal/sorts/ad_conversions_sort.h"
namespace ads {
class AdConversionsAscendingSort : public AdConversionsSort {
public :
AdConversionsAscendingSort();
~AdConversionsAscendingSort() override;
AdConversionList Apply(
const AdConversionList& list) const override;
};
} // namespace ads
#endif // BAT_ADS_INTERNAL_AD_CONVERSIONS_ASCENDING_SORT_H_
@@ -0,0 +1,28 @@
/* Copyright (c) 2020 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/. */
#include <algorithm>
#include "bat/ads/internal/sorts/ad_conversions_descending_sort.h"
namespace ads {
AdConversionsDescendingSort::AdConversionsDescendingSort() = default;
AdConversionsDescendingSort::~AdConversionsDescendingSort() = default;
AdConversionList AdConversionsDescendingSort::Apply(
const AdConversionList& list) const {
auto sorted_list = list;
std::sort(sorted_list.begin(), sorted_list.end(),
[](const AdConversionInfo& a, const AdConversionInfo& b) {
return a.type == "postclick" && b.type == "postview";
});
return sorted_list;
}
} // namespace ads
@@ -0,0 +1,24 @@
/* Copyright (c) 2020 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/. */
#ifndef BAT_ADS_INTERNAL_AD_CONVERSIONS_DESCENDING_SORT_H_
#define BAT_ADS_INTERNAL_AD_CONVERSIONS_DESCENDING_SORT_H_
#include "bat/ads/internal/sorts/ad_conversions_sort.h"
namespace ads {
class AdConversionsDescendingSort : public AdConversionsSort {
public :
AdConversionsDescendingSort();
~AdConversionsDescendingSort() override;
AdConversionList Apply(
const AdConversionList& list) const override;
};
} // namespace ads
#endif // BAT_ADS_INTERNAL_AD_CONVERSIONS_DESCENDING_SORT_H_
@@ -0,0 +1,23 @@
/* Copyright (c) 2020 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/. */
#ifndef BAT_ADS_INTERNAL_AD_CONVERSIONS_SORT_H_
#define BAT_ADS_INTERNAL_AD_CONVERSIONS_SORT_H_
#include "bat/ads/ad_conversion_info.h"
namespace ads {
class AdConversionsSort {
public:
virtual ~AdConversionsSort() = default;
virtual AdConversionList Apply(
const AdConversionList& ad_conversions) const = 0;
};
} // namespace ads
#endif // BAT_ADS_INTERNAL_AD_CONVERSIONS_SORT_H_
@@ -0,0 +1,29 @@
/* Copyright (c) 2020 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/. */
#include "bat/ads/internal/sorts/ad_conversions_sort_factory.h"
#include "bat/ads/internal/sorts/ad_conversions_ascending_sort.h"
#include "bat/ads/internal/sorts/ad_conversions_descending_sort.h"
namespace ads {
std::unique_ptr<AdConversionsSort> AdConversionsSortFactory::Build(
const AdConversionInfo::SortType type) {
switch (type) {
case AdConversionInfo::SortType::kNone: {
return nullptr;
}
case AdConversionInfo::SortType::kAscendingOrder: {
return std::make_unique<AdConversionsAscendingSort>();
}
case AdConversionInfo::SortType::kDescendingOrder: {
return std::make_unique<AdConversionsDescendingSort>();
}
}
}
} // namespace ads
@@ -0,0 +1,23 @@
/* Copyright (c) 2020 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/. */
#ifndef BAT_ADS_INTERNAL_AD_CONVERSIONS_SORT_FACTORY_H_
#define BAT_ADS_INTERNAL_AD_CONVERSIONS_SORT_FACTORY_H_
#include <memory>
#include "bat/ads/internal/sorts/ad_conversions_sort.h"
namespace ads {
class AdConversionsSortFactory {
public:
static std::unique_ptr<AdConversionsSort> Build(
const AdConversionInfo::SortType type);
};
} // namespace ads
#endif // BAT_ADS_INTERNAL_AD_CONVERSIONS_SORT_FACTORY_H_
@@ -0,0 +1,180 @@
/* Copyright (c) 2020 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/. */
#include "bat/ads/internal/sorts/ad_conversions_sort_factory.h"
#include "bat/ads/internal/client_mock.h"
#include "bat/ads/internal/ads_client_mock.h"
#include "bat/ads/internal/ads_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
// npm run test -- brave_unit_tests --filter=BatAds*
using std::placeholders::_1;
namespace ads {
class BatAdConversionsSortTest : public ::testing::Test {
protected:
BatAdConversionsSortTest()
: mock_ads_client_(std::make_unique<MockAdsClient>()),
ads_(std::make_unique<AdsImpl>(mock_ads_client_.get())) {
// You can do set-up work for each test here
}
~BatAdConversionsSortTest() override {
// You can do clean-up work that doesn't throw exceptions here
}
// If the constructor and destructor are not enough for setting up and
// cleaning up each test, you can use the following methods
void SetUp() override {
// Code here will be called immediately after the constructor (right before
// each test)
auto callback = std::bind(
&BatAdConversionsSortTest::OnAdsImplInitialize, this, _1);
ads_->Initialize(callback);
client_mock_ =
std::make_unique<ClientMock>(ads_.get(), mock_ads_client_.get());
}
void TearDown() override {
// Code here will be called immediately after each test (right before the
// destructor)
}
void OnAdsImplInitialize(const Result result) {
EXPECT_EQ(Result::SUCCESS, result);
}
AdConversionList GetUnsortedAdConversions() {
AdConversionList list;
AdConversionInfo info;
info.type = "postview";
list.push_back(info);
info.type = "postclick";
list.push_back(info);
info.type = "postview";
list.push_back(info);
info.type = "postclick";
list.push_back(info);
info.type = "postview";
list.push_back(info);
return list;
}
std::unique_ptr<MockAdsClient> mock_ads_client_;
std::unique_ptr<AdsImpl> ads_;
std::unique_ptr<ClientMock> client_mock_;
};
TEST_F(BatAdConversionsSortTest,
NoSortOrder) {
// Arrange
// Act
const auto sort =
AdConversionsSortFactory::Build(AdConversionInfo::SortType::kNone);
// Assert
ASSERT_EQ(sort, nullptr);
}
TEST_F(BatAdConversionsSortTest,
DescendingSortOrder) {
// Arrange
AdConversionList list = GetUnsortedAdConversions();
const auto sort = AdConversionsSortFactory::Build(
AdConversionInfo::SortType::kDescendingOrder);
// Act
list = sort->Apply(list);
// Assert
AdConversionList expected_list;
AdConversionInfo info;
info.type = "postclick";
expected_list.push_back(info);
info.type = "postclick";
expected_list.push_back(info);
info.type = "postview";
expected_list.push_back(info);
info.type = "postview";
expected_list.push_back(info);
info.type = "postview";
expected_list.push_back(info);
ASSERT_EQ(expected_list, list);
}
TEST_F(BatAdConversionsSortTest,
DescendingSortOrderForEmptyList) {
// Arrange
const auto sort = AdConversionsSortFactory::Build(
AdConversionInfo::SortType::kDescendingOrder);
AdConversionList list;
// Act
list = sort->Apply(list);
// Assert
AdConversionList expected_list;
ASSERT_EQ(expected_list, list);
}
TEST_F(BatAdConversionsSortTest,
AscendingSortOrder) {
// Arrange
AdConversionList list = GetUnsortedAdConversions();
const auto sort = AdConversionsSortFactory::Build(
AdConversionInfo::SortType::kAscendingOrder);
// Act
list = sort->Apply(list);
// Assert
AdConversionList expected_list;
AdConversionInfo info;
info.type = "postview";
expected_list.push_back(info);
info.type = "postview";
expected_list.push_back(info);
info.type = "postview";
expected_list.push_back(info);
info.type = "postclick";
expected_list.push_back(info);
info.type = "postclick";
expected_list.push_back(info);
ASSERT_EQ(expected_list, list);
}
TEST_F(BatAdConversionsSortTest,
AscendingSortOrderForEmptyList) {
// Arrange
const auto sort = AdConversionsSortFactory::Build(
AdConversionInfo::SortType::kAscendingOrder);
AdConversionList list;
// Act
list = sort->Apply(list);
// Assert
AdConversionList expected_list;
ASSERT_EQ(expected_list, list);
}
} // namespace ads