diff --git a/browser/brave_ads/BUILD.gn b/browser/brave_ads/BUILD.gn index 789f58bc74d7..b1f5bb9f9a83 100644 --- a/browser/brave_ads/BUILD.gn +++ b/browser/brave_ads/BUILD.gn @@ -67,6 +67,7 @@ source_set("impl") { "//chrome/browser:browser_process", "//chrome/browser:browser_public_dependencies", "//chrome/browser:primitives", + "//chrome/browser/content_settings:content_settings_factory", "//chrome/browser/profiles:profile", "//chrome/browser/regional_capabilities", "//chrome/browser/ui", diff --git a/browser/brave_ads/ads_service_factory.cc b/browser/brave_ads/ads_service_factory.cc index adfbda348c45..ed4adb05a21c 100644 --- a/browser/brave_ads/ads_service_factory.cc +++ b/browser/brave_ads/ads_service_factory.cc @@ -22,6 +22,7 @@ #include "brave/components/brave_ads/browser/ads_service_impl.h" #include "brave/components/brave_ads/core/browser/service/ads_service.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/notifications/notification_display_service_factory.h" @@ -98,7 +99,7 @@ AdsServiceFactory::BuildServiceInstanceForBrowserContext( std::make_unique(), std::make_unique(), g_brave_browser_process->resource_component(), history_service, - rewards_service); + rewards_service, HostContentSettingsMapFactory::GetForProfile(profile)); } bool AdsServiceFactory::ServiceIsNULLWhileTesting() const { diff --git a/browser/ntp_background/BUILD.gn b/browser/ntp_background/BUILD.gn index 190ee39cbe8e..f0130f45b830 100644 --- a/browser/ntp_background/BUILD.gn +++ b/browser/ntp_background/BUILD.gn @@ -28,6 +28,7 @@ source_set("ntp_background") { "//brave/components/ntp_background_images/buildflags", "//brave/components/p3a", "//chrome/browser:browser_process", + "//chrome/browser/content_settings:content_settings_factory", "//chrome/browser/profiles:profile", "//components/keyed_service/content", "//components/pref_registry", diff --git a/browser/ntp_background/android/ntp_background_images_bridge.cc b/browser/ntp_background/android/ntp_background_images_bridge.cc index 48eeb74cf186..e6daec923827 100644 --- a/browser/ntp_background/android/ntp_background_images_bridge.cc +++ b/browser/ntp_background/android/ntp_background_images_bridge.cc @@ -283,8 +283,9 @@ void NTPBackgroundImagesBridge::OnBackgroundImagesDataDidUpdate( void NTPBackgroundImagesBridge::OnSponsoredImagesDataDidUpdate( NTPSponsoredImagesData* data) { // Don't have interest about in-effective component data update. - if (data != view_counter_service_->GetCurrentBrandedWallpaperData()) + if (data != view_counter_service_->GetSponsoredImagesData()) { return; + } JNIEnv* env = AttachCurrentThread(); Java_NTPBackgroundImagesBridge_onUpdated(env, java_object_); diff --git a/browser/ntp_background/ntp_p3a_helper_impl.cc b/browser/ntp_background/ntp_p3a_helper_impl.cc index 14aa8bc47ff8..450d142cb510 100644 --- a/browser/ntp_background/ntp_p3a_helper_impl.cc +++ b/browser/ntp_background/ntp_p3a_helper_impl.cc @@ -136,13 +136,13 @@ NTPP3AHelperImpl::NTPP3AHelperImpl( &NTPP3AHelperImpl::OnP3ARotation, base::Unretained(this))); if (ntp_background_images_service) { if (const auto* sr_data = - ntp_background_images_service->GetBrandedImagesData( - /*super_referral=*/true)) { + ntp_background_images_service->GetSponsoredImagesData( + /*super_referral=*/true, /*supports_rich_media=*/true)) { CheckLoadedCampaigns(*sr_data); } if (const auto* si_data = - ntp_background_images_service->GetBrandedImagesData( - /*super_referral=*/false)) { + ntp_background_images_service->GetSponsoredImagesData( + /*super_referral=*/false, /*supports_rich_media=*/true)) { CheckLoadedCampaigns(*si_data); } ntp_background_images_service_observation_.Observe( diff --git a/browser/ntp_background/view_counter_service_factory.cc b/browser/ntp_background/view_counter_service_factory.cc index 38aa255df961..96be047147b0 100644 --- a/browser/ntp_background/view_counter_service_factory.cc +++ b/browser/ntp_background/view_counter_service_factory.cc @@ -20,6 +20,7 @@ #include "brave/components/ntp_background_images/browser/view_counter_service.h" #include "brave/components/ntp_background_images/buildflags/buildflags.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" @@ -78,9 +79,9 @@ ViewCounterServiceFactory::BuildServiceInstanceForBrowserContext( browser_context, std::make_unique(service)); content::URLDataSource::Add( browser_context, std::make_unique(service)); - content::URLDataSource::Add( - browser_context, - std::make_unique(service)); + content::URLDataSource::Add(browser_context, + std::make_unique( + service, profile->GetPrefs())); std::unique_ptr ntp_p3a_helper; if (g_brave_browser_process->p3a_service() != nullptr) { @@ -92,7 +93,7 @@ ViewCounterServiceFactory::BuildServiceInstanceForBrowserContext( } return std::make_unique( - service, + HostContentSettingsMapFactory::GetForProfile(profile), service, #if BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) BraveNTPCustomBackgroundServiceFactory::GetForContext(profile), #else diff --git a/components/brave_ads/browser/BUILD.gn b/components/brave_ads/browser/BUILD.gn index e5f32c3b07dd..c8db4a312cbd 100644 --- a/components/brave_ads/browser/BUILD.gn +++ b/components/brave_ads/browser/BUILD.gn @@ -40,6 +40,7 @@ static_library("browser") { "//brave/components/ntp_background_images/common", "//brave/components/p3a_utils", "//brave/components/time_period_storage", + "//components/content_settings/core/browser", "//components/pref_registry", "//components/prefs", "//components/sessions", diff --git a/components/brave_ads/browser/ads_service_impl.cc b/components/brave_ads/browser/ads_service_impl.cc index 3b3600cac91b..b10c12637c31 100644 --- a/components/brave_ads/browser/ads_service_impl.cc +++ b/components/brave_ads/browser/ads_service_impl.cc @@ -61,6 +61,9 @@ #include "brave/components/ntp_background_images/common/pref_names.h" #include "brave/components/services/bat_ads/public/interfaces/bat_ads.mojom.h" #include "build/build_config.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings.h" +#include "components/content_settings/core/common/content_settings_pattern.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" @@ -194,13 +197,15 @@ AdsServiceImpl::AdsServiceImpl( std::unique_ptr bat_ads_service_factory, brave_ads::ResourceComponent* resource_component, history::HistoryService* history_service, - brave_rewards::RewardsService* rewards_service) + brave_rewards::RewardsService* rewards_service, + HostContentSettingsMap* host_content_settings_map) : AdsService(std::move(delegate)), prefs_(prefs), local_state_(local_state), url_loader_(std::move(url_loader)), channel_name_(channel_name), history_service_(history_service), + host_content_settings_map_(host_content_settings_map), ads_tooltips_delegate_(std::move(ads_tooltips_delegate)), device_id_(std::move(device_id)), bat_ads_service_factory_(std::move(bat_ads_service_factory)), @@ -485,6 +490,8 @@ void AdsServiceImpl::InitializeBatAdsCallback(bool success) { BackgroundHelper::GetInstance()->AddObserver(this); + host_content_settings_map_->AddObserver(this); + MaybeShowOnboardingNotification(); MaybeOpenNewTabWithAd(); @@ -599,6 +606,25 @@ void AdsServiceImpl::SetFlags() { bat_ads_associated_remote_->SetFlags(std::move(mojom_flags)); } +void AdsServiceImpl::SetContentSettings() { + if (!bat_ads_associated_remote_.is_bound()) { + return; + } + + const ContentSetting javascript_content_setting = + host_content_settings_map_->GetDefaultContentSetting( + ContentSettingsType::JAVASCRIPT); + + mojom::ContentSettingsPtr mojom_content_settings = + mojom::ContentSettings::New(); + mojom_content_settings->allow_javascript = + javascript_content_setting == CONTENT_SETTING_ALLOW || + javascript_content_setting == CONTENT_SETTING_SESSION_ONLY; + + bat_ads_associated_remote_->SetContentSettings( + std::move(mojom_content_settings)); +} + bool AdsServiceImpl::ShouldShowOnboardingNotification() { const bool should_show_onboarding_notification = prefs_->GetBoolean(prefs::kShouldShowOnboardingNotification); @@ -1103,6 +1129,8 @@ void AdsServiceImpl::ShutdownAdsService() { if (is_bat_ads_initialized_) { BackgroundHelper::GetInstance()->RemoveObserver(this); + + host_content_settings_map_->RemoveObserver(this); } CloseAllNotificationAds(); @@ -1275,7 +1303,7 @@ void AdsServiceImpl::PrefetchNewTabPageAd() { } std::optional -AdsServiceImpl::MaybeGetPrefetchedNewTabPageAdForDisplay() { +AdsServiceImpl::MaybeGetPrefetchedNewTabPageAd() { if (!bat_ads_associated_remote_.is_bound()) { return std::nullopt; } @@ -1299,7 +1327,7 @@ void AdsServiceImpl::OnFailedToPrefetchNewTabPageAd( } void AdsServiceImpl::ParseAndSaveCreativeNewTabPageAds( - const base::Value::Dict& data, + const base::Value::Dict& dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) { if (!bat_ads_associated_remote_.is_bound()) { return std::move(callback).Run(/*success*/ false); @@ -1308,7 +1336,7 @@ void AdsServiceImpl::ParseAndSaveCreativeNewTabPageAds( // Since `data` contains small JSON from a CRX component, cloning it has // no performance impact. bat_ads_associated_remote_->ParseAndSaveCreativeNewTabPageAds( - data.Clone(), std::move(callback)); + dict.Clone(), std::move(callback)); } void AdsServiceImpl::TriggerNewTabPageAdEvent( @@ -1895,4 +1923,14 @@ void AdsServiceImpl::OnCompleteReset(bool success) { } } +void AdsServiceImpl::OnContentSettingChanged( + const ContentSettingsPattern& /*primary_pattern*/, + const ContentSettingsPattern& /*secondary_pattern*/, + ContentSettingsTypeSet content_type_set) { + if (content_type_set.Contains(ContentSettingsType::JAVASCRIPT)) { + SetContentSettings(); + PrefetchNewTabPageAd(); + } +} + } // namespace brave_ads diff --git a/components/brave_ads/browser/ads_service_impl.h b/components/brave_ads/browser/ads_service_impl.h index 33f1affa4196..f7a8ac5e16b7 100644 --- a/components/brave_ads/browser/ads_service_impl.h +++ b/components/brave_ads/browser/ads_service_impl.h @@ -30,6 +30,9 @@ #include "brave/components/brave_ads/core/public/service/ads_service_callback.h" #include "brave/components/brave_rewards/core/mojom/rewards.mojom-forward.h" #include "brave/components/services/bat_ads/public/interfaces/bat_ads.mojom.h" +#include "components/content_settings/core/browser/content_settings_observer.h" +#include "components/content_settings/core/browser/content_settings_type_set.h" +#include "components/content_settings/core/common/content_settings_pattern.h" #include "components/history/core/browser/history_service.h" #include "components/prefs/pref_change_registrar.h" #include "mojo/public/cpp/bindings/associated_receiver.h" @@ -39,6 +42,7 @@ #include "ui/base/idle/idle.h" class GURL; +class HostContentSettingsMap; class PrefService; namespace base { @@ -69,7 +73,8 @@ class AdsServiceImpl final : public AdsService, public bat_ads::mojom::BatAdsObserver, BackgroundHelper::Observer, public ResourceComponentObserver, - public brave_rewards::RewardsServiceObserver { + public brave_rewards::RewardsServiceObserver, + public content_settings::Observer { public: explicit AdsServiceImpl( std::unique_ptr delegate, @@ -83,7 +88,8 @@ class AdsServiceImpl final : public AdsService, std::unique_ptr bat_ads_service_factory, brave_ads::ResourceComponent* resource_component, history::HistoryService* history_service, - brave_rewards::RewardsService* rewards_service); + brave_rewards::RewardsService* rewards_service, + HostContentSettingsMap* host_content_settings); AdsServiceImpl(const AdsServiceImpl&) = delete; AdsServiceImpl& operator=(const AdsServiceImpl&) = delete; @@ -145,6 +151,7 @@ class AdsServiceImpl final : public AdsService, void SetSysInfo(); void SetBuildChannel(); void SetFlags(); + void SetContentSettings(); bool ShouldShowOnboardingNotification(); void MaybeShowOnboardingNotification(); @@ -243,14 +250,13 @@ class AdsServiceImpl final : public AdsService, mojom::InlineContentAdEventType mojom_ad_event_type, TriggerAdEventCallback callback) override; - std::optional MaybeGetPrefetchedNewTabPageAdForDisplay() - override; + std::optional MaybeGetPrefetchedNewTabPageAd() override; void PrefetchNewTabPageAd() override; void OnFailedToPrefetchNewTabPageAd( const std::string& placement_id, const std::string& creative_instance_id) override; void ParseAndSaveCreativeNewTabPageAds( - const base::Value::Dict& data, + const base::Value::Dict& dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) override; void TriggerNewTabPageAdEvent( const std::string& placement_id, @@ -406,6 +412,12 @@ class AdsServiceImpl final : public AdsService, void OnExternalWalletConnected() override; void OnCompleteReset(bool success) override; + // content_settings::Observer: + void OnContentSettingChanged( + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsTypeSet content_type_set) override; + bool is_bat_ads_initialized_ = false; bool is_shutting_down_ = false; @@ -455,6 +467,9 @@ class AdsServiceImpl final : public AdsService, const raw_ptr history_service_ = nullptr; // Not owned. + const raw_ptr host_content_settings_map_ = + nullptr; // Not owned. + const std::unique_ptr ads_tooltips_delegate_; const std::unique_ptr device_id_; diff --git a/components/brave_ads/browser/ads_service_mock.h b/components/brave_ads/browser/ads_service_mock.h index 4af45bed0970..6195a692ff31 100644 --- a/components/brave_ads/browser/ads_service_mock.h +++ b/components/brave_ads/browser/ads_service_mock.h @@ -57,7 +57,7 @@ class AdsServiceMock : public AdsService { TriggerAdEventCallback)); MOCK_METHOD(std::optional, - MaybeGetPrefetchedNewTabPageAdForDisplay, + MaybeGetPrefetchedNewTabPageAd, ()); MOCK_METHOD(void, PrefetchNewTabPageAd, ()); MOCK_METHOD(void, @@ -71,7 +71,7 @@ class AdsServiceMock : public AdsService { (const std::string&, const std::string&)); MOCK_METHOD(void, ParseAndSaveCreativeNewTabPageAds, - (const base::Value::Dict& data, + (const base::Value::Dict& dict, ParseAndSaveCreativeNewTabPageAdsCallback)); MOCK_METHOD(void, diff --git a/components/brave_ads/core/browser/service/ads_service.h b/components/brave_ads/core/browser/service/ads_service.h index 8529d7e1a39e..7b89b46e0222 100644 --- a/components/brave_ads/core/browser/service/ads_service.h +++ b/components/brave_ads/core/browser/service/ads_service.h @@ -130,8 +130,7 @@ class AdsService : public KeyedService { virtual void PrefetchNewTabPageAd() = 0; // Called to get the prefetched new tab page ad for display. - virtual std::optional - MaybeGetPrefetchedNewTabPageAdForDisplay() = 0; + virtual std::optional MaybeGetPrefetchedNewTabPageAd() = 0; // Called when failing to prefetch a new tab page ad for the specified // `placement_id` and `creative_instance_id`. @@ -142,7 +141,7 @@ class AdsService : public KeyedService { // Called to parse and save creative new tab page ads. The callback takes one // argument - `bool` is set to `true` if successful otherwise `false`. virtual void ParseAndSaveCreativeNewTabPageAds( - const base::Value::Dict& data, + const base::Value::Dict& dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) = 0; // Called when a user views or interacts with a new tab page ad to trigger a diff --git a/components/brave_ads/core/internal/BUILD.gn b/components/brave_ads/core/internal/BUILD.gn index 5d0b595fb760..fb6dcf2c93c2 100644 --- a/components/brave_ads/core/internal/BUILD.gn +++ b/components/brave_ads/core/internal/BUILD.gn @@ -500,6 +500,8 @@ static_library("internal") { "common/url/url_util.cc", "common/url/url_util_internal.cc", "common/url/url_util_internal.h", + "content_settings/content_settings_util.cc", + "content_settings/content_settings_util.h", "creatives/campaigns_database_table.cc", "creatives/campaigns_database_table.h", "creatives/conversions/creative_set_conversion_builder.cc", @@ -540,6 +542,10 @@ static_library("internal") { "creatives/inline_content_ads/inline_content_ad_builder.h", "creatives/new_tab_page_ads/creative_new_tab_page_ad_info.cc", "creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h", + "creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h", + "creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_constants.h", + "creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.cc", + "creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h", "creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.cc", "creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.h", "creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.cc", diff --git a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_info_unittest.cc b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_info_unittest.cc index e63a6e6fa33f..381e2e570ee4 100644 --- a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_info_unittest.cc +++ b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_info_unittest.cc @@ -8,6 +8,7 @@ #include "brave/components/brave_ads/core/internal/common/test/test_base.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/new_tab_page_ad_builder.h" // npm run test -- brave_unit_tests --filter=BraveAds* @@ -19,7 +20,8 @@ class BraveAdsNewTabPageAdInfoTest : public test::TestBase {}; TEST_F(BraveAdsNewTabPageAdInfoTest, IsValid) { // Arrange const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); const NewTabPageAdInfo ad = BuildNewTabPageAd(creative_ad); // Act & Assert diff --git a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test.cc b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test.cc index 41fd1345ad67..12a61248075b 100644 --- a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test.cc +++ b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test.cc @@ -116,8 +116,8 @@ class BraveAdsNewTabPageAdIntegrationTest : public test::TestBase { EXPECT_CALL(callback, Run(/*success=*/true)) .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); - base::Value::Dict data = base::test::ParseJsonDict(json); - GetAds().ParseAndSaveCreativeNewTabPageAds(std::move(data), callback.Get()); + base::Value::Dict dict = base::test::ParseJsonDict(json); + GetAds().ParseAndSaveCreativeNewTabPageAds(std::move(dict), callback.Get()); run_loop.Run(); } diff --git a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test_util.cc b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test_util.cc index 846e8fc65fa0..73d6e5db502b 100644 --- a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test_util.cc +++ b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_test_util.cc @@ -7,6 +7,7 @@ #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/new_tab_page_ad_builder.h" #include "brave/components/brave_ads/core/public/ad_units/new_tab_page_ad/new_tab_page_ad_info.h" @@ -14,14 +15,14 @@ namespace brave_ads::test { NewTabPageAdInfo BuildNewTabPageAd(bool should_generate_random_uuids) { - const CreativeNewTabPageAdInfo creative_ad = - BuildCreativeNewTabPageAd(should_generate_random_uuids); + const CreativeNewTabPageAdInfo creative_ad = BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kImage, should_generate_random_uuids); return BuildNewTabPageAd(creative_ad); } NewTabPageAdInfo BuildAndSaveNewTabPageAd(bool should_generate_random_uuids) { - const CreativeNewTabPageAdInfo creative_ad = - BuildCreativeNewTabPageAd(should_generate_random_uuids); + const CreativeNewTabPageAdInfo creative_ad = BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kImage, should_generate_random_uuids); database::SaveCreativeNewTabPageAds({creative_ad}); return BuildNewTabPageAd(creative_ad); } diff --git a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_value_util_unittest.cc b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_value_util_unittest.cc index 39e2e457faa1..47fea836fead 100644 --- a/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_value_util_unittest.cc +++ b/components/brave_ads/core/internal/ad_units/new_tab_page_ad/new_tab_page_ad_value_util_unittest.cc @@ -45,14 +45,16 @@ TEST_F(BraveAdsNewTabPageAdValueUtilTest, NewTabPageAdFromValue) { // Assert const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/false); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/false); EXPECT_EQ(BuildNewTabPageAd(test::kPlacementId, creative_ad), ad); } TEST_F(BraveAdsNewTabPageAdValueUtilTest, NewTabPageAdToValue) { // Arrange const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/false); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/false); const NewTabPageAdInfo ad = BuildNewTabPageAd(test::kPlacementId, creative_ad); diff --git a/components/brave_ads/core/internal/ads_impl.cc b/components/brave_ads/core/internal/ads_impl.cc index 55a8e8a2e0bd..9905df6a5835 100644 --- a/components/brave_ads/core/internal/ads_impl.cc +++ b/components/brave_ads/core/internal/ads_impl.cc @@ -64,6 +64,12 @@ void AdsImpl::SetFlags(mojom::FlagsPtr mojom_flags) { flags.environment_type = mojom_flags->environment_type; } +void AdsImpl::SetContentSettings( + mojom::ContentSettingsPtr mojom_content_settings) { + auto& content_settings = GlobalState::GetInstance()->ContentSettings(); + content_settings.allow_javascript = mojom_content_settings->allow_javascript; +} + void AdsImpl::Initialize(mojom::WalletInfoPtr mojom_wallet, InitializeCallback callback) { BLOG(1, "Initializing ads"); @@ -178,16 +184,16 @@ void AdsImpl::TriggerInlineContentAdEvent( } void AdsImpl::ParseAndSaveCreativeNewTabPageAds( - base::Value::Dict data, + base::Value::Dict dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) { if (task_queue_.should_queue()) { return task_queue_.Add(base::BindOnce( &AdsImpl::ParseAndSaveCreativeNewTabPageAds, weak_factory_.GetWeakPtr(), - std::move(data), std::move(callback))); + std::move(dict), std::move(callback))); } const bool success = - database::ParseAndSaveCreativeNewTabPageAds(std::move(data)); + database::ParseAndSaveCreativeNewTabPageAds(std::move(dict)); std::move(callback).Run(success); } diff --git a/components/brave_ads/core/internal/ads_impl.h b/components/brave_ads/core/internal/ads_impl.h index 5b6f816796a9..093c07391e7f 100644 --- a/components/brave_ads/core/internal/ads_impl.h +++ b/components/brave_ads/core/internal/ads_impl.h @@ -47,6 +47,8 @@ class AdsImpl final : public Ads { void SetSysInfo(mojom::SysInfoPtr mojom_sys_info) override; void SetBuildChannel(mojom::BuildChannelInfoPtr mojom_build_channel) override; void SetFlags(mojom::FlagsPtr mojom_flags) override; + void SetContentSettings( + mojom::ContentSettingsPtr mojom_content_settings) override; void Initialize(mojom::WalletInfoPtr mojom_wallet, InitializeCallback callback) override; @@ -70,7 +72,7 @@ class AdsImpl final : public Ads { TriggerAdEventCallback callback) override; void ParseAndSaveCreativeNewTabPageAds( - base::Value::Dict data, + base::Value::Dict dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) override; void MaybeServeNewTabPageAd(MaybeServeNewTabPageAdCallback callback) override; void TriggerNewTabPageAdEvent( diff --git a/components/brave_ads/core/internal/common/test/README.md b/components/brave_ads/core/internal/common/test/README.md index 3d27773dafd9..1c6cf8a6c6f6 100644 --- a/components/brave_ads/core/internal/common/test/README.md +++ b/components/brave_ads/core/internal/common/test/README.md @@ -140,6 +140,7 @@ You can add one or more responses per request. These will be returned in the giv | Device identifier | string | `21b4677de1a9b4a197ab671a1481d3fcb24f826a4358a05aafbaee5a9a51b57e` | `test::MockDeviceId();` | | Platform | `kWindows`, `kMacOS`, `kLinux`, `kAndroid` or `kIOS` | `kWindows` | `test::MockPlatformHelper(platform_helper_mock_, PlatformType::kMacOS);` | | Build channel | `kRelease`, `kBeta` or `kNightly` | `kRelease` | `test::MockBuildChannel(test::BuildChannelType::kNightly);` | +| JavaScript content setting | boolean | `true` | `test::MockAllowJavaScript(false);` | | Is network connection available | boolean | `true` | `test::MockIsNetworkConnectionAvailable(ads_client_mock_, false);` | | Is browser active | boolean | `true` | `test::MockIsBrowserActive(ads_client_mock_, false);` | | Is browser in full-screen mode | boolean | `false` | `test::MockIsBrowserInFullScreenMode(ads_client_mock_, true);` | diff --git a/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.cc b/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.cc index 0e6016692426..3a03a5316619 100644 --- a/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.cc +++ b/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.cc @@ -44,6 +44,10 @@ void MockFlags() { } } +void MockContentSettings() { + GlobalState::GetInstance()->ContentSettings().allow_javascript = true; +} + void MockAdsClientNotifierAddObserver(AdsClientMock& ads_client_mock, TestBase& test_base) { ON_CALL(ads_client_mock, AddObserver) diff --git a/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.h b/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.h index da9e1c5e902e..1ef6138d48f9 100644 --- a/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.h +++ b/components/brave_ads/core/internal/common/test/internal/mock_test_util_internal.h @@ -15,6 +15,8 @@ class TestBase; void MockFlags(); +void MockContentSettings(); + void MockAdsClientNotifierAddObserver(AdsClientMock& ads_client_mock, TestBase& test_base); void MockNotifyPendingObservers(AdsClientMock& ads_client_mock, diff --git a/components/brave_ads/core/internal/common/test/mock_test_util.cc b/components/brave_ads/core/internal/common/test/mock_test_util.cc index 5095cf33443d..91b1492f7d99 100644 --- a/components/brave_ads/core/internal/common/test/mock_test_util.cc +++ b/components/brave_ads/core/internal/common/test/mock_test_util.cc @@ -117,6 +117,11 @@ void MockBuildChannel(BuildChannelType type) { << base::to_underlying(type); } +void MockAllowJavaScript(bool allow_javascript) { + GlobalState::GetInstance()->ContentSettings().allow_javascript = + allow_javascript; +} + void MockIsNetworkConnectionAvailable(const AdsClientMock& ads_client_mock, bool is_available) { ON_CALL(ads_client_mock, IsNetworkConnectionAvailable()) diff --git a/components/brave_ads/core/internal/common/test/mock_test_util.h b/components/brave_ads/core/internal/common/test/mock_test_util.h index fcd51ad89ebf..ff37d0d6ad8a 100644 --- a/components/brave_ads/core/internal/common/test/mock_test_util.h +++ b/components/brave_ads/core/internal/common/test/mock_test_util.h @@ -31,6 +31,8 @@ void MockPlatformHelper(const PlatformHelperMock& platform_helper_mock, void MockBuildChannel(BuildChannelType type); +void MockAllowJavaScript(bool allow_javascript); + void MockIsNetworkConnectionAvailable(const AdsClientMock& ads_client_mock, bool is_available); diff --git a/components/brave_ads/core/internal/common/test/test_base.cc b/components/brave_ads/core/internal/common/test/test_base.cc index 2c2556f9c954..2957ef79c369 100644 --- a/components/brave_ads/core/internal/common/test/test_base.cc +++ b/components/brave_ads/core/internal/common/test/test_base.cc @@ -259,6 +259,8 @@ void TestBase::Mock() { MockBuildChannel(BuildChannelType::kRelease); + MockContentSettings(); + SetUpMocks(); // Must be called after `SetUpMocks` because `SetupMocks` may call diff --git a/components/brave_ads/core/internal/content_settings/README.md b/components/brave_ads/core/internal/content_settings/README.md new file mode 100644 index 000000000000..9fd9a3cb028b --- /dev/null +++ b/components/brave_ads/core/internal/content_settings/README.md @@ -0,0 +1,5 @@ +# Content Settings + +Allows users to control various aspects of their browsing experience, ensuring that user preferences are respected and applied consistently. + +Please add to it! diff --git a/components/brave_ads/core/internal/content_settings/content_settings_util.cc b/components/brave_ads/core/internal/content_settings/content_settings_util.cc new file mode 100644 index 000000000000..4d8afa6a778c --- /dev/null +++ b/components/brave_ads/core/internal/content_settings/content_settings_util.cc @@ -0,0 +1,16 @@ +/* Copyright (c) 2023 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/. */ + +#include "brave/components/brave_ads/core/internal/content_settings/content_settings_util.h" + +#include "brave/components/brave_ads/core/internal/global_state/global_state.h" + +namespace brave_ads { + +bool IsJavaScriptAllowed() { + return GlobalState::GetInstance()->ContentSettings().allow_javascript; +} + +} // namespace brave_ads diff --git a/components/brave_ads/core/internal/content_settings/content_settings_util.h b/components/brave_ads/core/internal/content_settings/content_settings_util.h new file mode 100644 index 000000000000..d9ef9771250c --- /dev/null +++ b/components/brave_ads/core/internal/content_settings/content_settings_util.h @@ -0,0 +1,15 @@ +/* Copyright (c) 2025 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/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CONTENT_SETTINGS_CONTENT_SETTINGS_UTIL_H_ +#define BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CONTENT_SETTINGS_CONTENT_SETTINGS_UTIL_H_ + +namespace brave_ads { + +bool IsJavaScriptAllowed(); + +} // namespace brave_ads + +#endif // BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CONTENT_SETTINGS_CONTENT_SETTINGS_UTIL_H_ diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h index a52357691b56..e6018993c275 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h @@ -10,6 +10,7 @@ #include #include "brave/components/brave_ads/core/internal/creatives/creative_ad_info.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" namespace brave_ads { @@ -27,6 +28,8 @@ struct CreativeNewTabPageAdInfo final : CreativeAdInfo { bool operator==(const CreativeNewTabPageAdInfo&) const = default; + CreativeNewTabPageAdWallpaperType wallpaper_type = + CreativeNewTabPageAdWallpaperType::kUndefined; std::string company_name; std::string alt; }; diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.cc b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.cc index eb1b0f20e3d0..078a1c142c4f 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.cc +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.cc @@ -13,14 +13,16 @@ namespace brave_ads::test { -CreativeNewTabPageAdList BuildCreativeNewTabPageAds(size_t count) { +CreativeNewTabPageAdList BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType wallpaper_type, + size_t count) { CHECK_GT(count, 0U); CreativeNewTabPageAdList creative_ads; for (size_t i = 0; i < count; ++i) { - CreativeNewTabPageAdInfo creative_ad = - BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + CreativeNewTabPageAdInfo creative_ad = BuildCreativeNewTabPageAd( + wallpaper_type, /*should_generate_random_uuids=*/true); creative_ad.segment = kSegments[i % kSegments.size()]; creative_ads.push_back(creative_ad); @@ -30,11 +32,13 @@ CreativeNewTabPageAdList BuildCreativeNewTabPageAds(size_t count) { } CreativeNewTabPageAdInfo BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType wallpaper_type, bool should_generate_random_uuids) { const CreativeAdInfo creative_ad = BuildCreativeAd(should_generate_random_uuids); CreativeNewTabPageAdInfo creative_new_tab_page_ad(creative_ad); + creative_new_tab_page_ad.wallpaper_type = wallpaper_type; creative_new_tab_page_ad.company_name = "Test Ad Company Name"; creative_new_tab_page_ad.alt = "Test Ad Alt"; diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h index be9586a4e2c8..fa7986e1ddc9 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h @@ -9,11 +9,15 @@ #include #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" namespace brave_ads::test { -CreativeNewTabPageAdList BuildCreativeNewTabPageAds(size_t count); +CreativeNewTabPageAdList BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType wallpaper_type, + size_t count); CreativeNewTabPageAdInfo BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType wallpaper_type, bool should_generate_random_uuids); } // namespace brave_ads::test diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h new file mode 100644 index 000000000000..76514aed3922 --- /dev/null +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h @@ -0,0 +1,19 @@ +/* Copyright (c) 2025 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/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_H_ +#define BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_H_ + +namespace brave_ads { + +enum class CreativeNewTabPageAdWallpaperType { + kUndefined = 0, + kImage, + kRichMedia +}; + +} // namespace brave_ads + +#endif // BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_H_ diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_constants.h b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_constants.h new file mode 100644 index 000000000000..94b9a5956cd3 --- /dev/null +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_constants.h @@ -0,0 +1,17 @@ +/* Copyright (c) 2025 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/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_CONSTANTS_H_ +#define BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_CONSTANTS_H_ + +namespace brave_ads { + +inline constexpr char kCreativeNewTabPageAdImageWallpaperType[] = "image"; +inline constexpr char kCreativeNewTabPageAdRichMediaWallpaperType[] = + "richMedia"; + +} // namespace brave_ads + +#endif // BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_CONSTANTS_H_ diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.cc b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.cc new file mode 100644 index 000000000000..f3c6fa5c9f2d --- /dev/null +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.cc @@ -0,0 +1,48 @@ +/* Copyright (c) 2025 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/. */ + +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h" + +#include + +#include "base/notreached.h" +#include "base/types/cxx23_to_underlying.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_constants.h" + +namespace brave_ads { + +CreativeNewTabPageAdWallpaperType ToCreativeNewTabPageAdWallpaperType( + std::string_view wallpaper_type) { + if (wallpaper_type == kCreativeNewTabPageAdImageWallpaperType) { + return CreativeNewTabPageAdWallpaperType::kImage; + } + + if (wallpaper_type == kCreativeNewTabPageAdRichMediaWallpaperType) { + return CreativeNewTabPageAdWallpaperType::kRichMedia; + } + + NOTREACHED() << "Unexpected value for wallpaper_type: " << wallpaper_type; +} + +std::string ToString(CreativeNewTabPageAdWallpaperType wallpaper_type) { + switch (wallpaper_type) { + case CreativeNewTabPageAdWallpaperType::kImage: { + return kCreativeNewTabPageAdImageWallpaperType; + } + + case CreativeNewTabPageAdWallpaperType::kRichMedia: { + return kCreativeNewTabPageAdRichMediaWallpaperType; + } + + default: { + break; + } + } + + NOTREACHED() << "Unexpected value for CreativeNewTabPageAdWallpaperType: " + << base::to_underlying(wallpaper_type); +} + +} // namespace brave_ads diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h new file mode 100644 index 000000000000..59b19824ab42 --- /dev/null +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h @@ -0,0 +1,23 @@ +/* Copyright (c) 2025 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/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_UTIL_H_ +#define BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_UTIL_H_ + +#include +#include + +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" + +namespace brave_ads { + +CreativeNewTabPageAdWallpaperType ToCreativeNewTabPageAdWallpaperType( + std::string_view wallpaper_type); + +std::string ToString(CreativeNewTabPageAdWallpaperType wallpaper_type); + +} // namespace brave_ads + +#endif // BRAVE_COMPONENTS_BRAVE_ADS_CORE_INTERNAL_CREATIVES_NEW_TAB_PAGE_ADS_CREATIVE_NEW_TAB_PAGE_AD_WALLPAPER_TYPE_UTIL_H_ diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util_unittest.cc b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util_unittest.cc new file mode 100644 index 000000000000..cdaf8d57c9c5 --- /dev/null +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util_unittest.cc @@ -0,0 +1,42 @@ +/* Copyright (c) 2025 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/. */ + +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h" + +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=BraveAds* + +namespace brave_ads { + +TEST(BraveAdsCreativeNewTabPageAdWallpaperTypeUtilTest, + StringToCreativeNewTabPageAdImageWallpaperType) { + // Act & Assert + EXPECT_EQ(CreativeNewTabPageAdWallpaperType::kImage, + ToCreativeNewTabPageAdWallpaperType("image")); +} + +TEST(BraveAdsCreativeNewTabPageAdWallpaperTypeUtilTest, + StringToCreativeNewTabPageAdWallpaperType) { + // Act & Assert + EXPECT_EQ(CreativeNewTabPageAdWallpaperType::kRichMedia, + ToCreativeNewTabPageAdWallpaperType("richMedia")); +} + +TEST(BraveAdsCreativeNewTabPageAdWallpaperTypeUtilTest, + CreativeNewTabPageAdImageWallpaperTypeToString) { + // Act & Assert + EXPECT_EQ("image", ToString(CreativeNewTabPageAdWallpaperType::kImage)); +} + +TEST(BraveAdsCreativeNewTabPageAdWallpaperTypeUtilTest, + CreativeNewTabPageAdRichMediaWallpaperTypeToString) { + // Act & Assert + EXPECT_EQ("richMedia", + ToString(CreativeNewTabPageAdWallpaperType::kRichMedia)); +} + +} // namespace brave_ads diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.cc b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.cc index a5e3b0ff76bc..b71089cdf021 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.cc +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.cc @@ -22,9 +22,11 @@ #include "brave/components/brave_ads/core/internal/common/database/database_transaction_util.h" #include "brave/components/brave_ads/core/internal/common/logging_util.h" #include "brave/components/brave_ads/core/internal/common/time/time_util.h" +#include "brave/components/brave_ads/core/internal/content_settings/content_settings_util.h" #include "brave/components/brave_ads/core/internal/creatives/creative_ad_info.h" #include "brave/components/brave_ads/core/internal/creatives/creative_ad_util.h" #include "brave/components/brave_ads/core/internal/creatives/creative_ads_database_table_util.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h" #include "brave/components/brave_ads/core/internal/segments/segment_util.h" #include "brave/components/brave_ads/core/mojom/brave_ads.mojom.h" #include "brave/components/brave_ads/core/public/serving/targeting/condition_matcher/condition_matcher_util.h" @@ -60,6 +62,7 @@ void BindColumnTypes(const mojom::DBActionInfoPtr& mojom_db_action) { mojom::DBBindColumnType::kString, // segment mojom::DBBindColumnType::kString, // geo_target mojom::DBBindColumnType::kString, // target_url + mojom::DBBindColumnType::kString, // type mojom::DBBindColumnType::kString, // company_name mojom::DBBindColumnType::kString, // alt mojom::DBBindColumnType::kDouble, // ptr @@ -82,6 +85,8 @@ size_t BindColumns(const mojom::DBActionInfoPtr& mojom_db_action, creative_ad.creative_instance_id); BindColumnString(mojom_db_action, index++, creative_ad.creative_set_id); BindColumnString(mojom_db_action, index++, creative_ad.campaign_id); + BindColumnString(mojom_db_action, index++, + ToString(creative_ad.wallpaper_type)); BindColumnString(mojom_db_action, index++, creative_ad.company_name); BindColumnString(mojom_db_action, index++, creative_ad.alt); @@ -115,14 +120,16 @@ CreativeNewTabPageAdInfo FromMojomRow(const mojom::DBRowInfoPtr& mojom_db_row) { creative_ad.segment = ColumnString(mojom_db_row, 15); creative_ad.geo_targets.insert(ColumnString(mojom_db_row, 16)); creative_ad.target_url = GURL(ColumnString(mojom_db_row, 17)); - creative_ad.company_name = ColumnString(mojom_db_row, 18); - creative_ad.alt = ColumnString(mojom_db_row, 19); - creative_ad.pass_through_rate = ColumnDouble(mojom_db_row, 20); + creative_ad.wallpaper_type = + ToCreativeNewTabPageAdWallpaperType(ColumnString(mojom_db_row, 18)); + creative_ad.company_name = ColumnString(mojom_db_row, 19); + creative_ad.alt = ColumnString(mojom_db_row, 20); + creative_ad.pass_through_rate = ColumnDouble(mojom_db_row, 21); CreativeDaypartInfo daypart; - daypart.days_of_week = ColumnString(mojom_db_row, 21); - daypart.start_minute = ColumnInt(mojom_db_row, 22); - daypart.end_minute = ColumnInt(mojom_db_row, 23); + daypart.days_of_week = ColumnString(mojom_db_row, 22); + daypart.start_minute = ColumnInt(mojom_db_row, 23); + daypart.end_minute = ColumnInt(mojom_db_row, 24); creative_ad.dayparts.insert(daypart); return creative_ad; @@ -216,6 +223,10 @@ void GetAllCallback( std::move(callback).Run(/*success=*/true, segments, creative_ads); } +std::string IsRichMediaAllowed() { + return IsJavaScriptAllowed() ? "1" : "0"; +} + } // namespace CreativeNewTabPageAds::CreativeNewTabPageAds() @@ -338,6 +349,7 @@ void CreativeNewTabPageAds::GetForCreativeInstanceId( segments.segment, geo_targets.geo_target, creative_ads.target_url, + creative_new_tab_page_ad.type, creative_new_tab_page_ad.company_name, creative_new_tab_page_ad.alt, campaigns.ptr, @@ -352,8 +364,9 @@ void CreativeNewTabPageAds::GetForCreativeInstanceId( INNER JOIN geo_targets ON geo_targets.campaign_id = creative_new_tab_page_ad.campaign_id INNER JOIN segments ON segments.creative_set_id = creative_new_tab_page_ad.creative_set_id WHERE - creative_new_tab_page_ad.creative_instance_id = '$2')", - {GetTableName(), creative_instance_id}, nullptr); + creative_new_tab_page_ad.creative_instance_id = '$2' + AND ($3 OR creative_new_tab_page_ad.type != 'richMedia'))", + {GetTableName(), creative_instance_id, IsRichMediaAllowed()}, nullptr); BindColumnTypes(mojom_db_action); mojom_db_transaction->actions.push_back(std::move(mojom_db_action)); @@ -395,6 +408,7 @@ void CreativeNewTabPageAds::GetForSegments( segments.segment, geo_targets.geo_target, creative_ads.target_url, + creative_new_tab_page_ad.type, creative_new_tab_page_ad.company_name, creative_new_tab_page_ad.alt, campaigns.ptr, @@ -410,10 +424,11 @@ void CreativeNewTabPageAds::GetForSegments( INNER JOIN segments ON segments.creative_set_id = creative_new_tab_page_ad.creative_set_id WHERE segments.segment IN $2 - AND $3 BETWEEN campaigns.start_at AND campaigns.end_at)", + AND $3 BETWEEN campaigns.start_at AND campaigns.end_at + AND ($4 OR creative_new_tab_page_ad.type != 'richMedia'))", {GetTableName(), BuildBindColumnPlaceholder(/*column_count=*/segments.size()), - TimeToSqlValueAsString(base::Time::Now())}, + TimeToSqlValueAsString(base::Time::Now()), IsRichMediaAllowed()}, nullptr); BindColumnTypes(mojom_db_action); @@ -456,6 +471,7 @@ void CreativeNewTabPageAds::GetForActiveCampaigns( segments.segment, geo_targets.geo_target, creative_ads.target_url, + creative_new_tab_page_ad.type, creative_new_tab_page_ad.company_name, creative_new_tab_page_ad.alt, campaigns.ptr, @@ -470,8 +486,11 @@ void CreativeNewTabPageAds::GetForActiveCampaigns( INNER JOIN geo_targets ON geo_targets.campaign_id = creative_new_tab_page_ad.campaign_id INNER JOIN segments ON segments.creative_set_id = creative_new_tab_page_ad.creative_set_id WHERE - $2 BETWEEN campaigns.start_at AND campaigns.end_at)", - {GetTableName(), TimeToSqlValueAsString(base::Time::Now())}, nullptr); + $2 BETWEEN campaigns.start_at AND campaigns.end_at + AND ($3 OR creative_new_tab_page_ad.type != 'richMedia'))", + {GetTableName(), TimeToSqlValueAsString(base::Time::Now()), + IsRichMediaAllowed()}, + nullptr); BindColumnTypes(mojom_db_action); mojom_db_transaction->actions.push_back(std::move(mojom_db_action)); @@ -492,6 +511,7 @@ void CreativeNewTabPageAds::Create( creative_instance_id TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE, creative_set_id TEXT NOT NULL, campaign_id TEXT NOT NULL, + type TEXT NOT NULL, company_name TEXT NOT NULL, alt TEXT NOT NULL ))"); @@ -508,6 +528,11 @@ void CreativeNewTabPageAds::Migrate( break; } + case 49: { + MigrateToV49(mojom_db_transaction); + break; + } + default: { // No migration needed. break; @@ -532,6 +557,38 @@ void CreativeNewTabPageAds::MigrateToV48( Create(mojom_db_transaction); } +void CreativeNewTabPageAds::MigrateToV49( + const mojom::DBTransactionInfoPtr& mojom_db_transaction) { + CHECK(mojom_db_transaction); + + // Create a temporary table: + // - with a new `type` column constraint. The default value for existing + // rows is 'image', which will be corrected when the new tab page ads are + // updated. + Execute(mojom_db_transaction, R"( + CREATE TABLE creative_new_tab_page_ads_temp ( + creative_instance_id TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE, + creative_set_id TEXT NOT NULL, + campaign_id TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'image', + company_name TEXT NOT NULL, + alt TEXT NOT NULL + ))"); + + // Copy legacy columns to the temporary table, drop the legacy table and + // rename the temporary table. + const std::vector columns = {"creative_instance_id", + "creative_set_id", "campaign_id", + "company_name", "alt"}; + + CopyTableColumns(mojom_db_transaction, "creative_new_tab_page_ads", + "creative_new_tab_page_ads_temp", columns, + /*should_drop=*/true); + + RenameTable(mojom_db_transaction, "creative_new_tab_page_ads_temp", + "creative_new_tab_page_ads"); +} + void CreativeNewTabPageAds::Insert( const mojom::DBTransactionInfoPtr& mojom_db_transaction, const CreativeNewTabPageAdList& creative_ads) { @@ -565,11 +622,12 @@ std::string CreativeNewTabPageAds::BuildInsertSql( creative_instance_id, creative_set_id, campaign_id, + type, company_name, alt ) VALUES $2)", {GetTableName(), - BuildBindColumnPlaceholders(/*column_count=*/5, row_count)}, + BuildBindColumnPlaceholders(/*column_count=*/6, row_count)}, nullptr); } diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.h b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.h index 64eafde3c97b..5f44f02e4c8b 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.h +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.h @@ -64,6 +64,7 @@ class CreativeNewTabPageAds final : public TableInterface { private: void MigrateToV48(const mojom::DBTransactionInfoPtr& mojom_db_transaction); + void MigrateToV49(const mojom::DBTransactionInfoPtr& mojom_db_transaction); void Insert(const mojom::DBTransactionInfoPtr& mojom_db_transaction, const CreativeNewTabPageAdList& creative_ads); diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table_unittest.cc b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table_unittest.cc index 74f5114aa044..ecbd6d7d8fac 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table_unittest.cc +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table_unittest.cc @@ -9,11 +9,14 @@ #include "base/test/gmock_callback_support.h" #include "base/test/mock_callback.h" #include "brave/components/brave_ads/core/internal/ad_units/ad_test_constants.h" +#include "brave/components/brave_ads/core/internal/common/test/mock_test_util.h" #include "brave/components/brave_ads/core/internal/common/test/test_base.h" #include "brave/components/brave_ads/core/internal/common/test/time_test_util.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_info.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.h" +#include "brave/components/brave_ads/core/internal/segments/segment_alias.h" // npm run test -- brave_unit_tests --filter=BraveAds* @@ -42,7 +45,8 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, SaveEmpty) { TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, Save) { // Arrange const CreativeNewTabPageAdList creative_ads = - test::BuildCreativeNewTabPageAds(/*count=*/2); + test::BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType::kImage, /*count=*/2); // Act database::SaveCreativeNewTabPageAds(creative_ads); @@ -64,7 +68,8 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, SaveInBatches) { database_table_.SetBatchSize(2); const CreativeNewTabPageAdList creative_ads = - test::BuildCreativeNewTabPageAds(/*count=*/3); + test::BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType::kImage, /*count=*/3); // Act database::SaveCreativeNewTabPageAds(creative_ads); @@ -85,7 +90,8 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, SaveInBatches) { TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, DoNotSaveDuplicates) { // Arrange const CreativeNewTabPageAdList creative_ads = - test::BuildCreativeNewTabPageAds(/*count=*/1); + test::BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType::kImage, /*count=*/1); database::SaveCreativeNewTabPageAds(creative_ads); // Act @@ -102,17 +108,19 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, DoNotSaveDuplicates) { run_loop.Run(); } -TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetForSegments) { +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetForImageSegments) { // Arrange CreativeNewTabPageAdList creative_ads; CreativeNewTabPageAdInfo creative_ad_1 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_1.segment = "food & drink"; creative_ads.push_back(creative_ad_1); CreativeNewTabPageAdInfo creative_ad_2 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_2.segment = "technology & computing"; creative_ads.push_back(creative_ad_2); @@ -130,10 +138,86 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetForSegments) { run_loop.Run(); } -TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetForEmptySegments) { +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + GetForSegmentsIfTypeIsRichMedia) { // Arrange - const CreativeNewTabPageAdList creative_ads = - test::BuildCreativeNewTabPageAds(/*count=*/1); + CreativeNewTabPageAdList creative_ads; + + CreativeNewTabPageAdInfo creative_ad_1 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_1.segment = "food & drink"; + creative_ads.push_back(creative_ad_1); + + CreativeNewTabPageAdInfo creative_ad_2 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_2.segment = "technology & computing"; + creative_ads.push_back(creative_ad_2); + + database::SaveCreativeNewTabPageAds(creative_ads); + + // Act & Assert + base::MockCallback + callback; + base::RunLoop run_loop; + EXPECT_CALL(callback, Run(/*success=*/true, SegmentList{"food & drink"}, + CreativeNewTabPageAdList{creative_ad_1})) + .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); + database_table_.GetForSegments( + /*segments=*/{"food & drink"}, callback.Get()); + run_loop.Run(); +} + +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + DoNotGetForSegmentsIfTypeIsRichMediaAndJavascriptIsDisabled) { + // Arrange + test::MockAllowJavaScript(false); + + CreativeNewTabPageAdList creative_ads; + + CreativeNewTabPageAdInfo creative_ad_1 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_1.segment = "food & drink"; + creative_ads.push_back(creative_ad_1); + + CreativeNewTabPageAdInfo creative_ad_2 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_2.segment = "technology & computing"; + creative_ads.push_back(creative_ad_2); + + database::SaveCreativeNewTabPageAds(creative_ads); + + // Act & Assert + base::MockCallback + callback; + base::RunLoop run_loop; + EXPECT_CALL(callback, Run(/*success=*/true, SegmentList{"food & drink"}, + /*creative_ads=*/::testing::IsEmpty())) + .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); + database_table_.GetForSegments( + /*segments=*/{"food & drink"}, callback.Get()); + run_loop.Run(); +} + +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + DoNotGetForEmptySegments) { + // Arrange + CreativeNewTabPageAdList creative_ads; + + const CreativeNewTabPageAdInfo creative_ad_1 = + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_1); + + const CreativeNewTabPageAdInfo creative_ad_2 = + test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_2); + database::SaveCreativeNewTabPageAds(creative_ads); // Act & Assert @@ -149,21 +233,22 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetForEmptySegments) { } TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, - GetForNonExistentSegment) { + DoNotGetForMissingSegment) { // Arrange const CreativeNewTabPageAdList creative_ads = - test::BuildCreativeNewTabPageAds(/*count=*/1); + test::BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType::kImage, /*count=*/1); database::SaveCreativeNewTabPageAds(creative_ads); // Act & Assert base::MockCallback callback; base::RunLoop run_loop; - EXPECT_CALL(callback, Run(/*success=*/true, SegmentList{"NON_EXISTENT"}, + EXPECT_CALL(callback, Run(/*success=*/true, SegmentList{"MISSING"}, /*creative_ads=*/::testing::IsEmpty())) .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); database_table_.GetForSegments( - /*segments=*/{"NON_EXISTENT"}, callback.Get()); + /*segments=*/{"MISSING"}, callback.Get()); run_loop.Run(); } @@ -172,17 +257,20 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetForMultipleSegments) { CreativeNewTabPageAdList creative_ads; CreativeNewTabPageAdInfo creative_ad_1 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_1.segment = "technology & computing"; creative_ads.push_back(creative_ad_1); - CreativeNewTabPageAdInfo creative_ad_2 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + CreativeNewTabPageAdInfo creative_ad_2 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); creative_ad_2.segment = "food & drink"; creative_ads.push_back(creative_ad_2); CreativeNewTabPageAdInfo creative_ad_3 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_3.segment = "automotive"; creative_ads.push_back(creative_ad_3); @@ -204,16 +292,18 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetForMultipleSegments) { } TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, - GetForCreativeInstanceId) { + GetForCreativeInstanceIdIfTypeIsImage) { // Arrange CreativeNewTabPageAdList creative_ads; const CreativeNewTabPageAdInfo creative_ad_1 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ads.push_back(creative_ad_1); const CreativeNewTabPageAdInfo creative_ad_2 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ads.push_back(creative_ad_2); database::SaveCreativeNewTabPageAds(creative_ads); @@ -230,10 +320,102 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, } TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, - GetForNonExistentCreativeInstanceId) { + GetForCreativeInstanceIdIfTypeIsImageAndJavascriptIsDisabled) { + // Arrange + test::MockAllowJavaScript(false); + + CreativeNewTabPageAdList creative_ads; + + const CreativeNewTabPageAdInfo creative_ad_1 = + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_1); + + const CreativeNewTabPageAdInfo creative_ad_2 = + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_2); + + database::SaveCreativeNewTabPageAds(creative_ads); + + // Act & Assert + base::MockCallback callback; + base::RunLoop run_loop; + EXPECT_CALL(callback, Run(/*success=*/true, + creative_ad_1.creative_instance_id, creative_ad_1)) + .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); + database_table_.GetForCreativeInstanceId(creative_ad_1.creative_instance_id, + callback.Get()); + run_loop.Run(); +} + +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + GetForCreativeInstanceIdIfTypeIsRichMedia) { + // Arrange + CreativeNewTabPageAdList creative_ads; + + const CreativeNewTabPageAdInfo creative_ad_1 = + test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_1); + + const CreativeNewTabPageAdInfo creative_ad_2 = + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_2); + + database::SaveCreativeNewTabPageAds(creative_ads); + + // Act & Assert + base::MockCallback callback; + base::RunLoop run_loop; + EXPECT_CALL(callback, Run(/*success=*/true, + creative_ad_1.creative_instance_id, creative_ad_1)) + .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); + database_table_.GetForCreativeInstanceId(creative_ad_1.creative_instance_id, + callback.Get()); + run_loop.Run(); +} + +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + DoNotGetForCreativeInstanceIdIfTypeIsRichMediaAndJavascriptIsDisabled) { + // Arrange + test::MockAllowJavaScript(false); + + CreativeNewTabPageAdList creative_ads; + + const CreativeNewTabPageAdInfo creative_ad_1 = + test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_1); + + const CreativeNewTabPageAdInfo creative_ad_2 = + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); + creative_ads.push_back(creative_ad_2); + + database::SaveCreativeNewTabPageAds(creative_ads); + + // Act & Assert + base::MockCallback callback; + base::RunLoop run_loop; + EXPECT_CALL(callback, + Run(/*success=*/false, creative_ad_1.creative_instance_id, + CreativeNewTabPageAdInfo{})) + .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); + database_table_.GetForCreativeInstanceId(creative_ad_1.creative_instance_id, + callback.Get()); + run_loop.Run(); +} + +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + DoNotGetForMissingCreativeInstanceId) { // Arrange const CreativeNewTabPageAdList creative_ads = - test::BuildCreativeNewTabPageAds(/*count=*/1); + test::BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType::kImage, /*count=*/1); database::SaveCreativeNewTabPageAds(creative_ads); // Act & Assert @@ -247,18 +429,21 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, run_loop.Run(); } -TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetNonExpired) { +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + GetNonExpiredIfTypeIsImage) { // Arrange CreativeNewTabPageAdList creative_ads; CreativeNewTabPageAdInfo creative_ad_1 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_1.start_at = test::DistantPast(); creative_ad_1.end_at = test::Now(); creative_ads.push_back(creative_ad_1); CreativeNewTabPageAdInfo creative_ad_2 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_2.start_at = test::DistantPast(); creative_ad_2.end_at = test::DistantFuture(); creative_ads.push_back(creative_ad_2); @@ -279,6 +464,77 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetNonExpired) { run_loop.Run(); } +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + GetNonExpiredIfTypeIsRichMedia) { + // Arrange + CreativeNewTabPageAdList creative_ads; + + CreativeNewTabPageAdInfo creative_ad_1 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_1.start_at = test::DistantPast(); + creative_ad_1.end_at = test::Now(); + creative_ads.push_back(creative_ad_1); + + CreativeNewTabPageAdInfo creative_ad_2 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_2.start_at = test::DistantPast(); + creative_ad_2.end_at = test::DistantFuture(); + creative_ads.push_back(creative_ad_2); + + database::SaveCreativeNewTabPageAds(creative_ads); + + AdvanceClockBy(base::Milliseconds(1)); + + // Act & Assert + base::MockCallback + callback; + base::RunLoop run_loop; + EXPECT_CALL(callback, + Run(/*success=*/true, SegmentList{creative_ad_2.segment}, + CreativeNewTabPageAdList{creative_ad_2})) + .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); + database_table_.GetForActiveCampaigns(callback.Get()); + run_loop.Run(); +} + +TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, + DoNotGetNonExpiredIfTypeIsRichMediaAndJavascriptIsDisabled) { + // Arrange + test::MockAllowJavaScript(false); + + CreativeNewTabPageAdList creative_ads; + + CreativeNewTabPageAdInfo creative_ad_1 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_1.start_at = test::DistantPast(); + creative_ad_1.end_at = test::Now(); + creative_ads.push_back(creative_ad_1); + + CreativeNewTabPageAdInfo creative_ad_2 = test::BuildCreativeNewTabPageAd( + CreativeNewTabPageAdWallpaperType::kRichMedia, + /*should_generate_random_uuids=*/true); + creative_ad_2.start_at = test::DistantPast(); + creative_ad_2.end_at = test::DistantFuture(); + creative_ads.push_back(creative_ad_2); + + database::SaveCreativeNewTabPageAds(creative_ads); + + AdvanceClockBy(base::Milliseconds(1)); + + // Act & Assert + base::MockCallback + callback; + base::RunLoop run_loop; + EXPECT_CALL(callback, Run(/*success=*/true, /*segments=*/::testing::IsEmpty(), + /*creative_ads=*/::testing::IsEmpty())) + .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure())); + database_table_.GetForActiveCampaigns(callback.Get()); + run_loop.Run(); +} + TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseTableTest, GetTableName) { // Act & Assert EXPECT_EQ("creative_new_tab_page_ads", database_table_.GetTableName()); diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.cc b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.cc index 98000e889b13..dc753f1f5c71 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.cc +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.cc @@ -15,6 +15,9 @@ #include "brave/components/brave_ads/core/internal/common/logging_util.h" #include "brave/components/brave_ads/core/internal/creatives/conversions/creative_set_conversion_database_table_util.h" #include "brave/components/brave_ads/core/internal/creatives/conversions/creative_set_conversion_info.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_constants.h" +#include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util.h" #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table.h" #include "brave/components/brave_ads/core/internal/segments/segment_constants.h" #include "brave/components/brave_ads/core/public/common/url/url_util.h" @@ -76,6 +79,9 @@ constexpr char kCreativeSetConversionPublicKeyKey[] = "publicKey"; constexpr char kCreativesKey[] = "creatives"; constexpr char kCreativeInstanceIdKey[] = "creativeInstanceId"; +constexpr char kCreativeWallpaperKey[] = "wallpaper"; +constexpr char kCreativeWallpaperTypeKey[] = "type"; + constexpr char kCreativeCompanyNameKey[] = "companyName"; constexpr char kCreativeAltKey[] = "alt"; @@ -90,14 +96,14 @@ constexpr char kCreativeConditionMatcherPrefPathKey[] = "prefPath"; // This temporary implementation has high congitive complexity to parse and save // creative new tab page ads. It will be replaced when new tab page ads are // served from the ads component. -bool ParseAndSaveCreativeNewTabPageAds(base::Value::Dict data) { - const std::optional schema_version = data.FindInt(kSchemaVersionKey); +bool ParseAndSaveCreativeNewTabPageAds(base::Value::Dict dict) { + const std::optional schema_version = dict.FindInt(kSchemaVersionKey); if (schema_version != kExpectedSchemaVersion) { // Currently, only version 2 is supported. Update this code to maintain. return false; } - const base::Value::List* const campaign_list = data.FindList(kCampaignsKey); + const base::Value::List* const campaign_list = dict.FindList(kCampaignsKey); if (!campaign_list) { BLOG(0, "Campaigns are required"); return false; @@ -406,6 +412,28 @@ bool ParseAndSaveCreativeNewTabPageAds(base::Value::Dict data) { continue; } + // Wallpaper. + const base::Value::Dict* const wallpaper_dict = + creative_dict->FindDict(kCreativeWallpaperKey); + if (!wallpaper_dict) { + BLOG(0, "Wallpaper is required, skipping creative"); + continue; + } + + const std::string* const wallpaper_type = + wallpaper_dict->FindString(kCreativeWallpaperTypeKey); + if (!wallpaper_type) { + BLOG(0, "Wallpaper type is required, skipping creative"); + continue; + } + if (*wallpaper_type != kCreativeNewTabPageAdImageWallpaperType && + *wallpaper_type != kCreativeNewTabPageAdRichMediaWallpaperType) { + BLOG(0, "Unknown wallpaper type, skipping creative"); + continue; + } + creative_ad.wallpaper_type = + ToCreativeNewTabPageAdWallpaperType(*wallpaper_type); + // Condition matchers. const base::Value::List* const condition_matcher_list = creative_dict->FindList(kCreativeConditionMatchersKey); diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.h b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.h index c1c53e61a6b8..efcff930fe7e 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.h +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.h @@ -11,7 +11,7 @@ namespace brave_ads::database { -bool ParseAndSaveCreativeNewTabPageAds(base::Value::Dict data); +bool ParseAndSaveCreativeNewTabPageAds(base::Value::Dict dict); void SaveCreativeNewTabPageAds(const CreativeNewTabPageAdList& creative_ads); diff --git a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util_unittest.cc b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util_unittest.cc index 50513432b138..dd7c68f7b45e 100644 --- a/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util_unittest.cc +++ b/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util_unittest.cc @@ -5,7 +5,6 @@ #include "brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util.h" -#include #include #include "base/test/values_test_util.h" @@ -20,7 +19,7 @@ class BraveAdsCreativeNewTabPageAdsDatabaseUtilTest : public test::TestBase {}; TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseUtilTest, ParseAndSaveCreativeAds) { // Arrange - base::Value::Dict data = base::test::ParseJsonDict(R"JSON( + base::Value::Dict dict = base::test::ParseJsonDict(R"JSON( { "schemaVersion": 2, "campaigns": [ @@ -110,7 +109,7 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseUtilTest, ParseAndSaveCreativeAds) { })JSON"); // Act & Assert - EXPECT_TRUE(database::ParseAndSaveCreativeNewTabPageAds(std::move(data))); + EXPECT_TRUE(database::ParseAndSaveCreativeNewTabPageAds(std::move(dict))); } TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseUtilTest, @@ -122,11 +121,11 @@ TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseUtilTest, TEST_F(BraveAdsCreativeNewTabPageAdsDatabaseUtilTest, DoNotParseAndSaveCreativeAdsWithMissingCampaigns) { - base::Value::Dict data = + base::Value::Dict dict = base::test::ParseJsonDict(R"JSON({"schemaVersion": 2})JSON"); // Act & Assert - EXPECT_FALSE(database::ParseAndSaveCreativeNewTabPageAds(std::move(data))); + EXPECT_FALSE(database::ParseAndSaveCreativeNewTabPageAds(std::move(dict))); } } // namespace brave_ads diff --git a/components/brave_ads/core/internal/global_state/global_state.cc b/components/brave_ads/core/internal/global_state/global_state.cc index f5b34c24510d..461a097ed737 100644 --- a/components/brave_ads/core/internal/global_state/global_state.cc +++ b/components/brave_ads/core/internal/global_state/global_state.cc @@ -148,6 +148,11 @@ mojom::Flags& GlobalState::Flags() { return mojom_flags_; } +mojom::ContentSettings& GlobalState::ContentSettings() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return mojom_content_settings_; +} + void GlobalState::PostDelayedTask(base::OnceClosure task, base::TimeDelta delay) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); diff --git a/components/brave_ads/core/internal/global_state/global_state.h b/components/brave_ads/core/internal/global_state/global_state.h index 27a11a1b8a4e..2a4c91a6eed8 100644 --- a/components/brave_ads/core/internal/global_state/global_state.h +++ b/components/brave_ads/core/internal/global_state/global_state.h @@ -69,6 +69,7 @@ class GlobalState final { mojom::SysInfo& SysInfo(); mojom::BuildChannelInfo& BuildChannel(); mojom::Flags& Flags(); + mojom::ContentSettings& ContentSettings(); void PostDelayedTask(base::OnceClosure task, base::TimeDelta delay); @@ -96,6 +97,7 @@ class GlobalState final { mojom::SysInfo mojom_sys_info_; mojom::BuildChannelInfo mojom_build_channel_; mojom::Flags mojom_flags_; + mojom::ContentSettings mojom_content_settings_; base::WeakPtrFactory weak_ptr_factory_{this}; }; diff --git a/components/brave_ads/core/internal/history/ad_history_manager_unittest.cc b/components/brave_ads/core/internal/history/ad_history_manager_unittest.cc index 6a1054a6990b..cd5cd8797929 100644 --- a/components/brave_ads/core/internal/history/ad_history_manager_unittest.cc +++ b/components/brave_ads/core/internal/history/ad_history_manager_unittest.cc @@ -83,7 +83,8 @@ TEST_F(BraveAdsAdHistoryManagerTest, TEST_F(BraveAdsAdHistoryManagerTest, AddNewTabPageAdHistory) { // Arrange const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); const NewTabPageAdInfo ad = BuildNewTabPageAd(creative_ad); // Act & Assert @@ -101,7 +102,8 @@ TEST_F(BraveAdsAdHistoryManagerTest, test::DisableBraveRewards(); const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); const NewTabPageAdInfo ad = BuildNewTabPageAd(creative_ad); // Act & Assert diff --git a/components/brave_ads/core/internal/legacy_migration/database/database_constants.h b/components/brave_ads/core/internal/legacy_migration/database/database_constants.h index 4583cb502fb6..aa127f17c740 100644 --- a/components/brave_ads/core/internal/legacy_migration/database/database_constants.h +++ b/components/brave_ads/core/internal/legacy_migration/database/database_constants.h @@ -8,8 +8,8 @@ namespace brave_ads::database { -inline constexpr int kVersionNumber = 48; -inline constexpr int kCompatibleVersionNumber = 48; +inline constexpr int kVersionNumber = 49; +inline constexpr int kCompatibleVersionNumber = 49; // If the database version number is less than or equal to this value, the // database will be razed and recreated during migration. This should be updated diff --git a/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature.h b/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature.h index f7d4eb298a5a..68e3221568fb 100644 --- a/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature.h +++ b/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature.h @@ -13,10 +13,10 @@ namespace brave_ads { BASE_DECLARE_FEATURE(kEligibleAdFeature); -inline constexpr base::FeatureParam kSiteHistoryMaxCount{ +inline constexpr base::FeatureParam kSiteHistoryMaxCount{ &kEligibleAdFeature, "site_history_max_count", 5'000}; -inline constexpr base::FeatureParam kSiteHistoryRecentDayRange{ +inline constexpr base::FeatureParam kSiteHistoryRecentDayRange{ &kEligibleAdFeature, "site_history_recent_day_range", 180}; } // namespace brave_ads diff --git a/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature_unittest.cc b/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature_unittest.cc index 93daf6777ddc..6a2095c4b0f2 100644 --- a/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature_unittest.cc +++ b/components/brave_ads/core/internal/serving/eligible_ads/eligible_ads_feature_unittest.cc @@ -33,12 +33,12 @@ TEST(BraveAdsEligibleAdFeatureTest, SiteHistoryMaxCount) { kEligibleAdFeature, {{"site_history_max_count", "666"}}); // Act & Assert - EXPECT_EQ(666U, kSiteHistoryMaxCount.Get()); + EXPECT_EQ(666, kSiteHistoryMaxCount.Get()); } TEST(BraveAdsEligibleAdFeatureTest, DefaultSiteHistoryMaxCount) { // Act & Assert - EXPECT_EQ(5'000U, kSiteHistoryMaxCount.Get()); + EXPECT_EQ(5'000, kSiteHistoryMaxCount.Get()); } TEST(BraveAdsEligibleAdFeatureTest, DefaultSiteHistoryMaxCountWhenDisabled) { @@ -47,7 +47,7 @@ TEST(BraveAdsEligibleAdFeatureTest, DefaultSiteHistoryMaxCountWhenDisabled) { scoped_feature_list.InitAndDisableFeature(kEligibleAdFeature); // Act & Assert - EXPECT_EQ(5'000U, kSiteHistoryMaxCount.Get()); + EXPECT_EQ(5'000, kSiteHistoryMaxCount.Get()); } TEST(BraveAdsEligibleAdFeatureTest, SiteHistoryRecentDayRange) { @@ -57,12 +57,12 @@ TEST(BraveAdsEligibleAdFeatureTest, SiteHistoryRecentDayRange) { kEligibleAdFeature, {{"site_history_recent_day_range", "7"}}); // Act & Assert - EXPECT_EQ(7U, kSiteHistoryRecentDayRange.Get()); + EXPECT_EQ(7, kSiteHistoryRecentDayRange.Get()); } TEST(BraveAdsEligibleAdFeatureTest, DefaultSiteHistoryRecentDayRange) { // Act & Assert - EXPECT_EQ(180U, kSiteHistoryRecentDayRange.Get()); + EXPECT_EQ(180, kSiteHistoryRecentDayRange.Get()); } TEST(BraveAdsEligibleAdFeatureTest, @@ -72,7 +72,7 @@ TEST(BraveAdsEligibleAdFeatureTest, scoped_feature_list.InitAndDisableFeature(kEligibleAdFeature); // Act & Assert - EXPECT_EQ(180U, kSiteHistoryRecentDayRange.Get()); + EXPECT_EQ(180, kSiteHistoryRecentDayRange.Get()); } } // namespace brave_ads diff --git a/components/brave_ads/core/internal/serving/eligible_ads/pipelines/new_tab_page_ads/eligible_new_tab_page_ads_v2_unittest.cc b/components/brave_ads/core/internal/serving/eligible_ads/pipelines/new_tab_page_ads/eligible_new_tab_page_ads_v2_unittest.cc index 6948def36d0e..406bc8f903dd 100644 --- a/components/brave_ads/core/internal/serving/eligible_ads/pipelines/new_tab_page_ads/eligible_new_tab_page_ads_v2_unittest.cc +++ b/components/brave_ads/core/internal/serving/eligible_ads/pipelines/new_tab_page_ads/eligible_new_tab_page_ads_v2_unittest.cc @@ -43,16 +43,19 @@ TEST_F(BraveAdsEligibleNewTabPageAdsV2Test, GetAds) { CreativeNewTabPageAdList creative_ads; const CreativeNewTabPageAdInfo creative_ad_1 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ads.push_back(creative_ad_1); CreativeNewTabPageAdInfo creative_ad_2 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_2.segment = "parent"; creative_ads.push_back(creative_ad_2); CreativeNewTabPageAdInfo creative_ad_3 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_3.segment = "parent-child"; creative_ads.push_back(creative_ad_3); @@ -75,12 +78,14 @@ TEST_F(BraveAdsEligibleNewTabPageAdsV2Test, GetAdsForNoMatchingSegments) { CreativeNewTabPageAdList creative_ads; CreativeNewTabPageAdInfo creative_ad_1 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_1.segment = "parent"; creative_ads.push_back(creative_ad_1); CreativeNewTabPageAdInfo creative_ad_2 = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); creative_ad_2.segment = "parent-child"; creative_ads.push_back(creative_ad_2); diff --git a/components/brave_ads/core/internal/serving/new_tab_page_ad_serving_unittest.cc b/components/brave_ads/core/internal/serving/new_tab_page_ad_serving_unittest.cc index 2f8376d0da9e..8160c3fb2900 100644 --- a/components/brave_ads/core/internal/serving/new_tab_page_ad_serving_unittest.cc +++ b/components/brave_ads/core/internal/serving/new_tab_page_ad_serving_unittest.cc @@ -53,7 +53,8 @@ TEST_F(BraveAdsNewTabPageAdServingTest, DoNotServeAdForUnsupportedVersion) { test::ForcePermissionRules(); const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); database::SaveCreativeNewTabPageAds({creative_ad}); // Act & Assert @@ -72,7 +73,8 @@ TEST_F(BraveAdsNewTabPageAdServingTest, ServeAd) { test::ForcePermissionRules(); const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); database::SaveCreativeNewTabPageAds({creative_ad}); const NewTabPageAdInfo ad = BuildNewTabPageAd(creative_ad); @@ -110,7 +112,8 @@ TEST_F(BraveAdsNewTabPageAdServingTest, DoNotServeAdIfNotAllowedDueToPermissionRules) { // Arrange const CreativeNewTabPageAdInfo creative_ad = - test::BuildCreativeNewTabPageAd(/*should_generate_random_uuids=*/true); + test::BuildCreativeNewTabPageAd(CreativeNewTabPageAdWallpaperType::kImage, + /*should_generate_random_uuids=*/true); database::SaveCreativeNewTabPageAds({creative_ad}); // Act & Assert diff --git a/components/brave_ads/core/internal/serving/prediction/model_based/weight/creative_ad_model_based_predictor_weights_builder_unittest.cc b/components/brave_ads/core/internal/serving/prediction/model_based/weight/creative_ad_model_based_predictor_weights_builder_unittest.cc index f2d27419db8b..1efe3cd354b8 100644 --- a/components/brave_ads/core/internal/serving/prediction/model_based/weight/creative_ad_model_based_predictor_weights_builder_unittest.cc +++ b/components/brave_ads/core/internal/serving/prediction/model_based/weight/creative_ad_model_based_predictor_weights_builder_unittest.cc @@ -46,7 +46,8 @@ TEST_F(BraveAdsCreativeAdModelBasedPredictorWeightsBuilderTest, BuildCreativeNewTabPageAdModelBasedPredictorWeights) { // Arrange const CreativeNewTabPageAdList creative_ads = - test::BuildCreativeNewTabPageAds(/*count=*/1); + test::BuildCreativeNewTabPageAds( + CreativeNewTabPageAdWallpaperType::kImage, /*count=*/1); // Act const CreativeAdModelBasedPredictorWeightsInfo weights = diff --git a/components/brave_ads/core/mojom/brave_ads.mojom b/components/brave_ads/core/mojom/brave_ads.mojom index a628a12a5a5d..181a1a226bb3 100644 --- a/components/brave_ads/core/mojom/brave_ads.mojom +++ b/components/brave_ads/core/mojom/brave_ads.mojom @@ -27,6 +27,10 @@ struct Flags { EnvironmentType environment_type; }; +struct ContentSettings { + bool allow_javascript; +}; + struct WalletInfo { string payment_id; string recovery_seed_base64; diff --git a/components/brave_ads/core/public/ads.h b/components/brave_ads/core/public/ads.h index c0534a759bee..f436ffdf83b9 100644 --- a/components/brave_ads/core/public/ads.h +++ b/components/brave_ads/core/public/ads.h @@ -47,6 +47,9 @@ class Ads { virtual void SetFlags(mojom::FlagsPtr mojom_flags) = 0; + virtual void SetContentSettings( + mojom::ContentSettingsPtr mojom_content_settings) = 0; + // Called to initialize ads for the specified `mojom::WalletInfoPtr`. // `mojom_wallet` can be nullptr if there is no wallet. The callback takes one // argument - `bool` is set to `true` if successful otherwise `false`. @@ -95,7 +98,7 @@ class Ads { // Called to parse and save creative new tab page ads. The callback takes one // argument - `bool` is set to `true` if successful otherwise `false`. virtual void ParseAndSaveCreativeNewTabPageAds( - base::Value::Dict data, + base::Value::Dict dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) = 0; // Called to serve a new tab page ad. The callback takes one argument - diff --git a/components/brave_ads/core/test/BUILD.gn b/components/brave_ads/core/test/BUILD.gn index 0752c142ff97..4175049ff861 100644 --- a/components/brave_ads/core/test/BUILD.gn +++ b/components/brave_ads/core/test/BUILD.gn @@ -363,6 +363,7 @@ source_set("brave_ads_unit_tests") { "//brave/components/brave_ads/core/internal/creatives/inline_content_ads/creative_inline_content_ads_database_table_unittest.cc", "//brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.cc", "//brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_test_util.h", + "//brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ad_wallpaper_type_util_unittest.cc", "//brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_table_unittest.cc", "//brave/components/brave_ads/core/internal/creatives/new_tab_page_ads/creative_new_tab_page_ads_database_util_unittest.cc", "//brave/components/brave_ads/core/internal/creatives/notification_ads/creative_notification_ad_test_util.cc", diff --git a/components/brave_ads/core/test/data/database/migration/database_schema_49.sqlite b/components/brave_ads/core/test/data/database/migration/database_schema_49.sqlite new file mode 100644 index 000000000000..0389251a5ffb Binary files /dev/null and b/components/brave_ads/core/test/data/database/migration/database_schema_49.sqlite differ diff --git a/components/ntp_background_images/browser/BUILD.gn b/components/ntp_background_images/browser/BUILD.gn index 6d175bcd4f3a..3eae8f769f88 100644 --- a/components/ntp_background_images/browser/BUILD.gn +++ b/components/ntp_background_images/browser/BUILD.gn @@ -59,6 +59,8 @@ static_library("browser") { "//brave/components/p3a_utils", "//brave/components/time_period_storage", "//components/component_updater", + "//components/content_settings/core/browser", + "//components/content_settings/core/common", "//components/keyed_service/core", "//components/pref_registry:pref_registry", "//components/prefs", diff --git a/components/ntp_background_images/browser/ntp_background_images_service.cc b/components/ntp_background_images/browser/ntp_background_images_service.cc index d0f276942651..5ebd8e56d769 100644 --- a/components/ntp_background_images/browser/ntp_background_images_service.cc +++ b/components/ntp_background_images/browser/ntp_background_images_service.cc @@ -98,8 +98,7 @@ NTPBackgroundImagesService::NTPBackgroundImagesService( component_updater::ComponentUpdateService* component_update_service, PrefService* pref_service) : component_update_service_(component_update_service), - pref_service_(pref_service), - weak_factory_(this) {} + pref_service_(pref_service) {} NTPBackgroundImagesService::~NTPBackgroundImagesService() = default; @@ -469,8 +468,9 @@ NTPBackgroundImagesData* NTPBackgroundImagesService::GetBackgroundImagesData() return nullptr; } -NTPSponsoredImagesData* NTPBackgroundImagesService::GetBrandedImagesData( - bool super_referral) const { +NTPSponsoredImagesData* NTPBackgroundImagesService::GetSponsoredImagesData( + bool super_referral, + bool supports_rich_media) const { const bool is_super_referrals_enabled = base::FeatureList::IsEnabled(features::kBraveNTPSuperReferralWallpaper); if (is_super_referrals_enabled) { @@ -496,11 +496,18 @@ NTPSponsoredImagesData* NTPBackgroundImagesService::GetBrandedImagesData( } } - if (sponsored_images_data_ && sponsored_images_data_->IsValid()) { - return sponsored_images_data_.get(); + NTPSponsoredImagesData* const sponsored_images_data = + supports_rich_media ? sponsored_images_data_.get() + : sponsored_images_data_excluding_rich_media_.get(); + if (!sponsored_images_data) { + return nullptr; } - return nullptr; + if (!sponsored_images_data->IsValid()) { + return nullptr; + } + + return sponsored_images_data; } void NTPBackgroundImagesService::OnComponentReady( @@ -574,6 +581,23 @@ void NTPBackgroundImagesService::OnGetSponsoredComponentJsonData( } else { sponsored_images_data_ = std::make_unique( data, sponsored_images_installed_dir_); + sponsored_images_data_excluding_rich_media_ = + std::make_unique( + data, sponsored_images_installed_dir_); + for (auto& campaign : + sponsored_images_data_excluding_rich_media_->campaigns) { + std::erase_if(campaign.creatives, [](const auto& creative) { + return creative.wallpaper_type == WallpaperType::kRichMedia; + }); + } + std::erase_if( + sponsored_images_data_excluding_rich_media_->campaigns, + [](const auto& campaign) { return campaign.creatives.empty(); }); + if (!sponsored_images_data_excluding_rich_media_) { + sponsored_images_data_excluding_rich_media_ = + std::make_unique(); + } + for (auto& observer : observers_) { observer.OnSponsoredContentDidUpdate(data); } diff --git a/components/ntp_background_images/browser/ntp_background_images_service.h b/components/ntp_background_images/browser/ntp_background_images_service.h index ae9b8bf7d672..e9edaafbe0ce 100644 --- a/components/ntp_background_images/browser/ntp_background_images_service.h +++ b/components/ntp_background_images/browser/ntp_background_images_service.h @@ -71,7 +71,9 @@ class NTPBackgroundImagesService { bool HasObserver(Observer* observer); NTPBackgroundImagesData* GetBackgroundImagesData() const; - NTPSponsoredImagesData* GetBrandedImagesData(bool super_referral) const; + NTPSponsoredImagesData* GetSponsoredImagesData( + bool super_referral, + bool supports_rich_media) const; bool test_data_used() const { return test_data_used_; } @@ -87,7 +89,19 @@ class NTPBackgroundImagesService { friend class NTPSponsoredRichMediaBrowserTest; friend class NTPBackgroundImagesServiceForTesting; friend class NTPBackgroundImagesServiceTest; - friend class NTPBackgroundImagesViewCounterTest; + friend class ViewCounterServiceTest; + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + AllowNewTabTakeoverWithRichMediaIfJavaScriptContentSettingIsSetToAllowed); + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + BlockNewTabTakeoverWithRichMediaIfJavaScriptContentSettingIsSetToBlocked); + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + AllowNewTabTakeOverWithImageIfJavaScriptContentSettingIsSetToAllowed); + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + AllowNewTabTakeoverWithImageIfJavaScriptContentSettingIsSetToBlocked); FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesServiceTest, InternalDataTest); FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesServiceTest, MultipleCampaignsTest); @@ -123,31 +137,29 @@ class NTPBackgroundImagesService { FRIEND_TEST_ALL_PREFIXES( NTPBackgroundImagesServiceTest, CheckRecoverShutdownWhileMappingTableFetchingWithNonDefaultCode); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - SINotActiveInitially); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - SINotActiveWithBadData); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - NotActiveOptedOut); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - IsActiveOptedIn); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - ActiveInitiallyOptedIn); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CanShowSponsoredImages); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CannotShowSponsoredImages); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowSponsoredImagesIfUninitialized); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowSponsoredImagesIfMalformed); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowSponsoredImagesIfOptedOut); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, IsActiveOptedIn); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, ActiveInitiallyOptedIn); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, ActiveOptedInWithNTPBackgoundOption); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, ModelTest); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - BINotActiveInitially); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - BINotActiveWithBadData); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - BINotActiveWithNTPBackgoundOptionOptedOut); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, ModelTest); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CanShowBackgroundImages); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CannotShowBackgroundImages); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowBackgroundImagesIfUninitialized); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowBackgroundImagesIfMalformed); FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesSourceTest, SponsoredImagesTest); FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesSourceTest, BasicSuperReferralDataTest); FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesSourceTest, BackgroundImagesTest); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - GetCurrentWallpaperTest); void OnSponsoredComponentReady(bool is_super_referral, const base::FilePath& installed_dir); @@ -195,6 +207,8 @@ class NTPBackgroundImagesService { std::optional sponsored_images_component_id_; base::FilePath sponsored_images_installed_dir_; std::unique_ptr sponsored_images_data_; + std::unique_ptr + sponsored_images_data_excluding_rich_media_; base::FilePath super_referrals_installed_dir_; std::unique_ptr super_referrals_images_data_; @@ -213,7 +227,7 @@ class NTPBackgroundImagesService { base::ObserverList::Unchecked observers_; - base::WeakPtrFactory weak_factory_; + base::WeakPtrFactory weak_factory_{this}; }; } // namespace ntp_background_images diff --git a/components/ntp_background_images/browser/ntp_background_images_service_unittest.cc b/components/ntp_background_images/browser/ntp_background_images_service_unittest.cc index 33062aa57e08..f0b8e21a0149 100644 --- a/components/ntp_background_images/browser/ntp_background_images_service_unittest.cc +++ b/components/ntp_background_images/browser/ntp_background_images_service_unittest.cc @@ -458,7 +458,8 @@ TEST_F(NTPBackgroundImagesServiceTest, DISABLED_InternalDataTest) { // Check with json file w/o schema version with empty object. service_->sponsored_images_data_.reset(); service_->OnGetSponsoredComponentJsonData(/*is_super_referral=*/false, "{}"); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); service_->background_images_data_.reset(); service_->OnGetComponentJsonData("{}"); EXPECT_FALSE(service_->GetBackgroundImagesData()); @@ -469,7 +470,8 @@ TEST_F(NTPBackgroundImagesServiceTest, DISABLED_InternalDataTest) { observer_.on_sponsored_images_updated = false; service_->OnGetSponsoredComponentJsonData(/*is_super_referral=*/false, kTestEmptyComponent); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); EXPECT_TRUE(observer_.on_sponsored_images_updated); EXPECT_THAT(observer_.sponsored_images_data->campaigns, ::testing::IsEmpty()); observer_.background_images_data = nullptr; @@ -490,7 +492,8 @@ TEST_F(NTPBackgroundImagesServiceTest, DISABLED_InternalDataTest) { // Mark this is not SR to get SI data. service_->MarkThisInstallIsNotSuperReferralForever(); NTPSponsoredImagesData* const images_data = - service_->GetBrandedImagesData(/*super_referral=*/false); + service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true); EXPECT_TRUE(images_data); EXPECT_TRUE(images_data->IsValid()); EXPECT_FALSE(images_data->IsSuperReferral()); @@ -600,7 +603,8 @@ TEST_F(NTPBackgroundImagesServiceTest, DISABLED_InternalDataTest) { observer_.on_sponsored_images_updated = false; service_->OnGetSponsoredComponentJsonData(/*is_super_referral=*/false, test_json_string_higher_schema); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); constexpr char kTestBackgroundJsonStringHigherSchema[] = R"( { @@ -638,7 +642,8 @@ TEST_F(NTPBackgroundImagesServiceTest, MultipleCampaignsTest) { // Mark this is not SR to get SI data. service_->MarkThisInstallIsNotSuperReferralForever(); const NTPSponsoredImagesData* const images_data = - service_->GetBrandedImagesData(/*super_referral=*/false); + service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true); EXPECT_TRUE(images_data); EXPECT_TRUE(images_data->IsValid()); EXPECT_FALSE(images_data->IsSuperReferral()); @@ -677,7 +682,8 @@ TEST_F(NTPBackgroundImagesServiceTest, // Mark this is not SR to get SI data. service_->MarkThisInstallIsNotSuperReferralForever(); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); EXPECT_TRUE(observer_.on_sponsored_images_updated); EXPECT_THAT(observer_.sponsored_images_data->campaigns, ::testing::IsEmpty()); EXPECT_THAT(service_->sponsored_images_data_->campaigns, @@ -699,7 +705,8 @@ TEST_F(NTPBackgroundImagesServiceTest, // Mark this is not SR to get SI data. service_->MarkThisInstallIsNotSuperReferralForever(); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); EXPECT_TRUE(observer_.on_sponsored_images_updated); EXPECT_THAT(observer_.sponsored_images_data->campaigns, ::testing::IsEmpty()); EXPECT_THAT(service_->sponsored_images_data_->campaigns, @@ -723,7 +730,8 @@ TEST_F( // Mark this is not SR to get SI data. service_->MarkThisInstallIsNotSuperReferralForever(); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); EXPECT_TRUE(observer_.on_sponsored_images_updated); EXPECT_THAT(observer_.sponsored_images_data->campaigns, ::testing::IsEmpty()); EXPECT_THAT(service_->sponsored_images_data_->campaigns, @@ -747,7 +755,8 @@ TEST_F( // Mark this is not SR to get SI data. service_->MarkThisInstallIsNotSuperReferralForever(); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); EXPECT_TRUE(observer_.on_sponsored_images_updated); EXPECT_THAT(observer_.sponsored_images_data->campaigns, ::testing::IsEmpty()); EXPECT_THAT(service_->sponsored_images_data_->campaigns, @@ -768,7 +777,8 @@ TEST_F(NTPBackgroundImagesServiceTest, SponsoredImageWithMissingImageUrlTest) { // Mark this is not SR to get SI data. service_->MarkThisInstallIsNotSuperReferralForever(); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); EXPECT_TRUE(observer_.on_sponsored_images_updated); EXPECT_THAT(observer_.sponsored_images_data->campaigns, ::testing::IsEmpty()); EXPECT_THAT(service_->sponsored_images_data_->campaigns, @@ -873,7 +883,8 @@ TEST_F(NTPBackgroundImagesServiceTest, BasicSuperReferralTest) { service_->OnGetSponsoredComponentJsonData(/*is_super_referral=*/true, kTestSuperReferral); const NTPSponsoredImagesData* const images_data = - service_->GetBrandedImagesData(/*super_referral=*/true); + service_->GetSponsoredImagesData(/*super_referral=*/true, + /*supports_rich_media=*/true); EXPECT_TRUE(images_data); EXPECT_THAT(images_data->campaigns[0].creatives, ::testing::SizeIs(1)); EXPECT_THAT(images_data->top_sites, ::testing::SizeIs(3)); @@ -943,7 +954,8 @@ TEST_F(NTPBackgroundImagesServiceTest, WithNonSuperReferralCodeTest) { kTestSponsoredImages); // NTP SI data is ready but don't give data until NTP SR initialization is // complete. Only gives NTP SI data when browser confirms this is not NTP SR. - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); observer_.on_super_referral_ended = false; service_->OnGetMappingTableData(kTestMappingTable); @@ -1000,7 +1012,8 @@ TEST_F(NTPBackgroundImagesServiceTest, WithSuperReferralCodeTest) { EXPECT_FALSE(pref_service_.GetBoolean( prefs::kNewTabPageGetInitialSuperReferralComponentInProgress)); const NTPSponsoredImagesData* const data = - service_->GetBrandedImagesData(/*super_referral=*/true); + service_->GetSponsoredImagesData(/*super_referral=*/true, + /*supports_rich_media=*/true); EXPECT_TRUE(service_->IsValidSuperReferralComponentInfo(pref_service_.GetDict( prefs::kNewTabPageCachedSuperReferralComponentInfo))); EXPECT_TRUE(data->IsSuperReferral()); @@ -1029,19 +1042,23 @@ TEST_F(NTPBackgroundImagesServiceTest, CheckReferralServiceInitStatusTest) { Init(); // Initially, data is not available. - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/true)); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/true, + /*supports_rich_media=*/true)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); // Simulate SI data is initialized first before referral service is // initialized. // Check SI data is not available before referrals service is initialized. service_->OnGetSponsoredComponentJsonData(/*is_super_referral=*/false, kTestSponsoredImages); - EXPECT_FALSE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_FALSE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); // Simulate that this install is not SR. Then, SI data is returned properly. service_->MarkThisInstallIsNotSuperReferralForever(); - EXPECT_TRUE(service_->GetBrandedImagesData(/*super_referral=*/false)); + EXPECT_TRUE(service_->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/true)); } TEST_F(NTPBackgroundImagesServiceTest, diff --git a/components/ntp_background_images/browser/ntp_background_images_source.cc b/components/ntp_background_images/browser/ntp_background_images_source.cc index 6cd6045bad1f..1154ce75097d 100644 --- a/components/ntp_background_images/browser/ntp_background_images_source.cc +++ b/components/ntp_background_images/browser/ntp_background_images_source.cc @@ -35,8 +35,8 @@ std::optional ReadFileToString(const base::FilePath& path) { } // namespace NTPBackgroundImagesSource::NTPBackgroundImagesSource( - NTPBackgroundImagesService* service) - : service_(service), weak_factory_(this) {} + NTPBackgroundImagesService* background_images_service) + : background_images_service_(background_images_service) {} NTPBackgroundImagesSource::~NTPBackgroundImagesSource() = default; @@ -51,7 +51,7 @@ void NTPBackgroundImagesSource::StartDataRequest( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const NTPBackgroundImagesData* const images_data = - service_->GetBackgroundImagesData(); + background_images_service_->GetBackgroundImagesData(); const std::string path = URLDataSource::URLToRequestPath(url); const int index = GetWallpaperIndexFromPath(path); @@ -110,7 +110,7 @@ std::string NTPBackgroundImagesSource::GetMimeType(const GURL& url) { int NTPBackgroundImagesSource::GetWallpaperIndexFromPath( const std::string& path) const { const NTPBackgroundImagesData* const images_data = - service_->GetBackgroundImagesData(); + background_images_service_->GetBackgroundImagesData(); if (!images_data) { return -1; } diff --git a/components/ntp_background_images/browser/ntp_background_images_source.h b/components/ntp_background_images/browser/ntp_background_images_source.h index 14ccb8253f58..bfbb2beaaaee 100644 --- a/components/ntp_background_images/browser/ntp_background_images_source.h +++ b/components/ntp_background_images/browser/ntp_background_images_source.h @@ -25,7 +25,8 @@ class NTPBackgroundImagesService; // This serves background image data. class NTPBackgroundImagesSource : public content::URLDataSource { public: - explicit NTPBackgroundImagesSource(NTPBackgroundImagesService* service); + explicit NTPBackgroundImagesSource( + NTPBackgroundImagesService* background_images_service); ~NTPBackgroundImagesSource() override; @@ -51,8 +52,10 @@ class NTPBackgroundImagesSource : public content::URLDataSource { std::optional input); int GetWallpaperIndexFromPath(const std::string& path) const; - raw_ptr service_ = nullptr; // not owned - base::WeakPtrFactory weak_factory_; + raw_ptr background_images_service_ = + nullptr; // Not owned. + + base::WeakPtrFactory weak_factory_{this}; }; } // namespace ntp_background_images diff --git a/components/ntp_background_images/browser/ntp_custom_images_source.cc b/components/ntp_background_images/browser/ntp_custom_images_source.cc index b3c3b284463d..1f5516ff8a0e 100644 --- a/components/ntp_background_images/browser/ntp_custom_images_source.cc +++ b/components/ntp_background_images/browser/ntp_custom_images_source.cc @@ -29,9 +29,9 @@ std::string ReadFileToString(const base::FilePath& path) { } // namespace NTPCustomImagesSource::NTPCustomImagesSource( - BraveNTPCustomBackgroundService* service) - : service_(service), weak_factory_(this) { - DCHECK(service_); + BraveNTPCustomBackgroundService* custom_background_service) + : custom_background_service_(custom_background_service) { + DCHECK(custom_background_service_); } NTPCustomImagesSource::~NTPCustomImagesSource() = default; @@ -45,7 +45,8 @@ void NTPCustomImagesSource::StartDataRequest( const content::WebContents::Getter& /*wc_getter*/, GotDataCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - GetImageFile(service_->GetImageFilePath(url), std::move(callback)); + GetImageFile(custom_background_service_->GetImageFilePath(url), + std::move(callback)); } std::string NTPCustomImagesSource::GetMimeType(const GURL& /*url*/) { diff --git a/components/ntp_background_images/browser/ntp_custom_images_source.h b/components/ntp_background_images/browser/ntp_custom_images_source.h index 22872933df5a..efe248f11afb 100644 --- a/components/ntp_background_images/browser/ntp_custom_images_source.h +++ b/components/ntp_background_images/browser/ntp_custom_images_source.h @@ -23,7 +23,8 @@ class BraveNTPCustomBackgroundService; // This serves background image data. class NTPCustomImagesSource : public content::URLDataSource { public: - explicit NTPCustomImagesSource(BraveNTPCustomBackgroundService* service); + explicit NTPCustomImagesSource( + BraveNTPCustomBackgroundService* custom_background_service); ~NTPCustomImagesSource() override; NTPCustomImagesSource(const NTPCustomImagesSource&) = delete; @@ -42,9 +43,10 @@ class NTPCustomImagesSource : public content::URLDataSource { GotDataCallback callback); void OnGotImageFile(GotDataCallback callback, const std::string& input); - raw_ptr service_ = - nullptr; // not owned - base::WeakPtrFactory weak_factory_; + raw_ptr + custom_background_service_ = nullptr; // Not owned. + + base::WeakPtrFactory weak_factory_{this}; }; } // namespace ntp_background_images diff --git a/components/ntp_background_images/browser/ntp_sponsored_image_source.cc b/components/ntp_background_images/browser/ntp_sponsored_image_source.cc index a8cc49fb364c..9a7f93feec4e 100644 --- a/components/ntp_background_images/browser/ntp_sponsored_image_source.cc +++ b/components/ntp_background_images/browser/ntp_sponsored_image_source.cc @@ -37,8 +37,8 @@ bool IsSuperReferralPath(const std::string& path) { } // namespace NTPSponsoredImageSource::NTPSponsoredImageSource( - NTPBackgroundImagesService* service) - : service_(service), weak_factory_(this) {} + NTPBackgroundImagesService* background_images_service) + : background_images_service_(background_images_service) {} NTPSponsoredImageSource::~NTPSponsoredImageSource() = default; @@ -113,7 +113,9 @@ base::FilePath NTPSponsoredImageSource::GetLocalFilePathFor( const std::string& path) { const bool is_super_referral_path = IsSuperReferralPath(path); const NTPSponsoredImagesData* const images_data = - service_->GetBrandedImagesData(is_super_referral_path); + background_images_service_->GetSponsoredImagesData( + is_super_referral_path, + /*supports_rich_media=*/false); CHECK(images_data); const base::FilePath basename_from_path = @@ -150,7 +152,9 @@ base::FilePath NTPSponsoredImageSource::GetLocalFilePathFor( bool NTPSponsoredImageSource::IsValidPath(const std::string& path) const { const bool is_super_referral_path = IsSuperReferralPath(path); const NTPSponsoredImagesData* const images_data = - service_->GetBrandedImagesData(is_super_referral_path); + background_images_service_->GetSponsoredImagesData( + is_super_referral_path, + /*supports_rich_media=*/false); if (!images_data) { return false; } diff --git a/components/ntp_background_images/browser/ntp_sponsored_image_source.h b/components/ntp_background_images/browser/ntp_sponsored_image_source.h index 0c51d19b653d..4d2c0f1a267d 100644 --- a/components/ntp_background_images/browser/ntp_sponsored_image_source.h +++ b/components/ntp_background_images/browser/ntp_sponsored_image_source.h @@ -25,7 +25,8 @@ class NTPBackgroundImagesService; // This serves background image data. class NTPSponsoredImageSource : public content::URLDataSource { public: - explicit NTPSponsoredImageSource(NTPBackgroundImagesService* service); + explicit NTPSponsoredImageSource( + NTPBackgroundImagesService* background_images_service); ~NTPSponsoredImageSource() override; @@ -52,9 +53,10 @@ class NTPSponsoredImageSource : public content::URLDataSource { std::optional input); bool IsValidPath(const std::string& path) const; - raw_ptr service_ = nullptr; // not owned + raw_ptr background_images_service_ = + nullptr; // Not owned. - base::WeakPtrFactory weak_factory_; + base::WeakPtrFactory weak_factory_{this}; }; } // namespace ntp_background_images diff --git a/components/ntp_background_images/browser/ntp_sponsored_images_data.cc b/components/ntp_background_images/browser/ntp_sponsored_images_data.cc index 1810c3a6b9e1..0b54bb6aa113 100644 --- a/components/ntp_background_images/browser/ntp_sponsored_images_data.cc +++ b/components/ntp_background_images/browser/ntp_sponsored_images_data.cc @@ -101,11 +101,13 @@ Logo& Logo::operator=(Logo&& other) noexcept = default; Logo::~Logo() = default; Creative::Creative() = default; -Creative::Creative(const base::FilePath& file_path, +Creative::Creative(WallpaperType wallpaper_type, + const base::FilePath& file_path, const gfx::Point& point, const Logo& test_logo, const std::string& creative_instance_id) - : file_path(file_path), + : wallpaper_type(wallpaper_type), + file_path(file_path), focal_point(point), creative_instance_id(creative_instance_id), logo(test_logo) {} @@ -324,15 +326,15 @@ std::optional NTPSponsoredImagesData::ParseCampaign( } // Wallpaper. - const base::Value::Dict* const wallpaper = + const base::Value::Dict* const wallpaper_dict = creative_dict->FindDict(kWallpaperKey); - if (!wallpaper) { + if (!wallpaper_dict) { // Wallpaper is required. continue; } const std::string* const wallpaper_type = - wallpaper->FindString(kWallpaperTypeKey); + wallpaper_dict->FindString(kWallpaperTypeKey); if (!wallpaper_type) { // Wallpaper type is required. continue; @@ -343,7 +345,7 @@ std::optional NTPSponsoredImagesData::ParseCampaign( creative.wallpaper_type = WallpaperType::kImage; const std::string* const relative_url = - wallpaper->FindString(kImageWallpaperRelativeUrlKey); + wallpaper_dict->FindString(kImageWallpaperRelativeUrlKey); if (!relative_url) { // Relative url is required. continue; @@ -357,38 +359,38 @@ std::optional NTPSponsoredImagesData::ParseCampaign( // Focal point (optional). const int focal_point_x = - wallpaper->FindIntByDottedPath(kImageWallpaperFocalPointXKey) + wallpaper_dict->FindIntByDottedPath(kImageWallpaperFocalPointXKey) .value_or(0); const int focal_point_y = - wallpaper->FindIntByDottedPath(kImageWallpaperFocalPointYKey) + wallpaper_dict->FindIntByDottedPath(kImageWallpaperFocalPointYKey) .value_or(0); creative.focal_point = {focal_point_x, focal_point_y}; // View box (optional, only used on iOS). const int view_box_x = - wallpaper->FindIntByDottedPath(kImageWallpaperViewBoxXKey) + wallpaper_dict->FindIntByDottedPath(kImageWallpaperViewBoxXKey) .value_or(0); const int view_box_y = - wallpaper->FindIntByDottedPath(kImageWallpaperViewBoxYKey) + wallpaper_dict->FindIntByDottedPath(kImageWallpaperViewBoxYKey) .value_or(0); const int view_box_width = - wallpaper->FindIntByDottedPath(kImageWallpaperViewBoxWidthKey) + wallpaper_dict->FindIntByDottedPath(kImageWallpaperViewBoxWidthKey) .value_or(0); const int view_box_height = - wallpaper->FindIntByDottedPath(kImageWallpaperViewBoxHeightKey) + wallpaper_dict->FindIntByDottedPath(kImageWallpaperViewBoxHeightKey) .value_or(0); creative.viewbox = {view_box_x, view_box_y, view_box_width, view_box_height}; // Background color (optional, only used on iOS). if (const std::string* const background_color = - wallpaper->FindString(kImageWallpaperBackgroundColorKey)) { + wallpaper_dict->FindString(kImageWallpaperBackgroundColorKey)) { creative.background_color = *background_color; } // Button. const std::string* const button_image_relative_url = - wallpaper->FindStringByDottedPath( + wallpaper_dict->FindStringByDottedPath( kImageWallpaperButtonImageRelativeUrlKey); if (!button_image_relative_url) { // Relative url is required. @@ -407,7 +409,7 @@ std::optional NTPSponsoredImagesData::ParseCampaign( creative.wallpaper_type = WallpaperType::kRichMedia; const std::string* const relative_url = - wallpaper->FindStringByDottedPath( + wallpaper_dict->FindStringByDottedPath( kRichMediaWallpaperRelativeUrlKey); if (!relative_url) { // Relative url is required. @@ -420,7 +422,7 @@ std::optional NTPSponsoredImagesData::ParseCampaign( creative.file_path = installed_dir.AppendASCII(*relative_url); creative.url = GURL(kNTPNewTabTakeoverRichMediaUrl + *relative_url); } else { - // Invalid wallpaper type. + // Unknown wallpaper type. continue; } diff --git a/components/ntp_background_images/browser/ntp_sponsored_images_data.h b/components/ntp_background_images/browser/ntp_sponsored_images_data.h index 285e36401767..c61ed80b5511 100644 --- a/components/ntp_background_images/browser/ntp_sponsored_images_data.h +++ b/components/ntp_background_images/browser/ntp_sponsored_images_data.h @@ -76,7 +76,8 @@ struct Creative { Creative(); // For unit test. - Creative(const base::FilePath& file_path, + Creative(WallpaperType wallpaper_type, + const base::FilePath& file_path, const gfx::Point& point, const Logo& test_logo, const std::string& creative_instance_id); diff --git a/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.cc b/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.cc index 05d9302487a4..7352fb10d6f6 100644 --- a/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.cc +++ b/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.cc @@ -38,8 +38,8 @@ std::optional ReadFileToString(const base::FilePath& path) { } // namespace NTPSponsoredRichMediaSource::NTPSponsoredRichMediaSource( - NTPBackgroundImagesService* service) - : service_(service), weak_factory_(this) {} + NTPBackgroundImagesService* background_images_service) + : background_images_service_(background_images_service) {} NTPSponsoredRichMediaSource::~NTPSponsoredRichMediaSource() = default; @@ -53,12 +53,14 @@ void NTPSponsoredRichMediaSource::StartDataRequest( GotDataCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!service_) { + if (!background_images_service_) { return DenyAccess(std::move(callback)); } const NTPSponsoredImagesData* const images_data = - service_->GetBrandedImagesData(/*super_referral=*/false); + background_images_service_->GetSponsoredImagesData( + /*super_referral=*/false, + /*supports_rich_media=*/true); if (!images_data) { return DenyAccess(std::move(callback)); } diff --git a/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.h b/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.h index bb2cf3a2ac74..bda0a65e7730 100644 --- a/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.h +++ b/components/ntp_background_images/browser/ntp_sponsored_rich_media_source.h @@ -23,7 +23,8 @@ class NTPBackgroundImagesService; class NTPSponsoredRichMediaSource : public content::URLDataSource { public: - explicit NTPSponsoredRichMediaSource(NTPBackgroundImagesService* service); + explicit NTPSponsoredRichMediaSource( + NTPBackgroundImagesService* background_images_service); NTPSponsoredRichMediaSource(const NTPSponsoredRichMediaSource&) = delete; NTPSponsoredRichMediaSource& operator=(const NTPSponsoredRichMediaSource&) = @@ -47,9 +48,10 @@ class NTPSponsoredRichMediaSource : public content::URLDataSource { void DenyAccess(GotDataCallback callback); - const raw_ptr service_; // not owned. + const raw_ptr + background_images_service_; // Not owned. - base::WeakPtrFactory weak_factory_; + base::WeakPtrFactory weak_factory_{this}; }; } // namespace ntp_background_images diff --git a/components/ntp_background_images/browser/ntp_sponsored_rich_media_source_unittest.cc b/components/ntp_background_images/browser/ntp_sponsored_rich_media_source_unittest.cc index e54fcd720897..07202f153fd7 100644 --- a/components/ntp_background_images/browser/ntp_sponsored_rich_media_source_unittest.cc +++ b/components/ntp_background_images/browser/ntp_sponsored_rich_media_source_unittest.cc @@ -73,7 +73,7 @@ class NTPSponsoredRichMediaSourceTest : public testing::Test { background_images_service_ = std::make_unique( /*component_update_service=*/nullptr, &pref_service_); url_data_source_ = std::make_unique( - background_images_service_.get()); + background_images_service_.get(), &pref_service_); } void SetupSponsoredComponent() { diff --git a/components/ntp_background_images/browser/view_counter_model.cc b/components/ntp_background_images/browser/view_counter_model.cc index 1c9714384007..3c63b21e93e1 100644 --- a/components/ntp_background_images/browser/view_counter_model.cc +++ b/components/ntp_background_images/browser/view_counter_model.cc @@ -56,7 +56,7 @@ std::tuple ViewCounterModel::GetCurrentBrandedImageIndex() campaigns_current_branded_image_index_[current_campaign_index_]}; } -bool ViewCounterModel::ShouldShowBrandedWallpaper() const { +bool ViewCounterModel::ShouldShowSponsoredImages() const { if (always_show_branded_wallpaper_) { return true; } diff --git a/components/ntp_background_images/browser/view_counter_model.h b/components/ntp_background_images/browser/view_counter_model.h index c0888ca47a58..47771a86a7b3 100644 --- a/components/ntp_background_images/browser/view_counter_model.h +++ b/components/ntp_background_images/browser/view_counter_model.h @@ -45,7 +45,7 @@ class ViewCounterModel { void set_show_branded_wallpaper(bool show) { show_branded_wallpaper_ = show; } void set_show_wallpaper(bool show) { show_wallpaper_ = show; } - bool ShouldShowBrandedWallpaper() const; + bool ShouldShowSponsoredImages() const; void RegisterPageView(); void MaybeResetBrandedWallpaperCount(); void NextBrandedImage(); @@ -53,7 +53,7 @@ class ViewCounterModel { void RotateBackgroundWallpaperImageIndex(); private: - friend class NTPBackgroundImagesViewCounterTest; + friend class ViewCounterServiceTest; FRIEND_TEST_ALL_PREFIXES(ViewCounterModelTest, NTPSponsoredImagesTest); FRIEND_TEST_ALL_PREFIXES(ViewCounterModelTest, NTPSponsoredImagesCountResetTest); @@ -70,9 +70,8 @@ class ViewCounterModel { NTPBackgroundImagesWithEmptyCampaignTest); FRIEND_TEST_ALL_PREFIXES(ViewCounterModelTest, NTPFailedToLoadSponsoredImagesTest); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, ModelTest); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - PrefsWithModelTest); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, ModelTest); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, PrefsWithModelTest); void RegisterPageViewForBrandedImages(); diff --git a/components/ntp_background_images/browser/view_counter_model_unittest.cc b/components/ntp_background_images/browser/view_counter_model_unittest.cc index 4a0ccc3be177..7fb57dcbb4d5 100644 --- a/components/ntp_background_images/browser/view_counter_model_unittest.cc +++ b/components/ntp_background_images/browser/view_counter_model_unittest.cc @@ -66,13 +66,13 @@ TEST_F(ViewCounterModelTest, NTPSponsoredImagesTest) { // Loading initial count times. for (int i = 0; i < features::kInitialCountToBrandedWallpaper.Get() - 1; ++i) { - EXPECT_FALSE(model.ShouldShowBrandedWallpaper()); + EXPECT_FALSE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); } for (size_t i = 0; i < 30; i++) { // Random image should be displayed now after loading initial count. - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); const auto [campaign_index, image_index] = model.GetCurrentBrandedImageIndex(); @@ -82,7 +82,7 @@ TEST_F(ViewCounterModelTest, NTPSponsoredImagesTest) { // Loading regular-count times. for (int j = 0; j < features::kCountToBrandedWallpaper.Get() - 1; ++j) { - EXPECT_FALSE(model.ShouldShowBrandedWallpaper()); + EXPECT_FALSE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); } } @@ -105,22 +105,22 @@ TEST_F(ViewCounterModelTest, NTPSponsoredImagesCountToBrandedWallpaperTest) { EXPECT_FALSE(model.always_show_branded_wallpaper_); // Count is 1 so we should not show branded wallpaper. - EXPECT_FALSE(model.ShouldShowBrandedWallpaper()); + EXPECT_FALSE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); // Count is 0 so we should show branded wallpaper. - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); // Loading regular-count times from kCountToBrandedWallpaper to 0 and do not // show branded wallpaper. for (int i = 0; i < features::kCountToBrandedWallpaper.Get() - 1; ++i) { - EXPECT_FALSE(model.ShouldShowBrandedWallpaper()); + EXPECT_FALSE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); } // Count is 0 so we should show branded wallpaper. - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); } @@ -131,9 +131,9 @@ TEST_F(ViewCounterModelTest, NTPSponsoredImagesCountResetTest) { // Verify param value for initial count was used EXPECT_EQ(1, model.count_to_branded_wallpaper_); model.RegisterPageView(); - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); - EXPECT_FALSE(model.ShouldShowBrandedWallpaper()); + EXPECT_FALSE(model.ShouldShowSponsoredImages()); EXPECT_EQ(3, model.count_to_branded_wallpaper_); // We expect to be reset to initial count when source data updates (which @@ -149,13 +149,13 @@ TEST_F(ViewCounterModelTest, NTPSponsoredImagesCountResetMinTest) { // Verify param value for initial count was used EXPECT_EQ(1, model.count_to_branded_wallpaper_); model.RegisterPageView(); - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); EXPECT_EQ(0, model.count_to_branded_wallpaper_); // We expect to be reset to initial count only if count_to_branded_wallpaper_ // is higher than initial count. model.Reset(); - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); EXPECT_EQ(0, model.count_to_branded_wallpaper_); } @@ -166,9 +166,9 @@ TEST_F(ViewCounterModelTest, NTPSponsoredImagesCountResetTimerTest) { // Verify param value for initial count was used EXPECT_EQ(1, model.count_to_branded_wallpaper_); model.RegisterPageView(); - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); model.RegisterPageView(); - EXPECT_FALSE(model.ShouldShowBrandedWallpaper()); + EXPECT_FALSE(model.ShouldShowSponsoredImages()); EXPECT_EQ(3, model.count_to_branded_wallpaper_); task_environment_.FastForwardBy(features::kResetCounterAfter.Get()); EXPECT_EQ(1, model.count_to_branded_wallpaper_); @@ -274,7 +274,7 @@ TEST_F(ViewCounterModelTest, NTPSuperReferralTest) { // Loading any number of times and check branded wallpaper is visible always // with proper index from the start. for (int i = 0; i < 10; ++i) { - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); const auto current_index = model.GetCurrentBrandedImageIndex(); // Always first campaign is used in SR mode. EXPECT_EQ(0UL, std::get<0>(current_index)); @@ -298,7 +298,7 @@ TEST_F(ViewCounterModelTest, NTPFailedToLoadSponsoredImagesTest) { EXPECT_EQ(i, model.current_wallpaper_image_index()); model.RegisterPageView(); } - EXPECT_TRUE(model.ShouldShowBrandedWallpaper()); + EXPECT_TRUE(model.ShouldShowSponsoredImages()); const int initial_wallpaper_image_index = model.current_wallpaper_image_index(); diff --git a/components/ntp_background_images/browser/view_counter_service.cc b/components/ntp_background_images/browser/view_counter_service.cc index 1582cac646d2..639586724a77 100644 --- a/components/ntp_background_images/browser/view_counter_service.cc +++ b/components/ntp_background_images/browser/view_counter_service.cc @@ -29,6 +29,9 @@ #include "brave/components/ntp_background_images/common/pref_names.h" #include "brave/components/p3a_utils/bucket.h" #include "brave/components/time_period_storage/weekly_storage.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings.h" +#include "components/content_settings/core/common/content_settings_pattern.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui_data_source.h" @@ -91,6 +94,7 @@ void ViewCounterService::MigrateObsoleteProfilePrefs(PrefService* prefs) { } ViewCounterService::ViewCounterService( + HostContentSettingsMap* host_content_settings_map, NTPBackgroundImagesService* background_images_service, BraveNTPCustomBackgroundService* custom_background_service, brave_ads::AdsService* ads_service, @@ -98,7 +102,8 @@ ViewCounterService::ViewCounterService( PrefService* local_state, std::unique_ptr ntp_p3a_helper, bool is_supported_locale) - : background_images_service_(background_images_service), + : host_content_settings_map_(host_content_settings_map), + background_images_service_(background_images_service), ads_service_(ads_service), prefs_(prefs), local_state_prefs_(local_state), @@ -110,6 +115,8 @@ ViewCounterService::ViewCounterService( ntp_background_images_service_observation_.Observe( background_images_service_); + host_content_settings_map_->AddObserver(this); + new_tab_count_state_ = std::make_unique(local_state, kNewTabsCreated); branded_new_tab_count_state_ = @@ -135,13 +142,25 @@ ViewCounterService::ViewCounterService( base::BindRepeating(&ViewCounterService::OnPreferenceChanged, weak_ptr_factory_.GetWeakPtr())); - OnBackgroundImagesDataDidUpdate(GetCurrentWallpaperData()); - OnSponsoredImagesDataDidUpdate(GetCurrentBrandedWallpaperData()); + OnBackgroundImagesDataDidUpdate( + background_images_service_->GetBackgroundImagesData()); + OnSponsoredImagesDataDidUpdate(GetSponsoredImagesData()); UpdateP3AValues(); } -ViewCounterService::~ViewCounterService() = default; +ViewCounterService::~ViewCounterService() { + host_content_settings_map_->RemoveObserver(this); +} + +void ViewCounterService::OnContentSettingChanged( + const ContentSettingsPattern& /*primary_pattern*/, + const ContentSettingsPattern& /*secondary_pattern*/, + ContentSettingsTypeSet content_type_set) { + if (content_type_set.Contains(ContentSettingsType::JAVASCRIPT)) { + ResetModel(); + } +} void ViewCounterService::BrandedWallpaperWillBeDisplayed( const std::string& wallpaper_id, @@ -160,20 +179,23 @@ void ViewCounterService::BrandedWallpaperWillBeDisplayed( UpdateP3AValues(); } -NTPBackgroundImagesData* ViewCounterService::GetCurrentWallpaperData() const { - return background_images_service_->GetBackgroundImagesData(); -} +NTPSponsoredImagesData* ViewCounterService::GetSponsoredImagesData() const { + const ContentSetting content_setting = + host_content_settings_map_->GetDefaultContentSetting( + ContentSettingsType::JAVASCRIPT); + const bool supports_rich_media = + content_setting == CONTENT_SETTING_ALLOW || + content_setting == CONTENT_SETTING_SESSION_ONLY; -NTPSponsoredImagesData* ViewCounterService::GetCurrentBrandedWallpaperData() - const { - NTPSponsoredImagesData* const images_data = - background_images_service_->GetBrandedImagesData(/*super_referral=*/true); - if (images_data && IsSuperReferralWallpaperOptedIn()) { - return images_data; + NTPSponsoredImagesData* sponsored_images_data = + background_images_service_->GetSponsoredImagesData( + /*super_referral=*/true, supports_rich_media); + if (sponsored_images_data && IsSuperReferralWallpaperOptedIn()) { + return sponsored_images_data; } - return background_images_service_->GetBrandedImagesData( - /*super_referral=*/false); + return background_images_service_->GetSponsoredImagesData( + /*super_referral=*/false, supports_rich_media); } std::optional @@ -184,7 +206,7 @@ ViewCounterService::GetNextWallpaperForDisplay() { std::optional ViewCounterService::GetCurrentWallpaperForDisplay() { - if (!ShouldShowBrandedWallpaper()) { + if (!ShouldShowSponsoredImages()) { return GetCurrentWallpaper(); } @@ -202,7 +224,7 @@ ViewCounterService::GetCurrentWallpaperForDisplay() { std::optional ViewCounterService::GetCurrentWallpaper() const { - if (!IsBackgroundWallpaperActive()) { + if (!CanShowBackgroundImages()) { return std::nullopt; } @@ -215,7 +237,8 @@ std::optional ViewCounterService::GetCurrentWallpaper() } #endif - const NTPBackgroundImagesData* const images_data = GetCurrentWallpaperData(); + const NTPBackgroundImagesData* const images_data = + background_images_service_->GetBackgroundImagesData(); if (!images_data) { CHECK_IS_TEST(); return std::nullopt; @@ -227,7 +250,7 @@ std::optional ViewCounterService::GetCurrentWallpaper() std::optional ViewCounterService::GetCurrentBrandedWallpaper() { - NTPSponsoredImagesData* images_data = GetCurrentBrandedWallpaperData(); + NTPSponsoredImagesData* images_data = GetSponsoredImagesData(); if (!images_data) { return std::nullopt; } @@ -375,12 +398,12 @@ ViewCounterService::GetCurrentBrandedWallpaperFromAdInfo() const { DCHECK(ads_service_); const std::optional ad = - ads_service_->MaybeGetPrefetchedNewTabPageAdForDisplay(); + ads_service_->MaybeGetPrefetchedNewTabPageAd(); if (!ad) { return std::nullopt; } - NTPSponsoredImagesData* images_data = GetCurrentBrandedWallpaperData(); + NTPSponsoredImagesData* images_data = GetSponsoredImagesData(); if (!images_data) { return std::nullopt; } @@ -400,13 +423,13 @@ ViewCounterService::GetCurrentBrandedWallpaperFromModel() const { size_t current_creative_index; std::tie(current_campaign_index, current_creative_index) = model_.GetCurrentBrandedImageIndex(); - return GetCurrentBrandedWallpaperData()->GetBackgroundAt( - current_campaign_index, current_creative_index); + return GetSponsoredImagesData()->GetBackgroundAt(current_campaign_index, + current_creative_index); } std::vector ViewCounterService::GetTopSitesData() const { if (const NTPSponsoredImagesData* const images_data = - GetCurrentBrandedWallpaperData()) { + GetSponsoredImagesData()) { return images_data->top_sites; } @@ -465,7 +488,7 @@ void ViewCounterService::ResetModel() { prefs_->GetBoolean(prefs::kNewTabPageShowBackgroundImage)); if (const NTPSponsoredImagesData* const images_data = - GetCurrentBrandedWallpaperData()) { + GetSponsoredImagesData()) { std::vector campaigns_total_branded_images_count; campaigns_total_branded_images_count.reserve(images_data->campaigns.size()); for (const auto& campaign : images_data->campaigns) { @@ -477,7 +500,7 @@ void ViewCounterService::ResetModel() { } if (const NTPBackgroundImagesData* const images_data = - GetCurrentWallpaperData()) { + background_images_service_->GetBackgroundImagesData()) { model_.set_total_image_count( static_cast(images_data->backgrounds.size())); } @@ -541,8 +564,8 @@ void ViewCounterService::MaybeTriggerNewTabPageAdEvent( } } -bool ViewCounterService::ShouldShowBrandedWallpaper() const { - return IsBrandedWallpaperActive() && model_.ShouldShowBrandedWallpaper(); +bool ViewCounterService::ShouldShowSponsoredImages() const { + return CanShowSponsoredImages() && model_.ShouldShowSponsoredImages(); } bool ViewCounterService::ShouldShowCustomBackground() const { @@ -565,14 +588,14 @@ void ViewCounterService::OnTabURLChanged(const GURL& url) { } } -bool ViewCounterService::IsBrandedWallpaperActive() const { - if (!GetCurrentBrandedWallpaperData()) { +bool ViewCounterService::CanShowSponsoredImages() const { + if (!GetSponsoredImagesData()) { return false; } // We show SR regardless of ntp background images option because SR works // like theme. - if (GetCurrentBrandedWallpaperData()->IsSuperReferral() && + if (GetSponsoredImagesData()->IsSuperReferral() && IsSuperReferralWallpaperOptedIn()) { return true; } @@ -585,14 +608,15 @@ bool ViewCounterService::IsBrandedWallpaperActive() const { return IsSponsoredImagesWallpaperOptedIn(); } -bool ViewCounterService::IsBackgroundWallpaperActive() const { +bool ViewCounterService::CanShowBackgroundImages() const { #if !BUILDFLAG(IS_ANDROID) if (!prefs_->GetBoolean(prefs::kNewTabPageShowBackgroundImage)) { return false; } #endif - return !!GetCurrentWallpaperData() || ShouldShowCustomBackground(); + return !!background_images_service_->GetBackgroundImagesData() || + ShouldShowCustomBackground(); } bool ViewCounterService::IsSponsoredImagesWallpaperOptedIn() const { @@ -619,8 +643,8 @@ std::string ViewCounterService::GetSuperReferralCode() const { } void ViewCounterService::MaybePrefetchNewTabPageAd() { - NTPSponsoredImagesData* images_data = GetCurrentBrandedWallpaperData(); - if (!ads_service_ || !IsBrandedWallpaperActive() || + NTPSponsoredImagesData* images_data = GetSponsoredImagesData(); + if (!ads_service_ || !CanShowSponsoredImages() || !prefs_->GetBoolean(brave_rewards::prefs::kEnabled) || !images_data || images_data->IsSuperReferral()) { return; diff --git a/components/ntp_background_images/browser/view_counter_service.h b/components/ntp_background_images/browser/view_counter_service.h index 3b149ce890f1..6f356e02516f 100644 --- a/components/ntp_background_images/browser/view_counter_service.h +++ b/components/ntp_background_images/browser/view_counter_service.h @@ -23,6 +23,7 @@ #include "brave/components/ntp_background_images/browser/ntp_background_images_service.h" #include "brave/components/ntp_background_images/browser/view_counter_model.h" #include "brave/components/ntp_background_images/buildflags/buildflags.h" +#include "components/content_settings/core/browser/content_settings_observer.h" #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_change_registrar.h" @@ -42,6 +43,7 @@ namespace user_prefs { class PrefRegistrySyncable; } // namespace user_prefs +class HostContentSettingsMap; class WeeklyStorage; namespace ntp_background_images { @@ -54,9 +56,11 @@ struct NTPSponsoredImagesData; struct TopSite; class ViewCounterService : public KeyedService, + public content_settings::Observer, public NTPBackgroundImagesService::Observer { public: - ViewCounterService(NTPBackgroundImagesService* background_images_service, + ViewCounterService(HostContentSettingsMap* host_content_settings, + NTPBackgroundImagesService* background_images_service, BraveNTPCustomBackgroundService* custom_background_service, brave_ads::AdsService* ads_service, PrefService* prefs, @@ -113,12 +117,7 @@ class ViewCounterService : public KeyedService, void BrandedWallpaperWillBeDisplayed(const std::string& wallpaper_id, const std::string& creative_instance_id, const std::string& campaign_id); - - NTPBackgroundImagesData* GetCurrentWallpaperData() const; - // Gets the current data for branded wallpaper, if there - // is a wallpaper active. Does not consider user opt-in - // status, or consider whether the wallpaper should be shown. - NTPSponsoredImagesData* GetCurrentBrandedWallpaperData() const; + NTPSponsoredImagesData* GetSponsoredImagesData() const; void InitializeWebUIDataSource(content::WebUIDataSource* html_source); @@ -131,36 +130,56 @@ class ViewCounterService : public KeyedService, SUPER_REFERRAL, }; - friend class NTPBackgroundImagesViewCounterTest; - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - SINotActiveInitially); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - SINotActiveWithBadData); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - NotActiveOptedOut); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, IsActiveOptedIn); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - ActiveInitiallyOptedIn); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, + friend class ViewCounterServiceTest; + friend class NTPBackgroundImagesServiceTest; + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CanShowSponsoredImages); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CannotShowSponsoredImages); + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + AllowNewTabTakeoverWithRichMediaIfJavaScriptContentSettingIsSetToAllowed); + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + BlockNewTabTakeoverWithRichMediaIfJavaScriptContentSettingIsSetToBlocked); + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + AllowNewTabTakeOverWithImageIfJavaScriptContentSettingIsSetToAllowed); + FRIEND_TEST_ALL_PREFIXES( + ViewCounterServiceTest, + AllowNewTabTakeoverWithImageIfJavaScriptContentSettingIsSetToBlocked); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowSponsoredImagesIfUninitialized); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowSponsoredImagesIfMalformed); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowSponsoredImagesIfOptedOut); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, IsActiveOptedIn); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, ActiveInitiallyOptedIn); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, ActiveOptedInWithNTPBackgoundOption); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, ModelTest); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - BINotActiveInitially); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - BINotActiveWithBadData); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - BINotActiveWithNTPBackgoundOptionOptedOut); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - PrefsWithModelTest); - FRIEND_TEST_ALL_PREFIXES(NTPBackgroundImagesViewCounterTest, - GetCurrentWallpaperTest); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, ModelTest); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CanShowBackgroundImages); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, CannotShowBackgroundImages); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowBackgroundImagesIfUninitialized); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowBackgroundImagesIfMalformed); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, + CannotShowBackgroundImagesIfOptedOut); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, PrefsWithModelTest); + FRIEND_TEST_ALL_PREFIXES(ViewCounterServiceTest, GetCurrentWallpaper); void OnPreferenceChanged(const std::string& pref_name); - // KeyedService + // content_settings::Observer: + void OnContentSettingChanged( + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsTypeSet content_type_set) override; + + // KeyedService: void Shutdown() override; - // NTPBackgroundImagesService::Observer + // NTPBackgroundImagesService::Observer: void OnBackgroundImagesDataDidUpdate(NTPBackgroundImagesData* data) override; void OnSponsoredImagesDataDidUpdate(NTPSponsoredImagesData* data) override; void OnSponsoredContentDidUpdate(const base::Value::Dict& data) override; @@ -171,14 +190,16 @@ class ViewCounterService : public KeyedService, void ResetNotificationState(); bool IsSponsoredImagesWallpaperOptedIn() const; bool IsSuperReferralWallpaperOptedIn() const; + // Do we have a sponsored or referral wallpaper to show and has the user // opted-in to showing it at some time. - bool IsBrandedWallpaperActive() const; - // Should we show background image. - bool IsBackgroundWallpaperActive() const; - // Should we show the branded wallpaper right now, in addition - // to the result from `IsBrandedWallpaperActive()`. - bool ShouldShowBrandedWallpaper() const; + bool CanShowSponsoredImages() const; + // Should we show the branded wallpaper right now, in addition to the result + // from `CanShowSponsoredImages()`. + bool ShouldShowSponsoredImages() const; + + bool CanShowBackgroundImages() const; + // Should we show custom background that user uploaded or fill background // with solid color user selected. bool ShouldShowCustomBackground() const; @@ -189,6 +210,7 @@ class ViewCounterService : public KeyedService, void UpdateP3AValues(); + raw_ptr host_content_settings_map_ = nullptr; raw_ptr background_images_service_ = nullptr; raw_ptr ads_service_ = nullptr; raw_ptr prefs_ = nullptr; diff --git a/components/ntp_background_images/browser/view_counter_service_unittest.cc b/components/ntp_background_images/browser/view_counter_service_unittest.cc index 5cbce0904c79..e62a7b2a9aca 100644 --- a/components/ntp_background_images/browser/view_counter_service_unittest.cc +++ b/components/ntp_background_images/browser/view_counter_service_unittest.cc @@ -12,8 +12,10 @@ #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" +#include "base/memory/scoped_refptr.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" +#include "base/test/values_test_util.h" #include "brave/components/brave_ads/browser/ads_service_mock.h" #include "brave/components/brave_ads/core/public/ad_units/new_tab_page_ad/new_tab_page_ad_info.h" #include "brave/components/brave_referrals/browser/brave_referrals_service.h" @@ -30,97 +32,118 @@ #include "brave/components/ntp_background_images/buildflags/buildflags.h" #include "brave/components/ntp_background_images/common/pref_names.h" #include "build/build_config.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings_types.h" #include "components/prefs/testing_pref_service.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "testing/gtest/include/gtest/gtest.h" #if BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) #include "brave/components/ntp_background_images/browser/brave_ntp_custom_background_service.h" -#endif +#endif // BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) namespace ntp_background_images { -using testing::_; -using testing::Return; - namespace { constexpr char kPlacementdId[] = "326eb47b-467b-46ab-ac1b-5f5de780b344"; constexpr char kCampaignId[] = "fb7ee174-5430-4fb9-8e97-29bf14e8d828"; -constexpr char kFirstCreativeInstanceId[] = - "ab257ca5-2bbc-4288-9c06-ce1d5d796343"; - -constexpr char kAltText[] = "Technikke: For music lovers."; -constexpr char kCompanyName[] = "Technikke"; -constexpr char kLogoImageFile[] = "logo_image.png"; -constexpr char kDestinationUrl[] = "https://brave.com"; constexpr char kCreativeInstanceId[] = "c0d61af3-3b85-4af4-a3cc-cf1b3dd40e70"; -constexpr char kSponsoredImageFile[] = "wallpaper2.jpg"; -constexpr int kSponsoredImageFocalPointX = 5233; -constexpr int kSponsoredImageFocalPointY = 3464; +constexpr char kCompanyName[] = "Technikke"; +constexpr char kAltText[] = "Technikke: For music lovers."; +constexpr char kTargetUrl[] = "https://brave.com"; + +constexpr char kSponsoredImageCampaignsJson[] = R"( + { + "schemaVersion": 2, + "campaigns": [ + { + "version": 1, + "campaignId": "65933e82-6b21-440b-9956-c0f675ca7435", + "creativeSets": [ + { + "creativeSetId": "6690ad47-d0af-4dbb-a2dd-c7a678b2b83b", + "creatives": [ + { + "creativeInstanceId": "30244a36-561a-48f0-8d7a-780e9035c57a", + "companyName": "Image NTT Creative", + "alt": "Some content", + "targetUrl": "https://basicattentiontoken.org", + "wallpaper": { + "type": "image", + "relativeUrl": "30244a36-561a-48f0-8d7a-780e9035c57a/background-1.jpg", + "focalPoint": { + "x": 25, + "y": 50 + }, + "button": { + "image": { + "relativeUrl": "30244a36-561a-48f0-8d7a-780e9035c57a/button-1.png" + } + } + } + } + ] + } + ] + } + ] + })"; + +constexpr char kSponsoredRichMediaCampaignsJson[] = R"( + { + "schemaVersion": 2, + "campaigns": [ + { + "version": 1, + "campaignId": "c27a3fae-ee9e-48a2-b3a7-f4675744e6ec", + "creativeSets": [ + { + "creativeSetId": "a245e3b9-2df4-47f5-aaab-67b61c528b6f", + "creatives": [ + { + "creativeInstanceId": "39d78863-327d-4b64-9952-cd0e5e330eb6", + "alt": "Some more rich content", + "companyName": "Another Rich Media NTT Creative", + "targetUrl": "https://basicattentiontoken.org", + "wallpaper": { + "type": "richMedia", + "relativeUrl": "39d78863-327d-4b64-9952-cd0e5e330eb6/index.html" + } + } + ] + } + ] + } + ] + })"; } // namespace -std::unique_ptr GetDemoBrandedWallpaper( - bool super_referral) { - auto demo = std::make_unique(); - demo->url_prefix = "chrome://newtab/ntp-dummy-brandedwallpaper/"; - Logo demo_logo; - demo_logo.alt_text = kAltText; - demo_logo.company_name = kCompanyName; - demo_logo.destination_url = kDestinationUrl; - demo_logo.image_file = base::FilePath::FromUTF8Unsafe(kLogoImageFile); - - Campaign demo_campaign; - demo_campaign.campaign_id = kCampaignId; - demo_campaign.creatives = { - {base::FilePath(FILE_PATH_LITERAL("wallpaper1.jpg")), - {3988, 2049}, - demo_logo, - kFirstCreativeInstanceId}, - {base::FilePath::FromUTF8Unsafe(kSponsoredImageFile), - {kSponsoredImageFocalPointX, kSponsoredImageFocalPointY}, - demo_logo, - kCreativeInstanceId}, - {base::FilePath(FILE_PATH_LITERAL("wallpaper3.jpg")), - {0, 0}, - demo_logo, - "1744602b-253b-47b2-909b-f9b248a6b681"}, - }; - demo->campaigns.push_back(demo_campaign); - - if (super_referral) { - demo->theme_name = "Technikke"; - demo->top_sites = { - { "Brave", "https://brave.com", "brave.png", - base::FilePath(FILE_PATH_LITERAL("brave.png")) }, - { "BAT", "https://basicattentiontoken.org/", "bat.png", - base::FilePath(FILE_PATH_LITERAL("bat.png")) }, - }; - } +#if BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) +class BraveNTPCustomBackgroundServiceDelegateMock + : public BraveNTPCustomBackgroundService::Delegate { + public: + BraveNTPCustomBackgroundServiceDelegateMock() = default; - return demo; -} + ~BraveNTPCustomBackgroundServiceDelegateMock() override = default; -std::unique_ptr GetDemoBackgroundWallpaper() { - auto demo = std::make_unique(); - demo->backgrounds = { - {base::FilePath(FILE_PATH_LITERAL("wallpaper1.jpg")), "Brave", - "https://brave.com/"}, - }; + void EnableCustomImageBackground() { + is_custom_image_background_enabled_ = true; + } - return demo; -} + void DisableCustomImageBackground() { + is_custom_image_background_enabled_ = false; + } -#if BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) -class TestDelegate : public BraveNTPCustomBackgroundService::Delegate { - public: - TestDelegate() = default; + void EnableColorBackground() { is_color_background_enabled_ = true; } - ~TestDelegate() override = default; + void DisableColorBackground() { is_color_background_enabled_ = false; } - // Delegate overrides: - bool IsCustomImageBackgroundEnabled() const override { return image_enabled; } + // Delegate: + bool IsCustomImageBackgroundEnabled() const override { + return is_custom_image_background_enabled_; + } base::FilePath GetCustomBackgroundImageLocalFilePath( const GURL& /*url*/) const override { @@ -131,445 +154,667 @@ class TestDelegate : public BraveNTPCustomBackgroundService::Delegate { return GURL(std::string(kCustomWallpaperURL) + "foo.jpg"); } - bool IsColorBackgroundEnabled() const override { return color_enabled; } + bool IsColorBackgroundEnabled() const override { + return is_color_background_enabled_; + } + std::string GetColor() const override { return "#ff0000"; } + bool ShouldUseRandomValue() const override { return false; } + bool HasPreferredBraveBackground() const override { return false; } + base::Value::Dict GetPreferredBraveBackground() const override { return {}; } - bool image_enabled = false; - bool color_enabled = false; + private: + bool is_custom_image_background_enabled_ = false; + bool is_color_background_enabled_ = false; }; -#endif +#endif // BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) -class NTPBackgroundImagesViewCounterTest : public testing::Test { +class ViewCounterServiceTest : public testing::Test { public: - NTPBackgroundImagesViewCounterTest() = default; + ViewCounterServiceTest() = default; - ~NTPBackgroundImagesViewCounterTest() override = default; + ~ViewCounterServiceTest() override = default; void SetUp() override { - // Need ntp_sponsored_images prefs - auto* const pref_registry = prefs()->registry(); - ViewCounterService::RegisterProfilePrefs(pref_registry); - brave_rewards::RegisterProfilePrefs(pref_registry); - auto* const local_registry = pref_service_.registry(); - brave::RegisterPrefsForBraveReferralsService(local_registry); - NTPBackgroundImagesService::RegisterLocalStatePrefs(local_registry); - ViewCounterService::RegisterLocalStatePrefs(local_registry); - - service_ = std::make_unique( - /*component_updater_service=*/nullptr, &pref_service_); + brave_rewards::RegisterProfilePrefs(prefs_.registry()); + ViewCounterService::RegisterProfilePrefs(prefs_.registry()); + HostContentSettingsMap::RegisterProfilePrefs(prefs_.registry()); + + brave::RegisterPrefsForBraveReferralsService(local_state_.registry()); + NTPBackgroundImagesService::RegisterLocalStatePrefs( + local_state_.registry()); + ViewCounterService::RegisterLocalStatePrefs(local_state_.registry()); + + host_content_settings_map_ = new HostContentSettingsMap( + &prefs_, /* is_off_the_record=*/false, /*store_last_modified=*/false, + /*restore_session=*/false, /*should_record_metrics=*/false); + + background_images_service_ = std::make_unique( + /*component_updater_service=*/nullptr, &local_state_); + #if BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) - auto delegate = std::make_unique(); - delegate_ = delegate.get(); + auto custom_background_service_delegate = + std::make_unique(); + custom_background_service_delegate_mock_ = + custom_background_service_delegate.get(); custom_background_service_ = - std::make_unique(std::move(delegate)); - view_counter_ = std::make_unique( - service_.get(), custom_background_service_.get(), &ads_service_mock_, - prefs(), &pref_service_, - // don't need to test p3a, so passing nullptr - std::unique_ptr(), - /* is_supported_locale */ true); -#else - view_counter_ = std::make_unique( - service_.get(), nullptr, &ads_service_mock_, prefs(), &pref_service_, - std::unique_ptr(), true); -#endif + std::make_unique( + std::move(custom_background_service_delegate)); +#endif // BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) + + view_counter_service_ = std::make_unique( + host_content_settings_map_.get(), background_images_service_.get(), + custom_background_service_.get(), &ads_service_mock_, &prefs_, + &local_state_, std::unique_ptr(), + /*is_supported_locale=*/true); // Set referral service is properly initialized sr component is set. - pref_service_.SetBoolean(kReferralCheckedForPromoCodeFile, true); - pref_service_.SetDict(prefs::kNewTabPageCachedSuperReferralComponentInfo, - base::Value::Dict()); + local_state_.SetBoolean(kReferralCheckedForPromoCodeFile, true); + local_state_.SetDict(prefs::kNewTabPageCachedSuperReferralComponentInfo, + base::Value::Dict()); + } + + void TearDown() override { host_content_settings_map_->ShutdownOnUIThread(); } + + void SetSponsoredImagesVisibility(bool should_show) { + prefs_.SetBoolean(prefs::kNewTabPageShowSponsoredImagesBackgroundImage, + should_show); + } + + void MockSponsoredImagesData(WallpaperType wallpaper_type, + bool super_referral) { + auto images_data = std::make_unique(); + + images_data->url_prefix = "chrome://branded-wallpaper/"; + + Logo logo; + logo.company_name = kCompanyName; + logo.alt_text = kAltText; + logo.image_file = base::FilePath(FILE_PATH_LITERAL("logo_image.png")); + logo.destination_url = kTargetUrl; + + Campaign campaign; + campaign.campaign_id = kCampaignId; + campaign.creatives = {{wallpaper_type, + base::FilePath(FILE_PATH_LITERAL("wallpaper1.jpg")), + {3988, 2049}, + logo, + "ab257ca5-2bbc-4288-9c06-ce1d5d796343"}, + {wallpaper_type, + base::FilePath(FILE_PATH_LITERAL("wallpaper2.jpg")), + {5233, 3464}, + logo, + kCreativeInstanceId}, + {wallpaper_type, + base::FilePath(FILE_PATH_LITERAL("wallpaper3.jpg")), + {0, 0}, + logo, + "1744602b-253b-47b2-909b-f9b248a6b681"}}; + images_data->campaigns.push_back(campaign); + + if (super_referral) { + images_data->theme_name = "Technikke"; + images_data->top_sites = { + {"Brave", "https://brave.com", "brave.png", + base::FilePath(FILE_PATH_LITERAL("brave.png"))}, + {"BAT", "https://basicattentiontoken.org/", "bat.png", + base::FilePath(FILE_PATH_LITERAL("bat.png"))}}; + + background_images_service_->super_referrals_images_data_ = + std::move(images_data); + return; + } + + background_images_service_->sponsored_images_data_ = std::move(images_data); } - void EnableSIPref(bool enable) { - prefs()->SetBoolean( - prefs::kNewTabPageShowSponsoredImagesBackgroundImage, enable); + void MockMalformedSponsoredImagesData() { + background_images_service_->OnGetSponsoredComponentJsonData( + /*is_super_referral=*/false, "MALFORMED JSON"); } - void EnableSRPref(bool enable) { - prefs()->SetInteger( - prefs::kNewTabPageSuperReferralThemesOption, - enable ? ViewCounterService::SUPER_REFERRAL - : ViewCounterService::DEFAULT); + void MockBackgroundImagesData() { + auto images_data = std::make_unique(); + images_data->backgrounds = { + {base::FilePath(FILE_PATH_LITERAL("wallpaper1.jpg")), "Brave", + "https://brave.com/"}}; + + background_images_service_->background_images_data_ = + std::move(images_data); + } + + void MockMalformedBackgroundImagesData() { + background_images_service_->OnGetComponentJsonData("MALFORMED JSON"); } - void EnableNTPBGImagesPref(bool enable) { - prefs()->SetBoolean(prefs::kNewTabPageShowBackgroundImage, enable); + void SetSuperReferralVisibility(bool should_show) { + prefs_.SetInteger(prefs::kNewTabPageSuperReferralThemesOption, + should_show ? ViewCounterService::SUPER_REFERRAL + : ViewCounterService::DEFAULT); } - sync_preferences::TestingPrefServiceSyncable* prefs() { return &prefs_; } + void SetBackgroundImagesVisibility(bool should_show) { + prefs_.SetBoolean(prefs::kNewTabPageShowBackgroundImage, should_show); + } + + void MockImagesData() { + SetSponsoredImagesVisibility(true); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/false); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); + + SetBackgroundImagesVisibility(true); + MockBackgroundImagesData(); + EXPECT_TRUE(view_counter_service_->CanShowBackgroundImages()); + } - void InitBackgroundAndSponsoredImageWallpapers() { - service_->sponsored_images_data_ = GetDemoBrandedWallpaper(false); - EnableSIPref(true); - EnableNTPBGImagesPref(true); - service_->background_images_data_ = GetDemoBackgroundWallpaper(); + void InitBackgroundAndSponsoredRichMediaWallpapers() { + SetSponsoredImagesVisibility(true); + MockSponsoredImagesData(WallpaperType::kRichMedia, + /*super_referral=*/false); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); - EXPECT_TRUE(view_counter_->IsBackgroundWallpaperActive()); + SetBackgroundImagesVisibility(true); + MockBackgroundImagesData(); + EXPECT_TRUE(view_counter_service_->CanShowBackgroundImages()); } brave_ads::NewTabPageAdInfo CreateNewTabPageAdInfo() { - brave_ads::NewTabPageAdInfo ad_info; - ad_info.placement_id = kPlacementdId; - ad_info.campaign_id = kCampaignId; - ad_info.creative_instance_id = kCreativeInstanceId; - ad_info.company_name = kCompanyName; - ad_info.alt = kAltText; - ad_info.target_url = GURL(kDestinationUrl); - return ad_info; + brave_ads::NewTabPageAdInfo ad; + ad.placement_id = kPlacementdId; + ad.campaign_id = kCampaignId; + ad.creative_instance_id = kCreativeInstanceId; + ad.company_name = kCompanyName; + ad.alt = kAltText; + ad.target_url = GURL(kTargetUrl); + + return ad; } int GetInitialCountToBrandedWallpaper() const { return features::kInitialCountToBrandedWallpaper.Get() - 1; } - std::optional TryGetFirstSponsoredImageWallpaper() { + std::optional + CycleThroughPageViewsAndMaybeGetNewTabTakeoverWallpaper() { // Loading initial count times. for (int i = 0; i < GetInitialCountToBrandedWallpaper(); ++i) { - auto wallpaper = view_counter_->GetCurrentWallpaperForDisplay(); - EXPECT_TRUE(wallpaper->FindBool(kIsBackgroundKey).value_or(false)); - view_counter_->RegisterPageView(); + const std::optional wallpaper = + view_counter_service_->GetCurrentWallpaperForDisplay(); + EXPECT_TRUE(wallpaper); + EXPECT_TRUE(wallpaper->FindBool(kIsBackgroundKey)); + + view_counter_service_->RegisterPageView(); } - return view_counter_->GetCurrentWallpaperForDisplay(); + return view_counter_service_->GetCurrentWallpaperForDisplay(); } - bool AdInfoMatchesSponsoredImage(const brave_ads::NewTabPageAdInfo& ad_info, + bool AdInfoMatchesSponsoredImage(const brave_ads::NewTabPageAdInfo& ad, size_t campaign_index, size_t creative_index) { - return service_->sponsored_images_data_->AdInfoMatchesSponsoredImage( - ad_info, campaign_index, creative_index); + return background_images_service_->sponsored_images_data_ + ->AdInfoMatchesSponsoredImage(ad, campaign_index, creative_index); } protected: - base::test::SingleThreadTaskEnvironment task_environment_; - TestingPrefServiceSimple pref_service_; + base::test::TaskEnvironment task_environment_; + + TestingPrefServiceSimple local_state_; sync_preferences::TestingPrefServiceSyncable prefs_; - std::unique_ptr service_; + + scoped_refptr host_content_settings_map_; + + std::unique_ptr background_images_service_; #if BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) std::unique_ptr custom_background_service_; - raw_ptr delegate_ = nullptr; -#endif + raw_ptr + custom_background_service_delegate_mock_ = nullptr; +#endif // BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) - std::unique_ptr view_counter_; - brave_ads::AdsServiceMock ads_service_mock_{nullptr}; + brave_ads::AdsServiceMock ads_service_mock_{/*delegate=*/nullptr}; + + std::unique_ptr view_counter_service_; }; -TEST_F(NTPBackgroundImagesViewCounterTest, SINotActiveInitially) { - // By default, data is bad and SI wallpaper is not active. - EXPECT_FALSE(view_counter_->IsBrandedWallpaperActive()); +TEST_F(ViewCounterServiceTest, CanShowSponsoredImages) { + SetSponsoredImagesVisibility(true); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/false); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); } -TEST_F(NTPBackgroundImagesViewCounterTest, BINotActiveInitially) { - // By default, data is bad and BI wallpaper is not active. - EXPECT_FALSE(view_counter_->IsBackgroundWallpaperActive()); +TEST_F(ViewCounterServiceTest, CannotShowSponsoredImagesIfOptedOut) { + SetSponsoredImagesVisibility(false); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/false); + EXPECT_FALSE(view_counter_service_->CanShowSponsoredImages()); + + SetSuperReferralVisibility(false); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/true); + EXPECT_FALSE(view_counter_service_->CanShowSponsoredImages()); } -TEST_F(NTPBackgroundImagesViewCounterTest, SINotActiveWithBadData) { - // Set some bad data explicitly. - service_->sponsored_images_data_ = std::make_unique(); - service_->super_referrals_images_data_ = - std::make_unique(); - EXPECT_FALSE(view_counter_->IsBrandedWallpaperActive()); +TEST_F(ViewCounterServiceTest, CannotShowSponsoredImagesIfUninitialized) { + EXPECT_FALSE(view_counter_service_->CanShowSponsoredImages()); +} + +TEST_F(ViewCounterServiceTest, CannotShowSponsoredImagesIfMalformed) { + SetSponsoredImagesVisibility(true); + MockMalformedSponsoredImagesData(); + EXPECT_FALSE(view_counter_service_->CanShowSponsoredImages()); +} + +TEST_F(ViewCounterServiceTest, CanShowBackgroundImages) { + SetBackgroundImagesVisibility(true); + MockBackgroundImagesData(); + EXPECT_TRUE(view_counter_service_->CanShowBackgroundImages()); } -TEST_F(NTPBackgroundImagesViewCounterTest, BINotActiveWithBadData) { - // Set some bad data explicitly. - service_->background_images_data_ = - std::make_unique(); - EXPECT_FALSE(view_counter_->IsBackgroundWallpaperActive()); +TEST_F(ViewCounterServiceTest, CannotShowBackgroundImages) { + EXPECT_FALSE(view_counter_service_->CanShowBackgroundImages()); } -TEST_F(NTPBackgroundImagesViewCounterTest, NotActiveOptedOut) { - // Even with good data, wallpaper should not be active if user pref is off. - service_->sponsored_images_data_ = GetDemoBrandedWallpaper(false); - EnableSIPref(false); - EXPECT_FALSE(view_counter_->IsBrandedWallpaperActive()); +TEST_F(ViewCounterServiceTest, CannotShowBackgroundImagesIfUninitialized) { + EXPECT_FALSE(view_counter_service_->CanShowBackgroundImages()); +} - service_->super_referrals_images_data_ = GetDemoBrandedWallpaper(true); - EnableSRPref(false); - EXPECT_FALSE(view_counter_->IsBrandedWallpaperActive()); +TEST_F(ViewCounterServiceTest, CannotShowBackgroundImagesIfMalformed) { + SetBackgroundImagesVisibility(true); + MockMalformedBackgroundImagesData(); + EXPECT_FALSE(view_counter_service_->CanShowBackgroundImages()); } -TEST_F(NTPBackgroundImagesViewCounterTest, - ActiveOptedInWithNTPBackgoundOption) { - EnableNTPBGImagesPref(false); - service_->super_referrals_images_data_ = GetDemoBrandedWallpaper(true); +TEST_F(ViewCounterServiceTest, ActiveOptedInWithNTPBackgoundOption) { + SetBackgroundImagesVisibility(false); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/true); // Even with bg images turned off, SR wallpaper should be active. - EnableSRPref(true); + SetSuperReferralVisibility(true); #if BUILDFLAG(IS_LINUX) - EXPECT_FALSE(view_counter_->IsBrandedWallpaperActive()); -#else - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); -#endif + EXPECT_FALSE(view_counter_service_->CanShowSponsoredImages()); +#else // BUILDFLAG(IS_LINUX) + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); +#endif // !BUILDFLAG(IS_LINUX) - EnableSRPref(false); - EXPECT_FALSE(view_counter_->IsBrandedWallpaperActive()); + SetSuperReferralVisibility(false); + EXPECT_FALSE(view_counter_service_->CanShowSponsoredImages()); } -TEST_F(NTPBackgroundImagesViewCounterTest, - BINotActiveWithNTPBackgoundOptionOptedOut) { - EnableNTPBGImagesPref(false); - service_->background_images_data_ = GetDemoBackgroundWallpaper(); +TEST_F(ViewCounterServiceTest, CannotShowBackgroundImagesIfOptedOut) { + SetBackgroundImagesVisibility(false); + MockBackgroundImagesData(); + #if BUILDFLAG(IS_ANDROID) // On android, |kNewTabPageShowBackgroundImage| prefs is not used for // controlling bg option. So view counter can give data. - EXPECT_TRUE(view_counter_->IsBackgroundWallpaperActive()); -#else - EXPECT_FALSE(view_counter_->IsBackgroundWallpaperActive()); -#endif + EXPECT_TRUE(view_counter_service_->CanShowBackgroundImages()); +#else // BUILDFLAG(IS_ANDROID) + EXPECT_FALSE(view_counter_service_->CanShowBackgroundImages()); +#endif // !BUILDFLAG(IS_ANDROID) } -// Branded wallpaper is active if one of them is available. -TEST_F(NTPBackgroundImagesViewCounterTest, IsActiveOptedIn) { - service_->sponsored_images_data_ = GetDemoBrandedWallpaper(false); - EnableSIPref(true); - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); +// New tab takeover wallpaper is active if one of them is available. +TEST_F(ViewCounterServiceTest, IsActiveOptedIn) { + SetSponsoredImagesVisibility(true); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/false); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); - service_->super_referrals_images_data_ = GetDemoBrandedWallpaper(true); - EnableSRPref(true); - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); + SetSuperReferralVisibility(true); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/true); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); - // Active if SI is possible. - EnableSRPref(false); - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); + // Active if super referral is possible. + SetSuperReferralVisibility(false); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); // Active if SR is only opted in. - EnableSIPref(false); - EnableSRPref(true); + SetSponsoredImagesVisibility(false); + SetSuperReferralVisibility(true); #if BUILDFLAG(IS_LINUX) - EXPECT_FALSE(view_counter_->IsBrandedWallpaperActive()); -#else - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); -#endif + EXPECT_FALSE(view_counter_service_->CanShowSponsoredImages()); +#else // BUILDFLAG(IS_LINUX) + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); +#endif // !BUILDFLAG(IS_LINUX) } -TEST_F(NTPBackgroundImagesViewCounterTest, PrefsWithModelTest) { - auto& model = view_counter_->model_; - - EXPECT_EQ(model.show_branded_wallpaper_, +TEST_F(ViewCounterServiceTest, PrefsWithModelTest) { + EXPECT_EQ(view_counter_service_->model_.show_branded_wallpaper_, features::kInitialCountToBrandedWallpaper.Get() - 1); - EXPECT_TRUE(model.show_wallpaper_); - EXPECT_TRUE(model.show_branded_wallpaper_); - EXPECT_FALSE(model.always_show_branded_wallpaper_); + EXPECT_TRUE(view_counter_service_->model_.show_wallpaper_); + EXPECT_TRUE(view_counter_service_->model_.show_branded_wallpaper_); + EXPECT_FALSE(view_counter_service_->model_.always_show_branded_wallpaper_); - EnableSRPref(true); - EXPECT_FALSE(model.always_show_branded_wallpaper_); + SetSuperReferralVisibility(true); + EXPECT_FALSE(view_counter_service_->model_.always_show_branded_wallpaper_); - EnableSIPref(false); - EXPECT_FALSE(model.show_branded_wallpaper_); + SetSponsoredImagesVisibility(false); + EXPECT_FALSE(view_counter_service_->model_.show_branded_wallpaper_); - EnableNTPBGImagesPref(false); - EXPECT_FALSE(model.show_wallpaper_); + SetBackgroundImagesVisibility(false); + EXPECT_FALSE(view_counter_service_->model_.show_wallpaper_); } -TEST_F(NTPBackgroundImagesViewCounterTest, ActiveInitiallyOptedIn) { +TEST_F(ViewCounterServiceTest, ActiveInitiallyOptedIn) { // Sanity check that the default is still to be opted-in. // If this gets manually changed, then this test should be manually changed // too. - service_->sponsored_images_data_ = GetDemoBrandedWallpaper(false); - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/false); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); - service_->super_referrals_images_data_ = GetDemoBrandedWallpaper(true); - EXPECT_TRUE(view_counter_->IsBrandedWallpaperActive()); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/true); + EXPECT_TRUE(view_counter_service_->CanShowSponsoredImages()); } #if !BUILDFLAG(IS_LINUX) // Super referral feature is disabled on linux. -TEST_F(NTPBackgroundImagesViewCounterTest, ModelTest) { - service_->super_referrals_images_data_ = GetDemoBrandedWallpaper(true); - service_->sponsored_images_data_ = GetDemoBrandedWallpaper(false); - view_counter_->OnSponsoredImagesDataDidUpdate( - service_->super_referrals_images_data_.get()); - EXPECT_TRUE(view_counter_->model_.always_show_branded_wallpaper_); +TEST_F(ViewCounterServiceTest, ModelTest) { + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/true); + MockSponsoredImagesData(WallpaperType::kImage, /*super_referral=*/false); + view_counter_service_->OnSponsoredImagesDataDidUpdate( + background_images_service_->super_referrals_images_data_.get()); + EXPECT_TRUE(view_counter_service_->model_.always_show_branded_wallpaper_); // Initial count is not changed because branded wallpaper is always // visible in SR mode. int expected_count = GetInitialCountToBrandedWallpaper(); - view_counter_->RegisterPageView(); - view_counter_->RegisterPageView(); - EXPECT_EQ(expected_count, view_counter_->model_.count_to_branded_wallpaper_); + view_counter_service_->RegisterPageView(); + view_counter_service_->RegisterPageView(); + EXPECT_EQ(expected_count, + view_counter_service_->model_.count_to_branded_wallpaper_); - service_->super_referrals_images_data_ = + background_images_service_->super_referrals_images_data_ = std::make_unique(); - view_counter_->OnSuperReferralCampaignDidEnd(); - EXPECT_FALSE(view_counter_->model_.always_show_branded_wallpaper_); - EXPECT_EQ(expected_count, view_counter_->model_.count_to_branded_wallpaper_); + view_counter_service_->OnSuperReferralCampaignDidEnd(); + EXPECT_FALSE(view_counter_service_->model_.always_show_branded_wallpaper_); + EXPECT_EQ(expected_count, + view_counter_service_->model_.count_to_branded_wallpaper_); - view_counter_->RegisterPageView(); + view_counter_service_->RegisterPageView(); expected_count--; - EXPECT_EQ(expected_count, view_counter_->model_.count_to_branded_wallpaper_); + EXPECT_EQ(expected_count, + view_counter_service_->model_.count_to_branded_wallpaper_); } #endif -TEST_F(NTPBackgroundImagesViewCounterTest, GetCurrentWallpaperTest) { - service_->background_images_data_ = GetDemoBackgroundWallpaper(); - EXPECT_TRUE(view_counter_->IsBackgroundWallpaperActive()); - auto wallpaper = view_counter_->GetCurrentWallpaper(); - EXPECT_EQ("chrome://background-wallpaper/wallpaper1.jpg", - *wallpaper->FindString(kWallpaperURLKey)); +TEST_F(ViewCounterServiceTest, GetCurrentWallpaper) { + MockBackgroundImagesData(); + EXPECT_TRUE(view_counter_service_->CanShowBackgroundImages()); + + EXPECT_EQ(base::test::ParseJsonDict(R"JSON( + { + "author": "Brave", + "isBackground": true, + "link": "https://brave.com/", + "random": true, + "type": "brave", + "wallpaperImagePath": "wallpaper1.jpg", + "wallpaperImageUrl": "chrome://background-wallpaper/wallpaper1.jpg" + })JSON"), + view_counter_service_->GetCurrentWallpaper()); #if BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) - // Enable custom image background. - delegate_->image_enabled = true; - wallpaper = view_counter_->GetCurrentWallpaper(); - EXPECT_TRUE(wallpaper->FindString(kWallpaperURLKey) - ->starts_with(kCustomWallpaperURL)); - - // Disable custom image background. - delegate_->image_enabled = false; - wallpaper = view_counter_->GetCurrentWallpaper(); - EXPECT_EQ("chrome://background-wallpaper/wallpaper1.jpg", - *wallpaper->FindString(kWallpaperURLKey)); - - // Enable color background - delegate_->color_enabled = true; - wallpaper = view_counter_->GetCurrentWallpaper(); - EXPECT_FALSE(wallpaper->FindString(kWallpaperURLKey)); - EXPECT_EQ(delegate_->GetColor(), *wallpaper->FindString(kWallpaperColorKey)); -#endif + custom_background_service_delegate_mock_->EnableCustomImageBackground(); + EXPECT_EQ(base::test::ParseJsonDict(R"JSON( + { + "isBackground": true, + "random": false, + "type": "image", + "wallpaperImageUrl": "chrome://custom-wallpaper/foo.jpg" + })JSON"), + view_counter_service_->GetCurrentWallpaper()); + + custom_background_service_delegate_mock_->DisableCustomImageBackground(); + EXPECT_EQ(base::test::ParseJsonDict(R"JSON( + { + "author": "Brave", + "isBackground": true, + "link": "https://brave.com/", + "random": true, + "type": "brave", + "wallpaperImagePath": "wallpaper1.jpg", + "wallpaperImageUrl": "chrome://background-wallpaper/wallpaper1.jpg" + })JSON"), + view_counter_service_->GetCurrentWallpaper()); + + custom_background_service_delegate_mock_->EnableColorBackground(); + EXPECT_EQ(base::test::ParseJsonDict(R"JSON( + { + "isBackground": true, + "random": false, + "type": "color", + "wallpaperColor": "#ff0000" + })JSON"), + view_counter_service_->GetCurrentWallpaper()); +#endif // BUILDFLAG(ENABLE_CUSTOM_BACKGROUND) } -TEST_F(NTPBackgroundImagesViewCounterTest, - GetSponsoredImageWallpaperAdsServiceDisabled) { - InitBackgroundAndSponsoredImageWallpapers(); +TEST_F(ViewCounterServiceTest, GetNewTabTakeoverWallpaperForNonRewardsUser) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, false); - prefs()->SetBoolean(brave_rewards::prefs::kEnabled, false); + MockImagesData(); - EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAdForDisplay()) - .Times(0); - EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd()).Times(0); + const ::testing::InSequence s; + EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd).Times(0); + EXPECT_CALL(ads_service_mock_, OnFailedToPrefetchNewTabPageAd).Times(0); + EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAd).Times(0); - auto si_wallpaper = TryGetFirstSponsoredImageWallpaper(); - EXPECT_FALSE(si_wallpaper->FindBool(kIsBackgroundKey).value_or(true)); - ASSERT_TRUE(si_wallpaper->FindString(kCreativeInstanceIDKey)); - EXPECT_TRUE(si_wallpaper->FindString(kCreativeInstanceIDKey)); - ASSERT_TRUE(si_wallpaper->FindString(kWallpaperIDKey)); - EXPECT_FALSE(si_wallpaper->FindString(kWallpaperIDKey)->empty()); + EXPECT_TRUE(CycleThroughPageViewsAndMaybeGetNewTabTakeoverWallpaper()); } -TEST_F(NTPBackgroundImagesViewCounterTest, SponsoredImageAdFrequencyCapped) { - InitBackgroundAndSponsoredImageWallpapers(); +TEST_F(ViewCounterServiceTest, DoNotGetNewTabTakeoverWallpaperForRewardsUser) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, true); - prefs()->SetBoolean(brave_rewards::prefs::kEnabled, true); + MockImagesData(); - EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAdForDisplay()) - .WillOnce(Return(std::nullopt)); - EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd()) + const ::testing::InSequence s; + EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd) .Times(GetInitialCountToBrandedWallpaper()); - EXPECT_CALL(ads_service_mock_, OnFailedToPrefetchNewTabPageAd(_, _)).Times(0); - - auto si_wallpaper = TryGetFirstSponsoredImageWallpaper(); - EXPECT_TRUE(si_wallpaper); - EXPECT_TRUE(si_wallpaper->FindBool(kIsBackgroundKey).value_or(false)); - EXPECT_FALSE(si_wallpaper->FindString(kCreativeInstanceIDKey)); - EXPECT_FALSE(si_wallpaper->FindString(kWallpaperIDKey)); + EXPECT_CALL(ads_service_mock_, OnFailedToPrefetchNewTabPageAd).Times(0); + EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAd) + .WillOnce(::testing::Return(/*ad*/ std::nullopt)); + + EXPECT_EQ(base::test::ParseJsonDict(R"JSON( + { + "author": "Brave", + "isBackground": true, + "link": "https://brave.com/", + "random": true, + "type": "brave", + "wallpaperImagePath": "wallpaper1.jpg", + "wallpaperImageUrl": "chrome://background-wallpaper/wallpaper1.jpg" + })JSON"), + CycleThroughPageViewsAndMaybeGetNewTabTakeoverWallpaper()); } -TEST_F(NTPBackgroundImagesViewCounterTest, SponsoredImageAdServed) { - InitBackgroundAndSponsoredImageWallpapers(); +TEST_F(ViewCounterServiceTest, GetNewTabTakeoverWallpaperForRewardsUser) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, true); - brave_ads::NewTabPageAdInfo ad_info = CreateNewTabPageAdInfo(); - EXPECT_TRUE(AdInfoMatchesSponsoredImage(ad_info, 0, 1)); + MockImagesData(); - prefs()->SetBoolean(brave_rewards::prefs::kEnabled, true); + brave_ads::NewTabPageAdInfo ad = CreateNewTabPageAdInfo(); + EXPECT_TRUE(AdInfoMatchesSponsoredImage(ad, /*campaign_index=*/0, + /*creative_index=*/1)); - EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAdForDisplay()) - .WillOnce(Return(ad_info)); - EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd()) + const ::testing::InSequence s; + EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd) .Times(GetInitialCountToBrandedWallpaper()); - EXPECT_CALL(ads_service_mock_, OnFailedToPrefetchNewTabPageAd(_, _)).Times(0); - - auto si_wallpaper = TryGetFirstSponsoredImageWallpaper(); - EXPECT_FALSE(si_wallpaper->FindBool(kIsBackgroundKey).value_or(true)); - ASSERT_TRUE(si_wallpaper->FindString(kCreativeInstanceIDKey)); - EXPECT_EQ(kCreativeInstanceId, - *si_wallpaper->FindString(kCreativeInstanceIDKey)); - ASSERT_TRUE(si_wallpaper->FindString(kWallpaperIDKey)); - EXPECT_EQ(ad_info.placement_id, *si_wallpaper->FindString(kWallpaperIDKey)); + EXPECT_CALL(ads_service_mock_, OnFailedToPrefetchNewTabPageAd).Times(0); + EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAd) + .WillOnce(::testing::Return(ad)); + + EXPECT_EQ(base::test::ParseJsonDict(R"JSON( + { + "campaignId": "fb7ee174-5430-4fb9-8e97-29bf14e8d828", + "conditionMatchers": [], + "creativeInstanceId": "c0d61af3-3b85-4af4-a3cc-cf1b3dd40e70", + "isBackground": false, + "isSponsored": true, + "logo": { + "alt": "Technikke: For music lovers.", + "companyName": "Technikke", + "destinationUrl": "https://brave.com", + "image": "", + "imagePath": "logo_image.png" + }, + "themeName": "", + "type": "image", + "wallpaperFocalPointX": 5233, + "wallpaperFocalPointY": 3464, + "wallpaperId": "326eb47b-467b-46ab-ac1b-5f5de780b344", + "wallpaperImagePath": "wallpaper2.jpg", + "wallpaperImageUrl": "" + })JSON"), + CycleThroughPageViewsAndMaybeGetNewTabTakeoverWallpaper()); } -TEST_F(NTPBackgroundImagesViewCounterTest, WrongSponsoredImageAdServed) { - InitBackgroundAndSponsoredImageWallpapers(); +TEST_F( + ViewCounterServiceTest, + AllowNewTabTakeoverWithRichMediaIfJavaScriptContentSettingIsSetToAllowed) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, false); - brave_ads::NewTabPageAdInfo ad_info = CreateNewTabPageAdInfo(); - ad_info.creative_instance_id = "wrong_creative_instance_id"; - EXPECT_FALSE(AdInfoMatchesSponsoredImage(ad_info, 0, 1)); + host_content_settings_map_->SetDefaultContentSetting( + ContentSettingsType::JAVASCRIPT, CONTENT_SETTING_ALLOW); - prefs()->SetBoolean(brave_rewards::prefs::kEnabled, true); + MockBackgroundImagesData(); + ASSERT_TRUE(view_counter_service_->CanShowBackgroundImages()); + background_images_service_->OnGetSponsoredComponentJsonData( + /*is_super_referral=*/false, kSponsoredRichMediaCampaignsJson); + ASSERT_TRUE(view_counter_service_->CanShowSponsoredImages()); - EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAdForDisplay()) - .WillOnce(Return(ad_info)); - EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd()) - .Times(GetInitialCountToBrandedWallpaper()); - EXPECT_CALL(ads_service_mock_, OnFailedToPrefetchNewTabPageAd(_, _)); + EXPECT_TRUE(view_counter_service_->GetCurrentBrandedWallpaper()); +} + +TEST_F( + ViewCounterServiceTest, + BlockNewTabTakeoverWithRichMediaIfJavaScriptContentSettingIsSetToBlocked) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, false); - auto si_wallpaper = TryGetFirstSponsoredImageWallpaper(); - EXPECT_TRUE(si_wallpaper); - EXPECT_TRUE(si_wallpaper->FindBool(kIsBackgroundKey).value_or(false)); - EXPECT_FALSE(si_wallpaper->FindString(kCreativeInstanceIDKey)); - EXPECT_FALSE(si_wallpaper->FindString(kWallpaperIDKey)); + host_content_settings_map_->SetDefaultContentSetting( + ContentSettingsType::JAVASCRIPT, CONTENT_SETTING_BLOCK); + + MockBackgroundImagesData(); + ASSERT_TRUE(view_counter_service_->CanShowBackgroundImages()); + + background_images_service_->OnGetSponsoredComponentJsonData( + /*is_super_referral=*/false, kSponsoredRichMediaCampaignsJson); + ASSERT_FALSE(view_counter_service_->CanShowSponsoredImages()); + + EXPECT_FALSE(view_counter_service_->GetCurrentBrandedWallpaper()); } -TEST_F(NTPBackgroundImagesViewCounterTest, - GetCurrentBrandedWallpaperIfNotDisplayed) { - InitBackgroundAndSponsoredImageWallpapers(); +TEST_F(ViewCounterServiceTest, + AllowNewTabTakeOverWithImageIfJavaScriptContentSettingIsSetToAllowed) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, false); - prefs()->SetBoolean(brave_rewards::prefs::kEnabled, false); + host_content_settings_map_->SetDefaultContentSetting( + ContentSettingsType::JAVASCRIPT, CONTENT_SETTING_ALLOW); - auto background_wallpaper = view_counter_->GetCurrentWallpaperForDisplay(); - EXPECT_TRUE(background_wallpaper->FindBool(kIsBackgroundKey).value_or(false)); + MockBackgroundImagesData(); + ASSERT_TRUE(view_counter_service_->CanShowBackgroundImages()); - base::MockCallback&, const std::optional&, - const std::optional&, const std::optional&)>> - callback; - EXPECT_CALL(callback, - Run(/*url=*/std::optional(), - /*placement_id=*/std::optional(), - /*creative_instance_id=*/std::optional(), - /*target_url=*/std::optional())); + background_images_service_->OnGetSponsoredComponentJsonData( + /*is_super_referral=*/false, kSponsoredImageCampaignsJson); + ASSERT_TRUE(view_counter_service_->CanShowSponsoredImages()); + + EXPECT_TRUE(view_counter_service_->GetCurrentBrandedWallpaper()); +} + +TEST_F(ViewCounterServiceTest, + AllowNewTabTakeoverWithImageIfJavaScriptContentSettingIsSetToBlocked) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, false); + + host_content_settings_map_->SetDefaultContentSetting( + ContentSettingsType::JAVASCRIPT, CONTENT_SETTING_BLOCK); - view_counter_->GetCurrentBrandedWallpaper(callback.Get()); + MockBackgroundImagesData(); + ASSERT_TRUE(view_counter_service_->CanShowBackgroundImages()); + + background_images_service_->OnGetSponsoredComponentJsonData( + /*is_super_referral=*/false, kSponsoredImageCampaignsJson); + ASSERT_TRUE(view_counter_service_->CanShowSponsoredImages()); + + EXPECT_TRUE(view_counter_service_->GetCurrentBrandedWallpaper()); } -TEST_F(NTPBackgroundImagesViewCounterTest, GetCurrentBrandedWallpaper) { - InitBackgroundAndSponsoredImageWallpapers(); +TEST_F(ViewCounterServiceTest, WrongSponsoredImageAdServedForRewardsUser) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, true); + + MockImagesData(); - prefs()->SetBoolean(brave_rewards::prefs::kEnabled, false); + brave_ads::NewTabPageAdInfo ad = CreateNewTabPageAdInfo(); + ad.creative_instance_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + EXPECT_FALSE(AdInfoMatchesSponsoredImage(ad, /*campaign_index=*/0, + /*creative_index=*/1)); + + EXPECT_CALL(ads_service_mock_, PrefetchNewTabPageAd) + .Times(GetInitialCountToBrandedWallpaper()); + EXPECT_CALL(ads_service_mock_, OnFailedToPrefetchNewTabPageAd); + EXPECT_CALL(ads_service_mock_, MaybeGetPrefetchedNewTabPageAd) + .WillOnce(::testing::Return(ad)); + + EXPECT_EQ(base::test::ParseJsonDict(R"JSON( + { + "author": "Brave", + "isBackground": true, + "link": "https://brave.com/", + "random": true, + "type": "brave", + "wallpaperImagePath": "wallpaper1.jpg", + "wallpaperImageUrl": "chrome://background-wallpaper/wallpaper1.jpg" + })JSON"), + CycleThroughPageViewsAndMaybeGetNewTabTakeoverWallpaper()); +} - auto sponsored_wallpaper = TryGetFirstSponsoredImageWallpaper(); +TEST_F(ViewCounterServiceTest, GetNewTabTakeoverWallpaper) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, false); - const std::string* url = sponsored_wallpaper->FindString(kWallpaperURLKey); + MockImagesData(); + + const std::optional wallpaper = + CycleThroughPageViewsAndMaybeGetNewTabTakeoverWallpaper(); + ASSERT_TRUE(wallpaper); + + const std::string* url = wallpaper->FindString(kWallpaperURLKey); ASSERT_TRUE(url); - const std::string* placement_id = - sponsored_wallpaper->FindString(kWallpaperIDKey); + const std::string* placement_id = wallpaper->FindString(kWallpaperIDKey); ASSERT_TRUE(placement_id); const std::string* creative_instance_id = - sponsored_wallpaper->FindString(kCreativeInstanceIDKey); + wallpaper->FindString(kCreativeInstanceIDKey); ASSERT_TRUE(creative_instance_id); const std::string* target_url = - sponsored_wallpaper->FindStringByDottedPath(kLogoDestinationURLPath); + wallpaper->FindStringByDottedPath(kLogoDestinationURLPath); ASSERT_TRUE(target_url); base::MockCallback&, const std::optional&, const std::optional&, const std::optional&)>> callback; - EXPECT_CALL(callback, Run(std::optional(*url), - std::optional(*placement_id), - std::optional(*creative_instance_id), - std::optional(*target_url))); + EXPECT_CALL(callback, Run(::testing::Optional(GURL(*url)), + ::testing::Optional(*placement_id), + ::testing::Optional(*creative_instance_id), + ::testing::Optional(GURL(*target_url)))); + + view_counter_service_->GetCurrentBrandedWallpaper(callback.Get()); +} + +TEST_F(ViewCounterServiceTest, DoNotGetNewTabTakeoverWallpaper) { + prefs_.SetBoolean(brave_rewards::prefs::kEnabled, false); + + MockImagesData(); - view_counter_->GetCurrentBrandedWallpaper(callback.Get()); + base::MockCallback&, const std::optional&, + const std::optional&, const std::optional&)>> + callback; + EXPECT_CALL(callback, + Run(::testing::Eq(std::nullopt), ::testing::Eq(std::nullopt), + ::testing::Eq(std::nullopt), ::testing::Eq(std::nullopt))); + view_counter_service_->GetCurrentBrandedWallpaper(callback.Get()); } } // namespace ntp_background_images diff --git a/components/services/bat_ads/bat_ads_impl.cc b/components/services/bat_ads/bat_ads_impl.cc index 172f56ea491a..bd2b7d62726e 100644 --- a/components/services/bat_ads/bat_ads_impl.cc +++ b/components/services/bat_ads/bat_ads_impl.cc @@ -90,6 +90,11 @@ void BatAdsImpl::SetFlags(brave_ads::mojom::FlagsPtr mojom_flags) { GetAds()->SetFlags(std::move(mojom_flags)); } +void BatAdsImpl::SetContentSettings( + brave_ads::mojom::ContentSettingsPtr mojom_content_settings) { + GetAds()->SetContentSettings(std::move(mojom_content_settings)); +} + void BatAdsImpl::Initialize(brave_ads::mojom::WalletInfoPtr mojom_wallet, InitializeCallback callback) { GetAds()->Initialize(std::move(mojom_wallet), std::move(callback)); diff --git a/components/services/bat_ads/bat_ads_impl.h b/components/services/bat_ads/bat_ads_impl.h index 9dd1f0a96384..3bad629bfbc7 100644 --- a/components/services/bat_ads/bat_ads_impl.h +++ b/components/services/bat_ads/bat_ads_impl.h @@ -47,6 +47,8 @@ class BatAdsImpl : public mojom::BatAds { void SetBuildChannel( brave_ads::mojom::BuildChannelInfoPtr mojom_build_channel) override; void SetFlags(brave_ads::mojom::FlagsPtr mojom_flags) override; + void SetContentSettings( + brave_ads::mojom::ContentSettingsPtr mojom_content_settings) override; void Initialize(brave_ads::mojom::WalletInfoPtr mojom_wallet, InitializeCallback callback) override; diff --git a/components/services/bat_ads/public/interfaces/bat_ads.mojom b/components/services/bat_ads/public/interfaces/bat_ads.mojom index 6b2397b55404..6127a5c00ef2 100644 --- a/components/services/bat_ads/public/interfaces/bat_ads.mojom +++ b/components/services/bat_ads/public/interfaces/bat_ads.mojom @@ -148,6 +148,7 @@ interface BatAds { SetSysInfo(brave_ads.mojom.SysInfo mojom_sys_info); SetBuildChannel(brave_ads.mojom.BuildChannelInfo mojom_build_channel); SetFlags(brave_ads.mojom.Flags mojom_flags); + SetContentSettings(brave_ads.mojom.ContentSettings mojom_content_settings); Initialize(brave_ads.mojom.WalletInfo? mojom_wallet) => (bool success); Shutdown() => (bool success); diff --git a/ios/browser/api/ntp_background_images/ntp_background_images_service_ios.mm b/ios/browser/api/ntp_background_images/ntp_background_images_service_ios.mm index 15172d329144..e02b9a79556f 100644 --- a/ios/browser/api/ntp_background_images/ntp_background_images_service_ios.mm +++ b/ios/browser/api/ntp_background_images/ntp_background_images_service_ios.mm @@ -88,7 +88,8 @@ - (void)dealloc { } - (NTPSponsoredImageData*)sponsoredImageData { - auto* data = _service->GetBrandedImagesData(/* super_referral */ false); + auto* data = _service->GetSponsoredImagesData(/*super_referral=*/false, + /*supports_rich_media=*/false); if (data == nullptr) { return nil; } @@ -96,7 +97,8 @@ - (NTPSponsoredImageData*)sponsoredImageData { } - (NTPSponsoredImageData*)superReferralImageData { - auto* data = _service->GetBrandedImagesData(/* super_referral */ true); + auto* data = _service->GetSponsoredImagesData(/* super_referral=*/true, + /*supports_rich_media=*/false); if (data == nullptr) { return nil; } diff --git a/ios/browser/brave_ads/ads_service_impl_ios.h b/ios/browser/brave_ads/ads_service_impl_ios.h index 0cdf6d2a6952..495a27f166a5 100644 --- a/ios/browser/brave_ads/ads_service_impl_ios.h +++ b/ios/browser/brave_ads/ads_service_impl_ios.h @@ -83,14 +83,13 @@ class AdsServiceImplIOS : public AdsService { mojom::InlineContentAdEventType mojom_ad_event_type, TriggerAdEventCallback callback) override; - std::optional MaybeGetPrefetchedNewTabPageAdForDisplay() - override; + std::optional MaybeGetPrefetchedNewTabPageAd() override; void PrefetchNewTabPageAd() override; void OnFailedToPrefetchNewTabPageAd( const std::string& placement_id, const std::string& creative_instance_id) override; void ParseAndSaveCreativeNewTabPageAds( - const base::Value::Dict& data, + const base::Value::Dict& dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) override; void TriggerNewTabPageAdEvent( const std::string& placement_id, diff --git a/ios/browser/brave_ads/ads_service_impl_ios.mm b/ios/browser/brave_ads/ads_service_impl_ios.mm index 66c837001343..dbba4bee3a3e 100644 --- a/ios/browser/brave_ads/ads_service_impl_ios.mm +++ b/ios/browser/brave_ads/ads_service_impl_ios.mm @@ -202,7 +202,7 @@ } std::optional -AdsServiceImplIOS::MaybeGetPrefetchedNewTabPageAdForDisplay() { +AdsServiceImplIOS::MaybeGetPrefetchedNewTabPageAd() { // TODO(https://github.com/brave/brave-browser/issues/39703): Unify iOS new // tab takeover ad serving NOTIMPLEMENTED() << "Not used on iOS."; @@ -218,13 +218,13 @@ } void AdsServiceImplIOS::ParseAndSaveCreativeNewTabPageAds( - const base::Value::Dict& data, + const base::Value::Dict& dict, ParseAndSaveCreativeNewTabPageAdsCallback callback) { if (!IsInitialized()) { return std::move(callback).Run(/*success*/ false); } - ads_->ParseAndSaveCreativeNewTabPageAds(data.Clone(), std::move(callback)); + ads_->ParseAndSaveCreativeNewTabPageAds(dict.Clone(), std::move(callback)); } void AdsServiceImplIOS::TriggerNewTabPageAdEvent(