From 8c275a40f02ee137a990466872cb476e96a7bf34 Mon Sep 17 00:00:00 2001 From: NejcZdovc Date: Mon, 22 Jun 2020 09:58:08 +0200 Subject: [PATCH] Do not start process if rewards is off Resolves https://github.com/brave/brave-browser/issues/9526 --- browser/greaselion/greaselion_browsertest.cc | 54 ++- browser/ui/webui/brave_rewards_page_ui.cc | 10 +- .../browser/ads_service_browsertest.cc | 27 -- .../rewards_notification_service_impl.cc | 2 +- .../browser/rewards_service_impl.cc | 389 ++++++++++++++---- .../browser/rewards_service_impl.h | 21 +- .../common/rewards_browsertest_observer.cc | 44 -- .../common/rewards_browsertest_observer.h | 40 -- .../browser/test/rewards_browsertest.cc | 9 - .../test/rewards_contribution_browsertest.cc | 9 - .../test/rewards_database_browsertest.cc | 73 +++- .../browser/test/rewards_flag_browsertest.cc | 121 +++--- .../test/rewards_notification_browsertest.cc | 9 - .../test/rewards_promotion_browsertest.cc | 10 - .../test/rewards_publisher_browsertest.cc | 9 - .../browser/test/rewards_state_browsertest.cc | 46 ++- .../android_page/actions/rewards_actions.ts | 8 + .../android_page/brave_rewards_page.tsx | 7 +- .../android_page/components/settingsPage.tsx | 93 +++-- .../android_page/constants/rewards_types.ts | 4 +- .../android_page/reducers/rewards_reducer.ts | 35 +- .../android_page/reducers/wallet_reducer.ts | 3 + .../resources/android_page/storage.ts | 3 +- .../actions/rewards_panel_actions.ts | 2 + .../background/events/rewardsEvents.ts | 4 + .../reducers/rewards_panel_reducer.ts | 23 +- .../brave_rewards/components/app.tsx | 18 +- .../brave_rewards/components/panel.tsx | 3 +- .../constants/rewards_panel_types.ts | 3 +- .../extension/brave_rewards/utils.ts | 4 +- .../resources/internals/components/app.tsx | 16 +- .../resources/page/actions/rewards_actions.ts | 13 +- .../resources/page/brave_rewards_page.tsx | 7 +- .../page/components/settingsPage.tsx | 95 +++-- .../resources/page/constants/rewards_types.ts | 4 +- .../page/reducers/rewards_reducer.ts | 48 ++- .../resources/page/reducers/wallet_reducer.ts | 3 + .../brave_rewards/resources/page/storage.ts | 3 +- components/definitions/rewards.d.ts | 1 + components/services/bat_ledger/BUILD.gn | 11 +- .../services/bat_ledger/bat_ledger_app.cc | 41 +- .../services/bat_ledger/bat_ledger_app.h | 24 +- ...xy.cc => bat_ledger_client_mojo_bridge.cc} | 130 +++--- ...roxy.h => bat_ledger_client_mojo_bridge.h} | 38 +- .../services/bat_ledger/bat_ledger_impl.cc | 36 +- .../services/bat_ledger/bat_ledger_impl.h | 21 +- .../bat_ledger/bat_ledger_service_impl.cc | 17 +- .../bat_ledger/bat_ledger_service_impl.h | 16 +- .../services/bat_ledger/public/cpp/BUILD.gn | 4 +- ..._proxy.cc => ledger_client_mojo_bridge.cc} | 158 +++---- ...jo_proxy.h => ledger_client_mojo_bridge.h} | 26 +- .../public/interfaces/bat_ledger.mojom | 9 +- .../page/actions/rewards_actions_test.ts | 1 + .../page/reducers/wallet_reducer_test.ts | 4 +- test/BUILD.gn | 2 - .../internal/confirmations_client_mock.h | 2 + .../include/bat/ledger/ledger.h | 2 + .../include/bat/ledger/ledger_client.h | 2 + .../bat/ledger/internal/database/database.cc | 5 + .../bat/ledger/internal/database/database.h | 2 + .../database/database_contribution_info.cc | 25 ++ .../database/database_contribution_info.h | 2 + .../bat/ledger/internal/ledger_client_mock.h | 2 + .../src/bat/ledger/internal/ledger_impl.cc | 29 +- .../src/bat/ledger/internal/ledger_impl.h | 7 + .../src/bat/ledger/internal/wallet/wallet.cc | 30 ++ .../src/bat/ledger/internal/wallet/wallet.h | 6 + .../bat/ledger/internal/wallet/wallet_util.cc | 10 +- .../Ledger/Generated/NativeLedgerClient.h | 1 + .../Ledger/Generated/NativeLedgerClient.mm | 3 + .../Generated/NativeLedgerClientBridge.h | 1 + 71 files changed, 1285 insertions(+), 655 deletions(-) delete mode 100644 components/brave_rewards/browser/test/common/rewards_browsertest_observer.cc delete mode 100644 components/brave_rewards/browser/test/common/rewards_browsertest_observer.h rename components/services/bat_ledger/{bat_ledger_client_mojo_proxy.cc => bat_ledger_client_mojo_bridge.cc} (73%) rename components/services/bat_ledger/{bat_ledger_client_mojo_proxy.h => bat_ledger_client_mojo_bridge.h} (88%) rename components/services/bat_ledger/public/cpp/{ledger_client_mojo_proxy.cc => ledger_client_mojo_bridge.cc} (72%) rename components/services/bat_ledger/public/cpp/{ledger_client_mojo_proxy.h => ledger_client_mojo_bridge.h} (92%) diff --git a/browser/greaselion/greaselion_browsertest.cc b/browser/greaselion/greaselion_browsertest.cc index b9be96665cd4..1fa0b59e13e1 100644 --- a/browser/greaselion/greaselion_browsertest.cc +++ b/browser/greaselion/greaselion_browsertest.cc @@ -14,6 +14,9 @@ #include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/browser/brave_rewards/rewards_service_factory.h" #include "brave/components/greaselion/browser/greaselion_download_service.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" #include "brave/components/greaselion/browser/greaselion_service.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/test/base/ui_test_utils.h" @@ -87,7 +90,13 @@ class GreaselionServiceWaiter : public GreaselionService::Observer { class GreaselionServiceTest : public BaseLocalDataFilesBrowserTest { public: - GreaselionServiceTest() {} + GreaselionServiceTest(): https_server_(net::EmbeddedTestServer::TYPE_HTTPS) { + brave::RegisterPathProvider(); + response_ = + std::make_unique(); + base::ScopedAllowBlockingForTesting allow_blocking; + response_->LoadMocks(); + } // BaseLocalDataFilesBrowserTest overrides const char* test_data_directory() override { return kTestDataDirectory; } @@ -120,16 +129,49 @@ class GreaselionServiceTest : public BaseLocalDataFilesBrowserTest { g_brave_browser_process->greaselion_download_service()->rules()->clear(); } - void SetRewardsEnabled(bool enabled) { - RewardsService* rewards_service = - RewardsServiceFactory::GetForProfile(profile()); - rewards_service->SetRewardsMainEnabled(enabled); + void StartRewards() { + // HTTP resolver + https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); + https_server_.RegisterRequestHandler( + base::BindRepeating(&rewards_browsertest_util::HandleRequest)); + ASSERT_TRUE(https_server_.Start()); + + // Rewards service + brave::RegisterPathProvider(); + rewards_service_ = static_cast( + brave_rewards::RewardsServiceFactory::GetForProfile(profile())); + + // Response mock + rewards_service_->ForTestingSetTestResponseCallback( + base::BindRepeating( + &GreaselionServiceTest::GetTestResponse, + base::Unretained(this))); + rewards_service_->SetLedgerEnvForTesting(); + + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); GreaselionService* greaselion_service = GreaselionServiceFactory::GetForBrowserContext(profile()); // wait for the Greaselion service to install all the extensions it creates // after the rewards service is turned off or on GreaselionServiceWaiter(greaselion_service).Wait(); } + + void GetTestResponse( + const std::string& url, + int32_t method, + int* response_status_code, + std::string* response, + std::map* headers) { + response_->Get( + url, + method, + response_status_code, + response); + } + + std::unique_ptr response_; + net::test_server::EmbeddedTestServer https_server_; + brave_rewards::RewardsServiceImpl* rewards_service_; }; // Ensure the site specific script service properly clears its cache of @@ -236,7 +278,7 @@ IN_PROC_BROWSER_TEST_F(GreaselionServiceTest, ScriptInjectionWithPrecondition) { // rules are active EXPECT_EQ(title, "OK"); - SetRewardsEnabled(true); + StartRewards(); ui_test_utils::NavigateToURL(browser(), url); contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(content::WaitForLoadStop(contents)); diff --git a/browser/ui/webui/brave_rewards_page_ui.cc b/browser/ui/webui/brave_rewards_page_ui.cc index 8123dee5a02b..0d53b1839cc3 100644 --- a/browser/ui/webui/brave_rewards_page_ui.cc +++ b/browser/ui/webui/brave_rewards_page_ui.cc @@ -543,10 +543,18 @@ void RewardsDOMHandler::OnWalletInitialized( // ledger::Result::WALLET_CREATED if (result == 12) { web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.walletCreated"); - } else if (result != 3 && result != 0) { + return; + } + + if (result != 3 && result != 0) { // Report back all errors except when ledger_state is missing web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.walletCreateFailed"); + return; } + + web_ui()->CallJavascriptFunctionUnsafe( + "brave_rewards.initialized", + base::Value(result)); } void RewardsDOMHandler::GetAutoContributeProperties( diff --git a/components/brave_ads/browser/ads_service_browsertest.cc b/components/brave_ads/browser/ads_service_browsertest.cc index 602617144a18..a65082e7cb7a 100644 --- a/components/brave_ads/browser/ads_service_browsertest.cc +++ b/components/brave_ads/browser/ads_service_browsertest.cc @@ -20,7 +20,6 @@ #include "brave/common/brave_paths.h" #include "brave/browser/brave_rewards/rewards_service_factory.h" #include "brave/components/brave_rewards/browser/rewards_service_impl.h" -#include "brave/components/brave_rewards/browser/rewards_service_observer.h" #include "brave/components/brave_rewards/browser/rewards_notification_service_impl.h" // NOLINT #include "brave/components/brave_rewards/browser/rewards_notification_service_observer.h" // NOLINT #include "brave/components/brave_rewards/common/pref_names.h" @@ -115,7 +114,6 @@ bool URLMatches(const std::string& url, class BraveAdsBrowserTest : public InProcessBrowserTest, - public brave_rewards::RewardsServiceObserver, public brave_rewards::RewardsNotificationServiceObserver, public base::SupportsWeakPtr { public: @@ -159,10 +157,6 @@ class BraveAdsBrowserTest ads_service_ = static_cast( brave_ads::AdsServiceFactory::GetForProfile(browser_profile)); ASSERT_NE(nullptr, ads_service_); - rewards_service_->AddObserver(this); - if (!rewards_service_->IsWalletInitialized()) { - WaitForWalletInitialization(); - } rewards_service_->SetLedgerEnvForTesting(); } @@ -173,24 +167,6 @@ class BraveAdsBrowserTest InProcessBrowserTest::TearDown(); } - void WaitForWalletInitialization() { - if (wallet_initialized_) - return; - wait_for_wallet_initialization_loop_.reset(new base::RunLoop); - wait_for_wallet_initialization_loop_->Run(); - } - - void OnWalletInitialized( - brave_rewards::RewardsService* rewards_service, - int32_t result) { - const auto converted_result = static_cast(result); - ASSERT_TRUE(converted_result == ledger::Result::WALLET_CREATED || - converted_result == ledger::Result::LEDGER_OK); - wallet_initialized_ = true; - if (wait_for_wallet_initialization_loop_) - wait_for_wallet_initialization_loop_->Quit(); - } - void GetTestDataDir(base::FilePath* test_data_dir) { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathService::Get(brave::DIR_TEST_DATA, test_data_dir)); @@ -543,9 +519,6 @@ class BraveAdsBrowserTest std::unique_ptr brave_ads_have_arrived_notification_run_loop_; bool brave_ads_have_arrived_notification_was_already_shown_ = false; - std::unique_ptr wait_for_wallet_initialization_loop_; - bool wallet_initialized_ = false; - std::string registrarVK_; std::string verification_; std::string parameters_; diff --git a/components/brave_rewards/browser/rewards_notification_service_impl.cc b/components/brave_rewards/browser/rewards_notification_service_impl.cc index 4acd630d13fa..d41dd84adaa8 100644 --- a/components/brave_rewards/browser/rewards_notification_service_impl.cc +++ b/components/brave_rewards/browser/rewards_notification_service_impl.cc @@ -96,8 +96,8 @@ void RewardsNotificationServiceImpl::DeleteAllNotifications() { rewards_notifications_.clear(); #if defined(OS_ANDROID) rewards_notifications_displayed_.clear(); - StoreRewardsNotifications(); #endif + StoreRewardsNotifications(); OnAllNotificationsDeleted(); } diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index c0052bc3cd0c..0ad4901c8436 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -61,7 +61,7 @@ #include "brave/components/brave_rewards/browser/static_values.h" #include "brave/components/brave_rewards/browser/switches.h" #include "brave/components/brave_rewards/common/pref_names.h" -#include "brave/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h" +#include "brave/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service_factory.h" #include "chrome/browser/browser_process_impl.h" #include "chrome/browser/favicon/favicon_service_factory.h" @@ -357,7 +357,7 @@ RewardsServiceImpl::RewardsServiceImpl(Profile* profile) #if BUILDFLAG(ENABLE_GREASELION) greaselion_service_(greaselion_service), #endif - bat_ledger_client_binding_(new bat_ledger::LedgerClientMojoProxy(this)), + bat_ledger_client_receiver_(new bat_ledger::LedgerClientMojoBridge(this)), file_task_runner_(base::CreateSequencedTaskRunner( {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, @@ -386,6 +386,11 @@ RewardsServiceImpl::~RewardsServiceImpl() { } void RewardsServiceImpl::ConnectionClosed() { + if (!profile_->GetPrefs()->GetBoolean(prefs::kBraveRewardsEnabled)) { + BLOG(1, "Rewards not enabled"); + return; + } + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, base::BindOnce(&RewardsServiceImpl::StartLedger, AsWeakPtr()), base::TimeDelta::FromSeconds(1)); @@ -408,28 +413,33 @@ void RewardsServiceImpl::Init( private_observers_.AddObserver(private_observer_.get()); } - StartLedger(); + if (profile_->GetPrefs()->GetBoolean(prefs::kBraveRewardsEnabled)) { + StartLedger(); + } } void RewardsServiceImpl::StartLedger() { - bat_ledger::mojom::BatLedgerClientAssociatedPtrInfo client_ptr_info; - bat_ledger_client_binding_.Bind(mojo::MakeRequest(&client_ptr_info)); + if (Connected()) { + BLOG(1, "Ledger process is already running"); + return; + } - content::ServiceManagerConnection* connection = - content::ServiceManagerConnection::GetForProcess(); + BLOG(1, "Starting ledger process"); + + auto* connection = content::ServiceManagerConnection::GetForProcess(); if (!connection) { + BLOG(1, "Connection not found"); return; } - if (bat_ledger_service_.is_bound()) { - bat_ledger_service_.reset(); - } + if (!bat_ledger_service_.is_bound()) { + connection->GetConnector()->Connect( + bat_ledger::mojom::kServiceName, + bat_ledger_service_.BindNewPipeAndPassReceiver()); - connection->GetConnector()->BindInterface( - bat_ledger::mojom::kServiceName, - bat_ledger_service_.BindNewPipeAndPassReceiver()); - bat_ledger_service_.set_disconnect_handler( + bat_ledger_service_.set_disconnect_handler( base::Bind(&RewardsServiceImpl::ConnectionClosed, AsWeakPtr())); + } ledger::Environment environment = ledger::Environment::STAGING; // Environment @@ -453,8 +463,18 @@ void RewardsServiceImpl::StartLedger() { } } - bat_ledger_service_->Create(std::move(client_ptr_info), - MakeRequest(&bat_ledger_)); + bat_ledger_service_->Create( + bat_ledger_client_receiver_.BindNewEndpointAndPassRemote(), + bat_ledger_.BindNewEndpointAndPassReceiver(), + base::BindOnce(&RewardsServiceImpl::OnCreate, AsWeakPtr())); +} + +void RewardsServiceImpl::OnCreate() { + if (!Connected()) { + return; + } + + PrepareLedgerEnvForTesting(); auto callback = base::BindOnce(&RewardsServiceImpl::OnWalletInitialized, AsWeakPtr()); @@ -525,30 +545,34 @@ void RewardsServiceImpl::RemovePrivateObserver( } void RewardsServiceImpl::CreateWallet(CreateWalletCallback callback) { - if (ready().is_signaled()) { - if (Connected()) { - auto on_create = base::BindOnce( - &RewardsServiceImpl::OnCreateWallet, - AsWeakPtr(), - std::move(callback)); -#if !defined(OS_ANDROID) - bat_ledger_->CreateWallet(std::move(on_create)); -#else - safetynet_check::ClientAttestationCallback attest_callback = - base::BindOnce(&RewardsServiceImpl::CreateWalletAttestationResult, - AsWeakPtr(), - std::move(on_create)); - safetynet_check_runner_.performSafetynetCheck("", - std::move(attest_callback), true); -#endif - } - } else { - ready().Post(FROM_HERE, - base::BindOnce( - &brave_rewards::RewardsService::CreateWallet, + if (!ready().is_signaled()) { + StartLedger(); + ready().Post( + FROM_HERE, + base::BindOnce(&brave_rewards::RewardsService::CreateWallet, AsWeakPtr(), std::move(callback))); + return; + } + + if (!Connected()) { + return; } + + auto on_create = base::BindOnce(&RewardsServiceImpl::OnCreateWallet, + AsWeakPtr(), + std::move(callback)); + +#if !defined(OS_ANDROID) + bat_ledger_->CreateWallet(std::move(on_create)); +#else + safetynet_check::ClientAttestationCallback attest_callback = + base::BindOnce(&RewardsServiceImpl::CreateWalletAttestationResult, + AsWeakPtr(), + std::move(on_create)); + safetynet_check_runner_.performSafetynetCheck("", + std::move(attest_callback), true); +#endif } #if defined(OS_ANDROID) @@ -557,6 +581,10 @@ void RewardsServiceImpl::CreateWalletAttestationResult( const bool token_received, const std::string& result_string, const bool attestation_passed) { + if (!Connected()) { + return; + } + if (!token_received) { BLOG(0, "CreateWalletAttestationResult error: " << result_string); OnWalletInitialized(ledger::Result::LEDGER_ERROR); @@ -578,6 +606,10 @@ void RewardsServiceImpl::GetContentSiteList( bool allow_non_verified, uint32_t min_visits, const GetContentSiteListCallback& callback) { + if (!Connected()) { + return; + } + auto filter = ledger::ActivityInfoFilter::New(); filter->min_duration = min_visit_time; auto pair = ledger::ActivityInfoFilterOrderPair::New("ai.percent", false); @@ -599,6 +631,10 @@ void RewardsServiceImpl::GetContentSiteList( void RewardsServiceImpl::GetExcludedList( const GetContentSiteListCallback& callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetExcludedList(base::BindOnce( &RewardsServiceImpl::OnGetContentSiteList, AsWeakPtr(), @@ -618,8 +654,9 @@ void RewardsServiceImpl::OnGetContentSiteList( } void RewardsServiceImpl::OnLoad(SessionID tab_id, const GURL& url) { - if (!Connected()) + if (!Connected()) { return; + } if (!ProcessPublisher(url)) { return; @@ -644,36 +681,41 @@ void RewardsServiceImpl::OnLoad(SessionID tab_id, const GURL& url) { } void RewardsServiceImpl::OnUnload(SessionID tab_id) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->OnUnload(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnShow(SessionID tab_id) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->OnShow(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnHide(SessionID tab_id) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->OnHide(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnForeground(SessionID tab_id) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->OnForeground(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnBackground(SessionID tab_id) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->OnBackground(tab_id.id(), GetCurrentTimestamp()); } @@ -683,8 +725,9 @@ void RewardsServiceImpl::OnPostData(SessionID tab_id, const GURL& first_party_url, const GURL& referrer, const std::string& post_data) { - if (!Connected()) + if (!Connected()) { return; + } if (!ProcessPublisher(url)) { return; @@ -717,8 +760,9 @@ void RewardsServiceImpl::OnXHRLoad(SessionID tab_id, const GURL& url, const GURL& first_party_url, const GURL& referrer) { - if (!Connected()) + if (!Connected()) { return; + } if (!ProcessPublisher(url)) { return; @@ -817,6 +861,9 @@ void RewardsServiceImpl::OnWalletInitialized(ledger::Result result) { #endif } + EnableGreaseLion(profile_->GetPrefs()->GetBoolean( + prefs::kBraveRewardsEnabled)); + for (auto& observer : observers_) { observer.OnWalletInitialized(this, static_cast(result)); } @@ -861,8 +908,9 @@ void RewardsServiceImpl::OnGetRewardsInternalsInfo( void RewardsServiceImpl::GetAutoContributeProperties( const GetAutoContributePropertiesCallback& callback) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->GetAutoContributeProperties(base::BindOnce( &RewardsServiceImpl::OnGetAutoContributeProperties, @@ -911,8 +959,9 @@ void RewardsServiceImpl::LoadLedgerState( void RewardsServiceImpl::OnLedgerStateLoaded( ledger::OnLoadCallback callback, std::pair state) { - if (!Connected()) + if (!Connected()) { return; + } if (state.second.is_dict()) { // Record stats. @@ -946,8 +995,9 @@ void RewardsServiceImpl::LoadPublisherState( void RewardsServiceImpl::OnPublisherStateLoaded( ledger::OnLoadCallback callback, const std::string& data) { - if (!Connected()) + if (!Connected()) { return; + } callback( data.empty() ? ledger::Result::NO_PUBLISHER_STATE @@ -957,8 +1007,9 @@ void RewardsServiceImpl::OnPublisherStateLoaded( void RewardsServiceImpl::LoadNicewareList( ledger::GetNicewareListCallback callback) { - if (!Connected()) + if (!Connected()) { return; + } std::string data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); @@ -1266,6 +1317,10 @@ void RewardsServiceImpl::OnAttestationAndroid( const bool token_received, const std::string& token, const bool attestation_passed) { + if (!Connected()) { + return; + } + if (!token_received) { std::move(callback).Run( static_cast(ledger::Result::LEDGER_ERROR), @@ -1389,6 +1444,19 @@ void RewardsServiceImpl::GetReconcileStamp( } void RewardsServiceImpl::SetRewardsMainEnabled(bool enabled) { + if (enabled) { + StartLedger(); + + if (!ready().is_signaled()) { + ready().Post( + FROM_HERE, + base::Bind(&brave_rewards::RewardsService::SetRewardsMainEnabled, + base::Unretained(this), + enabled)); + return; + } + } + if (!Connected()) { return; } @@ -1396,21 +1464,58 @@ void RewardsServiceImpl::SetRewardsMainEnabled(bool enabled) { bat_ledger_->SetRewardsMainEnabled(enabled); TriggerOnRewardsMainEnabled(enabled); -#if BUILDFLAG(ENABLE_GREASELION) - if (greaselion_service_) { - greaselion_service_->SetFeatureEnabled(greaselion::REWARDS, enabled); - greaselion_service_->SetFeatureEnabled(greaselion::TWITTER_TIPS, enabled); - } -#endif - if (!enabled) { RecordRewardsDisabledForSomeMetrics(); + StopLedger(); + } +} + +void RewardsServiceImpl::EnableGreaseLion(const bool enabled) { + #if BUILDFLAG(ENABLE_GREASELION) + if (greaselion_service_) { + greaselion_service_->SetFeatureEnabled(greaselion::REWARDS, enabled); + greaselion_service_->SetFeatureEnabled(greaselion::TWITTER_TIPS, enabled); + } + #endif +} + +void RewardsServiceImpl::StopLedger() { + BLOG(1, "Shutting down ledger process"); + bat_ledger_->Shutdown( + base::BindOnce(&RewardsServiceImpl::OnStopLedger, AsWeakPtr())); +} + +void RewardsServiceImpl::OnStopLedger(const ledger::Result result) { + BLOG_IF( + 1, + result != ledger::Result::LEDGER_OK, + "Ledger process was not shut down successfully"); + + for (auto* const url_loader : url_loaders_) { + delete url_loader; } + url_loaders_.clear(); + + BitmapFetcherService* image_service = + BitmapFetcherServiceFactory::GetForBrowserContext(profile_); + if (image_service) { + for (auto mapping : current_media_fetchers_) { + image_service->CancelRequest(mapping.second); + } + } + + bat_ledger_.reset(); + bat_ledger_client_receiver_.reset(); + bat_ledger_service_.reset(); + is_wallet_initialized_ = false; + BLOG(1, "Successfully shutdown ledger"); } void RewardsServiceImpl::GetRewardsMainEnabled( const GetRewardsMainEnabledCallback& callback) const { if (!Connected()) { + std::move(callback).Run( + profile_->GetPrefs()->GetBoolean(prefs::kBraveRewardsEnabled)); return; } @@ -1524,7 +1629,7 @@ void RewardsServiceImpl::ResetState( void RewardsServiceImpl::ResetTheWholeState( const base::Callback& callback) { reset_states_ = true; - notification_service_->DeleteAllNotifications(); + ClearAllNotifications(); std::vector paths; paths.push_back(ledger_state_path_); paths.push_back(publisher_state_path_); @@ -1548,16 +1653,18 @@ void RewardsServiceImpl::OnResetTheWholeState( void RewardsServiceImpl::OnSavedState( ledger::ResultCallback callback, bool success) { - if (!Connected()) + if (!Connected()) { return; + } callback(success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR); } void RewardsServiceImpl::OnLoadedState( ledger::OnLoadCallback callback, const std::string& value) { - if (!Connected()) + if (!Connected()) { return; + } if (value.empty()) { RecordNoWalletCreatedForAllMetrics(); callback(ledger::Result::LEDGER_ERROR, value); @@ -1684,8 +1791,9 @@ void RewardsServiceImpl::KillTimer(uint32_t timer_id) { void RewardsServiceImpl::OnResetState( ledger::ResultCallback callback, bool success) { - if (!Connected()) + if (!Connected()) { return; + } callback(success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR); } @@ -1863,6 +1971,12 @@ void RewardsServiceImpl::GetBalanceReport( const uint32_t month, const uint32_t year, GetBalanceReportCallback callback) { + if (!Connected()) { + brave_rewards::BalanceReport newReport; + std::move(callback).Run(0, newReport); + return; + } + bat_ledger_->GetBalanceReport( static_cast(month), year, @@ -1874,7 +1988,9 @@ void RewardsServiceImpl::GetBalanceReport( void RewardsServiceImpl::IsWalletCreated( const IsWalletCreatedCallback& callback) { if (!Connected()) { - callback.Run(false); + const auto stamp = + profile_->GetPrefs()->GetUint64(prefs::kStateCreationStamp); + callback.Run(stamp != 0u); return; } @@ -1902,8 +2018,9 @@ void RewardsServiceImpl::GetPublisherActivityFromUrl( return; } - if (!Connected()) + if (!Connected()) { return; + } ledger::VisitDataPtr visit_data = ledger::VisitData::New(); visit_data->domain = visit_data->name = baseDomain; @@ -1935,8 +2052,9 @@ void RewardsServiceImpl::OnPanelPublisherInfo( void RewardsServiceImpl::GetAutoContributionAmount( const GetAutoContributionAmountCallback& callback) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->GetAutoContributionAmount(callback); } @@ -1994,8 +2112,9 @@ void RewardsServiceImpl::OnFetchFavIconCompleted( void RewardsServiceImpl::OnSetOnDemandFaviconComplete( const std::string& favicon_url, ledger::FetchIconCallback callback, bool success) { - if (!Connected()) + if (!Connected()) { return; + } callback(success, favicon_url); } @@ -2003,8 +2122,9 @@ void RewardsServiceImpl::OnSetOnDemandFaviconComplete( void RewardsServiceImpl::GetPublisherBanner( const std::string& publisher_id, GetPublisherBannerCallback callback) { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->GetPublisherBanner(publisher_id, base::BindOnce(&RewardsServiceImpl::OnPublisherBanner, @@ -2053,6 +2173,10 @@ void RewardsServiceImpl::SaveRecurringTip( const std::string& publisher_key, const double amount, SaveRecurringTipCallback callback) { + if (!Connected()) { + return; + } + ledger::RecurringTipPtr info = ledger::RecurringTip::New(); info->publisher_key = publisher_key; info->amount = amount; @@ -2087,6 +2211,10 @@ void RewardsServiceImpl::SaveInlineMediaInfo( const std::string& media_type, const std::map& args, SaveMediaInfoCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->SaveMediaInfo( media_type, base::MapToFlatMap(args), @@ -2112,6 +2240,10 @@ void RewardsServiceImpl::OnGetRecurringTips( void RewardsServiceImpl::GetRecurringTips( GetRecurringTipsCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetRecurringTips( base::BindOnce(&RewardsServiceImpl::OnGetRecurringTips, AsWeakPtr(), @@ -2134,6 +2266,10 @@ void RewardsServiceImpl::OnGetOneTimeTips( } void RewardsServiceImpl::GetOneTimeTips(GetOneTimeTipsCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetOneTimeTips( base::BindOnce(&RewardsServiceImpl::OnGetOneTimeTips, AsWeakPtr(), @@ -2183,8 +2319,9 @@ void RewardsServiceImpl::OnSetPublisherExclude( void RewardsServiceImpl::SetPublisherExclude( const std::string& publisher_key, bool exclude) { - if (!Connected()) + if (!Connected()) { return; + } ledger::PublisherExclude status = exclude @@ -2234,8 +2371,9 @@ void RewardsServiceImpl::StopNotificationTimers() { } void RewardsServiceImpl::OnNotificationTimerFired() { - if (!Connected()) + if (!Connected()) { return; + } bat_ledger_->GetCreationStamp( base::BindOnce(&RewardsServiceImpl::MaybeShowBackupNotification, @@ -2247,6 +2385,10 @@ void RewardsServiceImpl::OnNotificationTimerFired() { } void RewardsServiceImpl::MaybeShowNotificationAddFunds() { + if (!Connected()) { + return; + } + bat_ledger_->HasSufficientBalanceToReconcile( base::BindOnce(&RewardsServiceImpl::ShowNotificationAddFunds, AsWeakPtr())); @@ -2254,6 +2396,10 @@ void RewardsServiceImpl::MaybeShowNotificationAddFunds() { void RewardsServiceImpl::MaybeShowNotificationAddFundsForTesting( base::OnceCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->HasSufficientBalanceToReconcile( base::BindOnce( &RewardsServiceImpl::OnMaybeShowNotificationAddFundsForTesting, @@ -2332,6 +2478,10 @@ void RewardsServiceImpl::DiagnosticLog( const int line, const int verbose_level, const std::string& message) { + if (ledger_for_testing_) { + return; + } + if (profile_->IsOffTheRecord()) { return; } @@ -2582,6 +2732,10 @@ void RewardsServiceImpl::SetBackupCompleted() { void RewardsServiceImpl::GetRewardsInternalsInfo( GetRewardsInternalsInfoCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetRewardsInternalsInfo( base::BindOnce(&RewardsServiceImpl::OnGetRewardsInternalsInfo, AsWeakPtr(), std::move(callback))); @@ -2592,7 +2746,7 @@ void RewardsServiceImpl::OnTip( const double amount, const bool recurring, std::unique_ptr site) { - if (!site) { + if (!Connected() || !site) { return; } @@ -2628,6 +2782,10 @@ void RewardsServiceImpl::OnTip( const std::string& publisher_key, const double amount, const bool recurring) { + if (!Connected()) { + return; + } + if (recurring) { SaveRecurringTip(publisher_key, amount, base::DoNothing()); return; @@ -2641,9 +2799,17 @@ bool RewardsServiceImpl::Connected() const { } void RewardsServiceImpl::SetLedgerEnvForTesting() { + ledger_for_testing_ = true; +} + +void RewardsServiceImpl::PrepareLedgerEnvForTesting() { + if (!ledger_for_testing_) { + return; + } + bat_ledger_service_->SetTesting(); - SetPublisherMinVisitTime(1); + profile_->GetPrefs()->SetInteger(prefs::kStateMinVisitTime, 1); SetShortRetries(true); // this is needed because we are using braveledger_request_util::buildURL @@ -2656,6 +2822,10 @@ void RewardsServiceImpl::SetLedgerEnvForTesting() { } void RewardsServiceImpl::StartMonthlyContributionForTest() { + if (!Connected()) { + return; + } + bat_ledger_->StartMonthlyContribution(); } @@ -2705,6 +2875,10 @@ void RewardsServiceImpl::SetShortRetries(bool short_retries) { void RewardsServiceImpl::GetPendingContributionsTotal( const GetPendingContributionsTotalCallback& callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetPendingContributionsTotal(std::move(callback)); } @@ -2754,6 +2928,10 @@ RewardsServiceImpl::GetAllNotifications() { void RewardsServiceImpl::SetInlineTippingPlatformEnabled( const std::string& key, bool enabled) { + if (!Connected()) { + return; + } + const auto platform = ConvertInlineTipStringToPlatform(key); bat_ledger_->SetInlineTippingPlatformEnabled(platform, enabled); } @@ -2761,6 +2939,10 @@ void RewardsServiceImpl::SetInlineTippingPlatformEnabled( void RewardsServiceImpl::GetInlineTippingPlatformEnabled( const std::string& key, GetInlineTippingPlatformEnabledCallback callback) { + if (!Connected()) { + return; + } + const auto platform = ConvertInlineTipStringToPlatform(key); bat_ledger_->GetInlineTippingPlatformEnabled( platform, @@ -2779,6 +2961,10 @@ void RewardsServiceImpl::GetShareURL( const std::string& type, const std::map& args, GetShareURLCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetShareURL( type, base::MapToFlatMap(args), @@ -2827,6 +3013,10 @@ void RewardsServiceImpl::OnGetPendingContributions( void RewardsServiceImpl::GetPendingContributions( GetPendingContributionsCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetPendingContributions( base::BindOnce(&RewardsServiceImpl::OnGetPendingContributions, AsWeakPtr(), @@ -2841,6 +3031,10 @@ void RewardsServiceImpl::OnPendingContributionRemoved( } void RewardsServiceImpl::RemovePendingContribution(const uint64_t id) { + if (!Connected()) { + return; + } + bat_ledger_->RemovePendingContribution( id, base::BindOnce(&RewardsServiceImpl::OnPendingContributionRemoved, @@ -2855,6 +3049,10 @@ void RewardsServiceImpl::OnRemoveAllPendingContributions( } void RewardsServiceImpl::RemoveAllPendingContributions() { + if (!Connected()) { + return; + } + bat_ledger_->RemoveAllPendingContributions( base::BindOnce(&RewardsServiceImpl::OnRemoveAllPendingContributions, AsWeakPtr())); @@ -2924,6 +3122,10 @@ void RewardsServiceImpl::OnFetchBalance(FetchBalanceCallback callback, } void RewardsServiceImpl::FetchBalance(FetchBalanceCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->FetchBalance( base::BindOnce(&RewardsServiceImpl::OnFetchBalance, AsWeakPtr(), @@ -3026,8 +3228,13 @@ void RewardsServiceImpl::OnGetExternalWallet( std::move(callback).Run(static_cast(result), std::move(external)); } -void RewardsServiceImpl::GetExternalWallet(const std::string& wallet_type, - GetExternalWalletCallback callback) { +void RewardsServiceImpl::GetExternalWallet( + const std::string& wallet_type, + GetExternalWalletCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetExternalWallet(wallet_type, base::BindOnce(&RewardsServiceImpl::OnGetExternalWallet, AsWeakPtr(), @@ -3047,6 +3254,10 @@ void RewardsServiceImpl::ExternalWalletAuthorization( const std::string& wallet_type, const std::map& args, ExternalWalletAuthorizationCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->ExternalWalletAuthorization( wallet_type, base::MapToFlatMap(args), @@ -3124,6 +3335,10 @@ void RewardsServiceImpl::OnDisconnectWallet( } void RewardsServiceImpl::DisconnectWallet(const std::string& wallet_type) { + if (!Connected()) { + return; + } + bat_ledger_->DisconnectWallet( wallet_type, base::BindOnce(&RewardsServiceImpl::OnDisconnectWallet, @@ -3291,6 +3506,10 @@ bool RewardsServiceImpl::OnlyAnonWallet() { } void RewardsServiceImpl::RecordBackendP3AStats() { + if (!Connected()) { + return; + } + bat_ledger_->GetRecurringTips( base::BindOnce(&RewardsServiceImpl::OnRecordBackendP3AStatsRecurring, AsWeakPtr())); @@ -3298,6 +3517,10 @@ void RewardsServiceImpl::RecordBackendP3AStats() { void RewardsServiceImpl::OnRecordBackendP3AStatsRecurring( ledger::PublisherInfoList list) { + if (!Connected()) { + return; + } + bat_ledger_->GetAllContributions( base::BindOnce(&RewardsServiceImpl::OnRecordBackendP3AStatsContributions, AsWeakPtr(), @@ -3402,6 +3625,10 @@ void RewardsServiceImpl::UnblindedTokensReady() { void RewardsServiceImpl::GetAnonWalletStatus( GetAnonWalletStatusCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetAnonWalletStatus( base::BindOnce(&RewardsServiceImpl::OnGetAnonWalletStatus, AsWeakPtr(), @@ -3418,6 +3645,10 @@ void RewardsServiceImpl::GetMonthlyReport( const uint32_t month, const uint32_t year, GetMonthlyReportCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetMonthlyReport( static_cast(month), year, @@ -3557,6 +3788,10 @@ void RewardsServiceImpl::ForTestingSetTestResponseCallback( void RewardsServiceImpl::GetAllMonthlyReportIds( GetAllMonthlyReportIdsCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetAllMonthlyReportIds( base::BindOnce(&RewardsServiceImpl::OnGetAllMonthlyReportIds, AsWeakPtr(), @@ -3571,6 +3806,10 @@ void RewardsServiceImpl::OnGetAllMonthlyReportIds( void RewardsServiceImpl::GetAllContributions( GetAllContributionsCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetAllContributions( base::BindOnce(&RewardsServiceImpl::OnGetAllContributions, AsWeakPtr(), @@ -3604,6 +3843,10 @@ void RewardsServiceImpl::OnGetAllContributions( } void RewardsServiceImpl::GetAllPromotions(GetAllPromotionsCallback callback) { + if (!Connected()) { + return; + } + bat_ledger_->GetAllPromotions( base::BindOnce(&RewardsServiceImpl::OnGetAllPromotions, AsWeakPtr(), @@ -3634,4 +3877,8 @@ void RewardsServiceImpl::OnGetAllPromotions( std::move(callback).Run(std::move(converted_rewards)); } +void RewardsServiceImpl::ClearAllNotifications() { + notification_service_->DeleteAllNotifications(); +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index 518f9a3793b7..f8bb11db1636 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -26,7 +26,8 @@ #include "brave/components/greaselion/browser/buildflags/buildflags.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/associated_binding.h" +#include "mojo/public/cpp/bindings/associated_receiver.h" +#include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "brave/components/brave_rewards/browser/balance_report.h" #include "brave/components/brave_rewards/browser/content_site.h" @@ -315,6 +316,7 @@ class RewardsServiceImpl : public RewardsService, // Testing methods void SetLedgerEnvForTesting(); + void PrepareLedgerEnvForTesting(); void StartMonthlyContributionForTest(); void MaybeShowNotificationAddFundsForTesting( base::OnceCallback callback); @@ -327,8 +329,16 @@ class RewardsServiceImpl : public RewardsService, private: friend class ::RewardsFlagBrowserTest; + void EnableGreaseLion(const bool enabled); + + void StopLedger(); + + void OnStopLedger(const ledger::Result result); + const base::OneShotEvent& ready() const { return ready_; } + void OnCreate(); + void OnResult(ledger::ResultCallback callback, const ledger::Result result); void OnCreateWallet(CreateWalletCallback callback, @@ -638,6 +648,8 @@ class RewardsServiceImpl : public RewardsService, const bool recurring, const ledger::Result result); + void ClearAllNotifications() override; + // end ledger::LedgerClient // Mojo Proxy methods @@ -724,9 +736,9 @@ class RewardsServiceImpl : public RewardsService, #if BUILDFLAG(ENABLE_GREASELION) greaselion::GreaselionService* greaselion_service_; // NOT OWNED #endif - mojo::AssociatedBinding - bat_ledger_client_binding_; - bat_ledger::mojom::BatLedgerAssociatedPtr bat_ledger_; + mojo::AssociatedReceiver + bat_ledger_client_receiver_; + mojo::AssociatedRemote bat_ledger_; mojo::Remote bat_ledger_service_; const scoped_refptr file_task_runner_; const base::FilePath diagnostic_log_path_; @@ -753,6 +765,7 @@ class RewardsServiceImpl : public RewardsService, uint32_t next_timer_id_; bool reset_states_; bool is_wallet_initialized_ = false; + bool ledger_for_testing_ = false; GetTestResponseCallback test_response_callback_; diff --git a/components/brave_rewards/browser/test/common/rewards_browsertest_observer.cc b/components/brave_rewards/browser/test/common/rewards_browsertest_observer.cc deleted file mode 100644 index e7784ca254f8..000000000000 --- a/components/brave_rewards/browser/test/common/rewards_browsertest_observer.cc +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace rewards_browsertest { - -RewardsBrowserTestObserver::RewardsBrowserTestObserver() = default; - -RewardsBrowserTestObserver::~RewardsBrowserTestObserver() = default; - -void RewardsBrowserTestObserver::Initialize( - brave_rewards::RewardsServiceImpl* rewards_service) { - DCHECK(rewards_service); - rewards_service_ = rewards_service; - rewards_service_->AddObserver(this); -} - -void RewardsBrowserTestObserver::WaitForWalletInitialization() { - if (wallet_initialized_) { - return; - } - - wait_for_wallet_initialization_loop_.reset(new base::RunLoop); - wait_for_wallet_initialization_loop_->Run(); -} - -void RewardsBrowserTestObserver::OnWalletInitialized( - brave_rewards::RewardsService* rewards_service, - int32_t result) { - const auto converted_result = static_cast(result); - ASSERT_TRUE(converted_result == ledger::Result::WALLET_CREATED || - converted_result == ledger::Result::LEDGER_OK); - wallet_initialized_ = true; - - if (wait_for_wallet_initialization_loop_) { - wait_for_wallet_initialization_loop_->Quit(); - } -} - -} // namespace rewards_browsertest diff --git a/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h b/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h deleted file mode 100644 index 46f275dcd3e3..000000000000 --- a/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright (c) 2020 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_TEST_COMMON_REWARDS_BROWSERTEST_OBSERVER_H_ -#define BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_TEST_COMMON_REWARDS_BROWSERTEST_OBSERVER_H_ - -#include - -#include "base/run_loop.h" -#include "bat/ledger/mojom_structs.h" -#include "brave/components/brave_rewards/browser/rewards_service_impl.h" -#include "brave/components/brave_rewards/browser/rewards_service_observer.h" - -namespace rewards_browsertest { - -class RewardsBrowserTestObserver - : public brave_rewards::RewardsServiceObserver { - public: - RewardsBrowserTestObserver(); - ~RewardsBrowserTestObserver() override; - - void Initialize(brave_rewards::RewardsServiceImpl* rewards_service); - - void WaitForWalletInitialization(); - - private: - void OnWalletInitialized( - brave_rewards::RewardsService* rewards_service, - int32_t result) override; - - std::unique_ptr wait_for_wallet_initialization_loop_; - bool wallet_initialized_ = false; - - brave_rewards::RewardsServiceImpl* rewards_service_; -}; - -} // namespace rewards_browsertest -#endif // BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_TEST_COMMON_REWARDS_BROWSERTEST_OBSERVER_H_ diff --git a/components/brave_rewards/browser/test/rewards_browsertest.cc b/components/brave_rewards/browser/test/rewards_browsertest.cc index d64a63ca81b1..5f9db7b1a42b 100644 --- a/components/brave_rewards/browser/test/rewards_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_browsertest.cc @@ -15,7 +15,6 @@ #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_util.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" #include "chrome/browser/ui/views/frame/browser_view.h" @@ -32,7 +31,6 @@ namespace rewards_browsertest { class RewardsBrowserTest : public InProcessBrowserTest { public: RewardsBrowserTest() { - observer_ = std::make_unique(); response_ = std::make_unique(); contribution_ = std::make_unique(); } @@ -62,12 +60,6 @@ class RewardsBrowserTest : public InProcessBrowserTest { base::BindRepeating( &RewardsBrowserTest::GetTestResponse, base::Unretained(this))); - - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } rewards_service_->SetLedgerEnvForTesting(); // Other @@ -111,7 +103,6 @@ class RewardsBrowserTest : public InProcessBrowserTest { brave_rewards::RewardsServiceImpl* rewards_service_; std::unique_ptr https_server_; std::unique_ptr contribution_; - std::unique_ptr observer_; std::unique_ptr response_; }; diff --git a/components/brave_rewards/browser/test/rewards_contribution_browsertest.cc b/components/brave_rewards/browser/test/rewards_contribution_browsertest.cc index a00a8464c519..0aac18dc6daa 100644 --- a/components/brave_rewards/browser/test/rewards_contribution_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_contribution_browsertest.cc @@ -14,7 +14,6 @@ #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_util.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_promotion.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" @@ -34,7 +33,6 @@ class RewardsContributionBrowserTest : public InProcessBrowserTest { public: RewardsContributionBrowserTest() { contribution_ = std::make_unique(); - observer_ = std::make_unique(); promotion_ = std::make_unique(); response_ = std::make_unique(); } @@ -64,12 +62,6 @@ class RewardsContributionBrowserTest : public InProcessBrowserTest { base::BindRepeating( &RewardsContributionBrowserTest::GetTestResponse, base::Unretained(this))); - - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } rewards_service_->SetLedgerEnvForTesting(); // Other @@ -121,7 +113,6 @@ class RewardsContributionBrowserTest : public InProcessBrowserTest { brave_rewards::RewardsServiceImpl* rewards_service_; std::unique_ptr https_server_; std::unique_ptr contribution_; - std::unique_ptr observer_; std::unique_ptr promotion_; std::unique_ptr response_; }; diff --git a/components/brave_rewards/browser/test/rewards_database_browsertest.cc b/components/brave_rewards/browser/test/rewards_database_browsertest.cc index cb7aeb616e8b..035d9852f877 100644 --- a/components/brave_rewards/browser/test/rewards_database_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_database_browsertest.cc @@ -11,11 +11,14 @@ #include "brave/browser/brave_rewards/rewards_service_factory.h" #include "brave/common/brave_paths.h" #include "brave/components/brave_rewards/browser/rewards_service_impl.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" +#include "net/dns/mock_host_resolver.h" #include "sql/database.h" #include "sql/meta_table.h" #include "sql/statement.h" @@ -27,7 +30,7 @@ namespace rewards_browsertest { class RewardsDatabaseBrowserTest : public InProcessBrowserTest { public: RewardsDatabaseBrowserTest() { - observer_ = std::make_unique(); + response_ = std::make_unique(); } bool SetUpUserDataDirectory() override { @@ -40,20 +43,43 @@ class RewardsDatabaseBrowserTest : public InProcessBrowserTest { void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); + // HTTP resolver + https_server_.reset(new net::EmbeddedTestServer( + net::test_server::EmbeddedTestServer::TYPE_HTTPS)); + https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); + https_server_->RegisterRequestHandler( + base::BindRepeating(&rewards_browsertest_util::HandleRequest)); + ASSERT_TRUE(https_server_->Start()); + // Rewards service brave::RegisterPathProvider(); + auto* profile = browser()->profile(); rewards_service_ = static_cast( - brave_rewards::RewardsServiceFactory::GetForProfile( - browser()->profile())); + brave_rewards::RewardsServiceFactory::GetForProfile(profile)); - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } + // Response mock + base::ScopedAllowBlockingForTesting allow_blocking; + response_->LoadMocks(); + rewards_service_->ForTestingSetTestResponseCallback( + base::BindRepeating( + &RewardsDatabaseBrowserTest::GetTestResponse, + base::Unretained(this))); rewards_service_->SetLedgerEnvForTesting(); } + void GetTestResponse( + const std::string& url, + int32_t method, + int* response_status_code, + std::string* response, + std::map* headers) { + response_->Get( + url, + method, + response_status_code, + response); + } + void TearDown() override { InProcessBrowserTest::TearDown(); } @@ -142,9 +168,6 @@ class RewardsDatabaseBrowserTest : public InProcessBrowserTest { &db_, braveledger_database::GetCurrentVersion(), braveledger_database::GetCompatibleVersion())); - ASSERT_EQ( - GetTableVersionNumber(), - braveledger_database::GetCurrentVersion()); } std::string GetSchemaString() { @@ -215,10 +238,10 @@ class RewardsDatabaseBrowserTest : public InProcessBrowserTest { } brave_rewards::RewardsServiceImpl* rewards_service_; - std::unique_ptr observer_; - sql::Database db_; sql::MetaTable meta_table_; + std::unique_ptr https_server_; + std::unique_ptr response_; }; /** @@ -256,9 +279,12 @@ IN_PROC_BROWSER_TEST_P(SchemaCheck, PerVersion) { { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(param.version); - + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); const std::string schema = GetSchema(); EXPECT_EQ(schema, GetSchemaString()); + ASSERT_EQ( + GetTableVersionNumber(), + braveledger_database::GetCurrentVersion()); } } @@ -274,6 +300,7 @@ IN_PROC_BROWSER_TEST_F(RewardsDatabaseBrowserTest, Migration_4_ActivityInfo) { { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); ledger::PublisherInfoList list; const std::string query = "SELECT publisher_id, visits FROM activity_info"; @@ -297,6 +324,7 @@ IN_PROC_BROWSER_TEST_F(RewardsDatabaseBrowserTest, Migration_5_ActivityInfo) { { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); ledger::PublisherInfoList list; const std::string query = "SELECT publisher_id, visits FROM activity_info"; @@ -321,6 +349,7 @@ IN_PROC_BROWSER_TEST_F(RewardsDatabaseBrowserTest, Migration_6_ActivityInfo) { { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); ledger::PublisherInfoList list; const std::string query = @@ -373,6 +402,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); auto pending_contribution = ledger::PendingContribution::New(); pending_contribution->publisher_key = "reddit.com"; @@ -406,6 +436,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("contribution_info"), 5); EXPECT_EQ(CountTableRows("contribution_info_publishers"), 4); @@ -454,6 +485,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("pending_contribution"), 4); @@ -486,6 +518,7 @@ IN_PROC_BROWSER_TEST_F(RewardsDatabaseBrowserTest, Migration_13_Promotion) { { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("promotion"), 1); } @@ -497,6 +530,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("unblinded_tokens"), 5); @@ -533,6 +567,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("contribution_info"), 5); @@ -557,6 +592,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("promotion"), 2); @@ -587,6 +623,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("creds_batch"), 2); @@ -640,6 +677,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("unblinded_tokens"), 80); @@ -668,6 +706,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("contribution_info_publishers"), 4); @@ -713,6 +752,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("contribution_queue"), 1); @@ -763,6 +803,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("contribution_queue"), 1); @@ -796,6 +837,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("unblinded_tokens"), 1); @@ -832,6 +874,7 @@ IN_PROC_BROWSER_TEST_F( { base::ScopedAllowBlockingForTesting allow_blocking; InitDB(); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ(CountTableRows("unblinded_tokens"), 10); diff --git a/components/brave_rewards/browser/test/rewards_flag_browsertest.cc b/components/brave_rewards/browser/test/rewards_flag_browsertest.cc index 87d04d1e690b..4cdd2adf3aaa 100644 --- a/components/brave_rewards/browser/test/rewards_flag_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_flag_browsertest.cc @@ -9,11 +9,13 @@ #include "brave/browser/brave_rewards/rewards_service_factory.h" #include "brave/common/brave_paths.h" #include "brave/components/brave_rewards/browser/rewards_service_impl.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" +#include "net/dns/mock_host_resolver.h" #include "testing/gmock/include/gmock/gmock.h" // npm run test -- brave_browser_tests --filter=RewardsFlagBrowserTest.* @@ -23,26 +25,49 @@ namespace rewards_browsertest { class RewardsFlagBrowserTest : public InProcessBrowserTest { public: RewardsFlagBrowserTest() { - observer_ = std::make_unique(); + response_ = std::make_unique(); } void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); + // HTTP resolver + https_server_.reset(new net::EmbeddedTestServer( + net::test_server::EmbeddedTestServer::TYPE_HTTPS)); + https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); + https_server_->RegisterRequestHandler( + base::BindRepeating(&rewards_browsertest_util::HandleRequest)); + ASSERT_TRUE(https_server_->Start()); + // Rewards service brave::RegisterPathProvider(); auto* profile = browser()->profile(); rewards_service_ = static_cast( brave_rewards::RewardsServiceFactory::GetForProfile(profile)); - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } + // Response mock + base::ScopedAllowBlockingForTesting allow_blocking; + response_->LoadMocks(); + rewards_service_->ForTestingSetTestResponseCallback( + base::BindRepeating( + &RewardsFlagBrowserTest::GetTestResponse, + base::Unretained(this))); rewards_service_->SetLedgerEnvForTesting(); } + void GetTestResponse( + const std::string& url, + int32_t method, + int* response_status_code, + std::string* response, + std::map* headers) { + response_->Get( + url, + method, + response_status_code, + response); + } + void TearDown() override { InProcessBrowserTest::TearDown(); } @@ -121,137 +146,127 @@ class RewardsFlagBrowserTest : public InProcessBrowserTest { MOCK_METHOD1(OnGetShortRetries, void(bool)); brave_rewards::RewardsServiceImpl* rewards_service_; - std::unique_ptr observer_; + std::unique_ptr https_server_; + std::unique_ptr response_; bool callback_called_ = false; std::unique_ptr wait_for_callback_; }; -IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsSingleArg) { - testing::InSequence s; - // SetEnvironment(ledger::Environment::PRODUCTION) - EXPECT_CALL(*this, OnGetEnvironment(ledger::Environment::PRODUCTION)); - // Staging - true and 1 +IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsStaging) { EXPECT_CALL(*this, OnGetEnvironment(ledger::Environment::STAGING)).Times(2); - // Staging - false and random EXPECT_CALL(*this, OnGetEnvironment( - ledger::Environment::PRODUCTION)).Times(2); + ledger::Environment::PRODUCTION)).Times(3); + + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); + testing::InSequence s; rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); GetEnvironment(); - // Staging - true rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->HandleFlags("staging=true"); GetEnvironment(); - // Staging - 1 rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->HandleFlags("staging=1"); GetEnvironment(); - // Staging - false rewards_service_->SetEnvironment(ledger::Environment::STAGING); rewards_service_->HandleFlags("staging=false"); GetEnvironment(); - // Staging - random rewards_service_->SetEnvironment(ledger::Environment::STAGING); rewards_service_->HandleFlags("staging=werwe"); GetEnvironment(); +} - // SetDebug(true) - EXPECT_CALL(*this, OnGetDebug(true)); - // Debug - true and 1 - EXPECT_CALL(*this, OnGetDebug(true)).Times(2); - // Debug - false and random +IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsDebug) { + EXPECT_CALL(*this, OnGetDebug(true)).Times(3); EXPECT_CALL(*this, OnGetDebug(false)).Times(2); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); + testing::InSequence s; + rewards_service_->SetDebug(true); GetDebug(); - // Debug - true rewards_service_->SetDebug(false); rewards_service_->HandleFlags("debug=true"); GetDebug(); - // Debug - 1 rewards_service_->SetDebug(false); rewards_service_->HandleFlags("debug=1"); GetDebug(); - // Debug - false rewards_service_->SetDebug(true); rewards_service_->HandleFlags("debug=false"); GetDebug(); - // Debug - random rewards_service_->SetDebug(true); rewards_service_->HandleFlags("debug=werwe"); GetDebug(); +} - // SetEnvironment(ledger::Environment::PRODUCTION) - EXPECT_CALL(*this, OnGetEnvironment(ledger::Environment::PRODUCTION)); - // Development - true and 1 - EXPECT_CALL( - *this, - OnGetEnvironment(ledger::Environment::DEVELOPMENT)).Times(2); - // Development - false and random - EXPECT_CALL( - *this, - OnGetEnvironment(ledger::Environment::PRODUCTION)).Times(2); +IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsDevelopment) { + EXPECT_CALL(*this, OnGetEnvironment(ledger::Environment::DEVELOPMENT)) + .Times(2); + EXPECT_CALL(*this, OnGetEnvironment(ledger::Environment::PRODUCTION)) + .Times(3); + + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); + testing::InSequence s; rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); GetEnvironment(); - // Development - true rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->HandleFlags("development=true"); GetEnvironment(); - // Development - 1 rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->HandleFlags("development=1"); GetEnvironment(); - // Development - false rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->HandleFlags("development=false"); GetEnvironment(); - // Development - random rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->HandleFlags("development=werwe"); GetEnvironment(); +} - // positive number +IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsReconcile) { EXPECT_CALL(*this, OnGetReconcileInterval(10)); - // negative number and string EXPECT_CALL(*this, OnGetReconcileInterval(0)).Times(2); - // Reconcile interval - positive number + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); + testing::InSequence s; + rewards_service_->SetReconcileInterval(0); rewards_service_->HandleFlags("reconcile-interval=10"); GetReconcileInterval(); - // Reconcile interval - negative number rewards_service_->SetReconcileInterval(0); rewards_service_->HandleFlags("reconcile-interval=-1"); GetReconcileInterval(); - // Reconcile interval - string rewards_service_->SetReconcileInterval(0); rewards_service_->HandleFlags("reconcile-interval=sdf"); GetReconcileInterval(); +} - EXPECT_CALL(*this, OnGetShortRetries(true)); // on - EXPECT_CALL(*this, OnGetShortRetries(false)); // off +IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsShortRetries) { + EXPECT_CALL(*this, OnGetShortRetries(true)); + EXPECT_CALL(*this, OnGetShortRetries(false)); + + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); + testing::InSequence s; - // Short retries - on rewards_service_->SetShortRetries(false); rewards_service_->HandleFlags("short-retries=true"); GetShortRetries(); - // Short retries - off rewards_service_->SetShortRetries(true); rewards_service_->HandleFlags("short-retries=false"); GetShortRetries(); @@ -263,6 +278,8 @@ IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsMultipleFlags) { EXPECT_CALL(*this, OnGetReconcileInterval(10)); EXPECT_CALL(*this, OnGetShortRetries(true)); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); + testing::InSequence s; rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->SetDebug(true); rewards_service_->SetReconcileInterval(0); @@ -283,6 +300,8 @@ IN_PROC_BROWSER_TEST_F(RewardsFlagBrowserTest, HandleFlagsWrongInput) { EXPECT_CALL(*this, OnGetReconcileInterval(0)); EXPECT_CALL(*this, OnGetShortRetries(false)); + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); + testing::InSequence s; rewards_service_->SetEnvironment(ledger::Environment::PRODUCTION); rewards_service_->SetDebug(false); rewards_service_->SetReconcileInterval(0); diff --git a/components/brave_rewards/browser/test/rewards_notification_browsertest.cc b/components/brave_rewards/browser/test/rewards_notification_browsertest.cc index d4dd781a27c2..34d896aefb1e 100644 --- a/components/brave_rewards/browser/test/rewards_notification_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_notification_browsertest.cc @@ -11,7 +11,6 @@ #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_helper.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_promotion.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" @@ -35,7 +34,6 @@ class RewardsNotificationBrowserTest public: RewardsNotificationBrowserTest() { contribution_ = std::make_unique(); - observer_ = std::make_unique(); promotion_ = std::make_unique(); response_ = std::make_unique(); } @@ -65,12 +63,6 @@ class RewardsNotificationBrowserTest base::BindRepeating( &RewardsNotificationBrowserTest::GetTestResponse, base::Unretained(this))); - - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } rewards_service_->SetLedgerEnvForTesting(); // Other @@ -218,7 +210,6 @@ class RewardsNotificationBrowserTest brave_rewards::RewardsServiceImpl* rewards_service_; std::unique_ptr https_server_; std::unique_ptr contribution_; - std::unique_ptr observer_; std::unique_ptr promotion_; std::unique_ptr response_; diff --git a/components/brave_rewards/browser/test/rewards_promotion_browsertest.cc b/components/brave_rewards/browser/test/rewards_promotion_browsertest.cc index 8fa7d59581b6..faf5bfff4e3a 100644 --- a/components/brave_rewards/browser/test/rewards_promotion_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_promotion_browsertest.cc @@ -9,7 +9,6 @@ #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_helper.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_util.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_promotion.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" @@ -25,7 +24,6 @@ namespace rewards_browsertest { class RewardsPromotionBrowserTest : public InProcessBrowserTest { public: RewardsPromotionBrowserTest() { - observer_ = std::make_unique(); promotion_ = std::make_unique(); response_ = std::make_unique(); } @@ -34,7 +32,6 @@ class RewardsPromotionBrowserTest : public InProcessBrowserTest { InProcessBrowserTest::SetUpOnMainThread(); // HTTP resolver - host_resolver()->AddRule("*", "127.0.0.1"); https_server_.reset(new net::EmbeddedTestServer( net::test_server::EmbeddedTestServer::TYPE_HTTPS)); https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); @@ -55,12 +52,6 @@ class RewardsPromotionBrowserTest : public InProcessBrowserTest { base::BindRepeating( &RewardsPromotionBrowserTest::GetTestResponse, base::Unretained(this))); - - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } rewards_service_->SetLedgerEnvForTesting(); // Other @@ -151,7 +142,6 @@ class RewardsPromotionBrowserTest : public InProcessBrowserTest { brave_rewards::RewardsServiceImpl* rewards_service_; std::unique_ptr https_server_; - std::unique_ptr observer_; std::unique_ptr promotion_; std::unique_ptr response_; }; diff --git a/components/brave_rewards/browser/test/rewards_publisher_browsertest.cc b/components/brave_rewards/browser/test/rewards_publisher_browsertest.cc index ed9ec76bc490..53eb223ad60e 100644 --- a/components/brave_rewards/browser/test/rewards_publisher_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_publisher_browsertest.cc @@ -9,7 +9,6 @@ #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_helper.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_util.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" #include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" #include "chrome/browser/ui/views/frame/browser_view.h" @@ -26,7 +25,6 @@ namespace rewards_browsertest { class RewardsPublisherBrowserTest : public InProcessBrowserTest { public: RewardsPublisherBrowserTest() { - observer_ = std::make_unique(); response_ = std::make_unique(); } @@ -55,12 +53,6 @@ class RewardsPublisherBrowserTest : public InProcessBrowserTest { base::BindRepeating( &RewardsPublisherBrowserTest::GetTestResponse, base::Unretained(this))); - - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } rewards_service_->SetLedgerEnvForTesting(); } @@ -93,7 +85,6 @@ class RewardsPublisherBrowserTest : public InProcessBrowserTest { brave_rewards::RewardsServiceImpl* rewards_service_; std::unique_ptr https_server_; - std::unique_ptr observer_; std::unique_ptr response_; }; diff --git a/components/brave_rewards/browser/test/rewards_state_browsertest.cc b/components/brave_rewards/browser/test/rewards_state_browsertest.cc index 798185c6fd58..46664f7e44d8 100644 --- a/components/brave_rewards/browser/test/rewards_state_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_state_browsertest.cc @@ -12,11 +12,14 @@ #include "brave/common/brave_paths.h" #include "brave/components/brave_rewards/browser/balance_report.h" #include "brave/components/brave_rewards/browser/rewards_service_impl.h" -#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.h" +#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_util.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" +#include "net/dns/mock_host_resolver.h" // npm run test -- brave_browser_tests --filter=RewardsStateBrowserTest.* @@ -25,7 +28,7 @@ namespace rewards_browsertest { class RewardsStateBrowserTest : public InProcessBrowserTest { public: RewardsStateBrowserTest() { - observer_ = std::make_unique(); + response_ = std::make_unique(); } bool SetUpUserDataDirectory() override { @@ -39,20 +42,43 @@ class RewardsStateBrowserTest : public InProcessBrowserTest { void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); + // HTTP resolver + https_server_.reset(new net::EmbeddedTestServer( + net::test_server::EmbeddedTestServer::TYPE_HTTPS)); + https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); + https_server_->RegisterRequestHandler( + base::BindRepeating(&rewards_browsertest_util::HandleRequest)); + ASSERT_TRUE(https_server_->Start()); + // Rewards service brave::RegisterPathProvider(); profile_ = browser()->profile(); rewards_service_ = static_cast( brave_rewards::RewardsServiceFactory::GetForProfile(profile_)); - // Observer - observer_->Initialize(rewards_service_); - if (!rewards_service_->IsWalletInitialized()) { - observer_->WaitForWalletInitialization(); - } + // Response mock + base::ScopedAllowBlockingForTesting allow_blocking; + response_->LoadMocks(); + rewards_service_->ForTestingSetTestResponseCallback( + base::BindRepeating( + &RewardsStateBrowserTest::GetTestResponse, + base::Unretained(this))); rewards_service_->SetLedgerEnvForTesting(); } + void GetTestResponse( + const std::string& url, + int32_t method, + int* response_status_code, + std::string* response, + std::map* headers) { + response_->Get( + url, + method, + response_status_code, + response); + } + void TearDown() override { InProcessBrowserTest::TearDown(); } @@ -135,12 +161,13 @@ class RewardsStateBrowserTest : public InProcessBrowserTest { } brave_rewards::RewardsServiceImpl* rewards_service_; - std::unique_ptr observer_; - Profile* profile_; + std::unique_ptr https_server_; + std::unique_ptr response_; }; IN_PROC_BROWSER_TEST_F(RewardsStateBrowserTest, State_1) { + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ( profile_->GetPrefs()->GetInteger("brave.rewards.ac.min_visit_time"), 5); @@ -184,6 +211,7 @@ IN_PROC_BROWSER_TEST_F(RewardsStateBrowserTest, State_1) { } IN_PROC_BROWSER_TEST_F(RewardsStateBrowserTest, State_2) { + rewards_browsertest_util::EnableRewardsViaCode(browser(), rewards_service_); EXPECT_EQ( profile_->GetPrefs()->GetString("brave.rewards.wallet.payment_id"), "eea767c4-cd27-4411-afd4-78a9c6b54dbc"); diff --git a/components/brave_rewards/resources/android_page/actions/rewards_actions.ts b/components/brave_rewards/resources/android_page/actions/rewards_actions.ts index 96957184d2e6..84a88a31dff8 100644 --- a/components/brave_rewards/resources/android_page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/android_page/actions/rewards_actions.ts @@ -193,3 +193,11 @@ export const onlyAnonWallet = () => action(types.ONLY_ANON_WALLET) export const onOnlyAnonWallet = (only: boolean) => action(types.ON_ONLY_ANON_WALLET, { only }) + +export const toggleEnableMain = (enable: boolean) => action(types.TOGGLE_ENABLE_MAIN, { + enable +}) + +export const onInitialized = (result: boolean) => action(types.ON_INITIALIZED, { + result +}) diff --git a/components/brave_rewards/resources/android_page/brave_rewards_page.tsx b/components/brave_rewards/resources/android_page/brave_rewards_page.tsx index 670df00b34e9..b5a05df5c17e 100644 --- a/components/brave_rewards/resources/android_page/brave_rewards_page.tsx +++ b/components/brave_rewards/resources/android_page/brave_rewards_page.tsx @@ -178,6 +178,10 @@ window.cr.define('brave_rewards', function () { getActions().getBalance() } + function initialized (result: number) { + getActions().onInitialized(result) + } + return { initialize, walletCreated, @@ -208,7 +212,8 @@ window.cr.define('brave_rewards', function () { balance, reconcileComplete, onlyAnonWallet, - unblindedTokensReady + unblindedTokensReady, + initialized } }) diff --git a/components/brave_rewards/resources/android_page/components/settingsPage.tsx b/components/brave_rewards/resources/android_page/components/settingsPage.tsx index b2b1baed3442..08f922e7c168 100644 --- a/components/brave_rewards/resources/android_page/components/settingsPage.tsx +++ b/components/brave_rewards/resources/android_page/components/settingsPage.tsx @@ -51,7 +51,11 @@ class SettingsPage extends React.Component { onToggle = () => { this.setState({ mainToggle: !this.state.mainToggle }) - this.actions.onSettingSave('enabledMain', !this.props.rewardsData.enabledMain) + if (this.props.rewardsData.initializing) { + return + } + + this.actions.toggleEnableMain(!this.props.rewardsData.enabledMain) } onToggleWallet = () => { @@ -76,53 +80,36 @@ class SettingsPage extends React.Component { } componentDidMount () { + this.actions.getRewardsMainEnabled() + if (this.props.rewardsData.firstLoad === null) { // First load ever - this.actions.onSettingSave('firstLoad', true) - this.actions.getWalletPassphrase() + this.actions.onSettingSave('firstLoad', true, false) } else if (this.props.rewardsData.firstLoad) { // Second load ever - this.actions.onSettingSave('firstLoad', false) + this.actions.onSettingSave('firstLoad', false, false) } - this.actions.getRewardsParameters() - this.actions.getAutoContributeProperties() - this.actions.getBalance() - this.balanceTimerId = setInterval(() => { - this.actions.getBalance() - }, 60000) - - if (this.props.rewardsData.firstLoad === false) { - this.refreshActions() - } else { - this.actions.getAdsData() + if (this.props.rewardsData.enabledMain && + !this.props.rewardsData.initializing) { + this.startRewards() } - - this.isWalletUrl() - - this.actions.fetchPromotions() - - window.addEventListener('popstate', (e) => { - this.isWalletUrl() - }) - window.addEventListener('hashchange', (e) => { - this.isWalletUrl() - }) } componentDidUpdate (prevProps: Props) { if ( - !prevProps.rewardsData.enabledMain && - this.props.rewardsData.enabledMain + this.props.rewardsData.enabledMain && + prevProps.rewardsData.initializing && + !this.props.rewardsData.initializing ) { - this.refreshActions() + this.startRewards() } if ( - !prevProps.rewardsData.adsData.adsEnabled && - this.props.rewardsData.adsData.adsEnabled + prevProps.rewardsData.enabledMain && + !this.props.rewardsData.enabledMain ) { - this.actions.getTransactionHistory() + this.stopRewards() } if ( @@ -130,9 +117,49 @@ class SettingsPage extends React.Component { this.props.rewardsData.enabledContribute ) { this.actions.getContributeList() + this.actions.getReconcileStamp() + } + + if ( + !prevProps.rewardsData.adsData.adsEnabled && + this.props.rewardsData.adsData.adsEnabled + ) { + this.actions.getTransactionHistory() } } + startRewards () { + if (this.props.rewardsData.firstLoad) { + this.actions.getAdsData() + this.actions.getWalletPassphrase() + } else { + // normal load + this.refreshActions() + } + + this.actions.getRewardsParameters() + this.actions.getContributionAmount() + this.actions.getAutoContributeProperties() + this.actions.getBalance() + this.balanceTimerId = setInterval(() => { + this.actions.getBalance() + }, 60000) + + this.actions.fetchPromotions() + this.isWalletUrl() + window.addEventListener('popstate', (e) => { + this.isWalletUrl() + }) + window.addEventListener('hashchange', (e) => { + this.isWalletUrl() + }) + } + + stopRewards () { + clearInterval(this.balanceTimerId) + this.balanceTimerId = -1 + } + isWalletUrl = () => { const walletShown = ( window && @@ -175,7 +202,7 @@ class SettingsPage extends React.Component { } componentWillUnmount () { - clearInterval(this.balanceTimerId) + this.stopRewards() } render () { diff --git a/components/brave_rewards/resources/android_page/constants/rewards_types.ts b/components/brave_rewards/resources/android_page/constants/rewards_types.ts index b1e665d81ad4..94ed88b306cf 100644 --- a/components/brave_rewards/resources/android_page/constants/rewards_types.ts +++ b/components/brave_rewards/resources/android_page/constants/rewards_types.ts @@ -60,5 +60,7 @@ export const enum types { GET_BALANCE = '@@rewards/GET_BALANCE', ON_BALANCE = '@@rewards/ON_BALANCE', ONLY_ANON_WALLET = '@@rewards/ONLY_ANON_WALLET', - ON_ONLY_ANON_WALLET = '@@rewards/ON_ONLY_ANON_WALLET' + ON_ONLY_ANON_WALLET = '@@rewards/ON_ONLY_ANON_WALLET', + TOGGLE_ENABLE_MAIN = '@@rewards/TOGGLE_ENABLE_MAIN', + ON_INITIALIZED = '@@rewards/ON_INITIALIZED' } diff --git a/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts b/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts index 4508f215dc3f..125407c22ccb 100644 --- a/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts @@ -10,6 +10,23 @@ import { defaultState } from '../storage' const rewardsReducer: Reducer = (state: Rewards.State, action) => { switch (action.type) { + case types.TOGGLE_ENABLE_MAIN: { + if (state.initializing) { + break + } + + state = { ...state } + const key = 'enabledMain' + const enable = action.payload.enable + + if (enable) { + state.initializing = true + } + + state[key] = enable + chrome.send('brave_rewards.saveSetting', [key, enable.toString()]) + break + } case types.GET_AUTO_CONTRIBUTE_PROPERTIES: { chrome.send('brave_rewards.getAutoContributeProperties') break @@ -138,8 +155,17 @@ const rewardsReducer: Reducer = (state: Rewards.State break } case types.ON_REWARDS_ENABLED: { + const enabled: boolean = action.payload.enabled state = { ...state } - state.enabledMain = action.payload.enabled + if (state.enabledMain && !enabled) { + state = defaultState + state.enabledMain = false + state.walletCreated = true + state.firstLoad = false + break + } + + state.enabledMain = enabled break } case types.GET_TRANSACTION_HISTORY: @@ -211,6 +237,13 @@ const rewardsReducer: Reducer = (state: Rewards.State } break } + case types.ON_INITIALIZED: { + state = { + ...state, + initializing: false + } + break + } } return state diff --git a/components/brave_rewards/resources/android_page/reducers/wallet_reducer.ts b/components/brave_rewards/resources/android_page/reducers/wallet_reducer.ts index bb3cedf18fcc..cdd382e133b3 100644 --- a/components/brave_rewards/resources/android_page/reducers/wallet_reducer.ts +++ b/components/brave_rewards/resources/android_page/reducers/wallet_reducer.ts @@ -25,15 +25,18 @@ const walletReducer: Reducer = (state: Rewards.State, state = { ...state } state.walletCreateFailed = false state.walletCreated = false + state.initializing = true chrome.send('brave_rewards.createWalletRequested') break case types.WALLET_CREATED: state = { ...state } state = createWallet(state) + state.initializing = false chrome.send('brave_rewards.saveAdsSetting', ['adsEnabled', 'true']) break case types.WALLET_CREATE_FAILED: state = { ...state } + state.initializing = false state.walletCreateFailed = true break case types.GET_REWARDS_PARAMETERS: diff --git a/components/brave_rewards/resources/android_page/storage.ts b/components/brave_rewards/resources/android_page/storage.ts index 1c03e15e5e01..84229582d94f 100644 --- a/components/brave_rewards/resources/android_page/storage.ts +++ b/components/brave_rewards/resources/android_page/storage.ts @@ -78,7 +78,8 @@ export const defaultState: Rewards.State = { autoContributeChoice: 0, autoContributeChoices: [], rate: 0 - } + }, + initializing: false } const cleanData = (state: Rewards.State) => { diff --git a/components/brave_rewards/resources/extension/brave_rewards/actions/rewards_panel_actions.ts b/components/brave_rewards/resources/extension/brave_rewards/actions/rewards_panel_actions.ts index f208ec5bc8cb..8509bfeaa1b8 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/actions/rewards_panel_actions.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/actions/rewards_panel_actions.ts @@ -147,3 +147,5 @@ export const onExternalWallet = (wallet: RewardsExtension.ExternalWallet) => act export const onAnonWalletStatus = (result: RewardsExtension.Result) => action(types.ON_ANON_WALLET_STATUS, { result }) + +export const onAllNotificationsDeleted = () => action(types.ON_ALL_NOTIFICATIONS_DELETED) diff --git a/components/brave_rewards/resources/extension/brave_rewards/background/events/rewardsEvents.ts b/components/brave_rewards/resources/extension/brave_rewards/background/events/rewardsEvents.ts index 979f9d33e6da..6fe403c12cc3 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/background/events/rewardsEvents.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/background/events/rewardsEvents.ts @@ -34,6 +34,10 @@ chrome.rewardsNotifications.onNotificationDeleted.addListener((id: string, type: }) }) +chrome.rewardsNotifications.onAllNotificationsDeleted.addListener(() => { + rewardsPanelActions.onAllNotificationsDeleted() +}) + chrome.braveRewards.onEnabledMain.addListener((enabledMain: boolean) => { rewardsPanelActions.onEnabledMain(enabledMain) }) diff --git a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts index 6b23ed98aaa9..b378bebe8645 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts @@ -253,10 +253,19 @@ export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, a } case types.ON_ENABLED_MAIN: { state = { ...state } - if (payload.enabledMain == null) { + const enabled = payload.enabledMain + if (enabled == null) { break } - state.enabledMain = payload.enabledMain + + if (state.enabledMain && !enabled) { + state = storage.defaultState + state.enabledMain = false + state.walletCreated = true + break + } + + state.enabledMain = enabled break } case types.ON_ENABLED_AC: { @@ -395,6 +404,7 @@ export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, a notifications: {}, currentNotification: undefined } + setBadgeText(state) break } @@ -485,6 +495,15 @@ export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, a } break } + case types.ON_ALL_NOTIFICATIONS_DELETED: { + state = { + ...state, + notifications: {}, + currentNotification: undefined + } + setBadgeText(state) + break + } } return state } diff --git a/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx b/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx index 978fc9b9cb08..6a413f8efbb3 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx +++ b/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx @@ -46,12 +46,19 @@ export class RewardsPanel extends React.Component { }) }) - chrome.windows.getCurrent({}, this.onWindowCallback) - chrome.braveRewards.getRewardsMainEnabled(((enabled: boolean) => { this.props.actions.onEnabledMain(enabled) + + if (enabled) { + this.startRewards() + } })) + } + + startRewards = () => { + chrome.windows.getCurrent({}, this.onWindowCallback) + chrome.braveRewards.getAllNotifications((list: RewardsExtension.Notification[]) => { this.props.actions.onAllNotifications(list) }) @@ -76,9 +83,10 @@ export class RewardsPanel extends React.Component { ) { this.getTabData() } - if (!prevProps.rewardsPanelData.enabledMain && this.props.rewardsPanelData.enabledMain) { - chrome.windows.getCurrent({}, this.onWindowCallback) - this.getBalance() + + if (!prevProps.rewardsPanelData.enabledMain && + this.props.rewardsPanelData.enabledMain) { + this.startRewards() } } diff --git a/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx b/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx index b45330708d05..d531adce55da 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx +++ b/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx @@ -102,7 +102,8 @@ export class Panel extends React.Component { }) } - if (!prevProps.rewardsPanelData.enabledMain && this.props.rewardsPanelData.enabledMain) { + if (!prevProps.rewardsPanelData.enabledMain && + this.props.rewardsPanelData.enabledMain) { this.actions.fetchPromotions() } } diff --git a/components/brave_rewards/resources/extension/brave_rewards/constants/rewards_panel_types.ts b/components/brave_rewards/resources/extension/brave_rewards/constants/rewards_panel_types.ts index b7ddf4c11808..1d3f4a5a1f37 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/constants/rewards_panel_types.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/constants/rewards_panel_types.ts @@ -34,7 +34,8 @@ export const enum types { ON_INIT = '@@rewards_panel/ON_INIT', ON_BALANCE = '@@rewards_panel/ON_BALANCE', ON_EXTERNAL_WALLET = '@@rewards_panel/ON_EXTERNAL_WALLET', - ON_ANON_WALLET_STATUS = '@@rewards_panel/ON_ANON_WALLET_STATUS' + ON_ANON_WALLET_STATUS = '@@rewards_panel/ON_ANON_WALLET_STATUS', + ON_ALL_NOTIFICATIONS_DELETED = '@@rewards_panel/ON_ALL_NOTIFICATIONS_DELETED' } // Note: This declaration must match the RewardsNotificationType enum in diff --git a/components/brave_rewards/resources/extension/brave_rewards/utils.ts b/components/brave_rewards/resources/extension/brave_rewards/utils.ts index 56cc0d785f31..f53ddb7ab120 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/utils.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/utils.ts @@ -116,9 +116,9 @@ export const isPublisherNotVerified = (status?: RewardsExtension.PublisherStatus return status === 0 } -export const getWalletStatus = (externalWallet?: RewardsExtension.ExternalWallet): WalletState => { +export const getWalletStatus = (externalWallet?: RewardsExtension.ExternalWallet): WalletState | undefined => { if (!externalWallet) { - return 'unverified' + return undefined } switch (externalWallet.status) { diff --git a/components/brave_rewards/resources/internals/components/app.tsx b/components/brave_rewards/resources/internals/components/app.tsx index e08e63f84183..17577689de24 100644 --- a/components/brave_rewards/resources/internals/components/app.tsx +++ b/components/brave_rewards/resources/internals/components/app.tsx @@ -36,7 +36,18 @@ export class RewardsInternalsPage extends React.Component { } componentDidMount () { - this.getGeneralInfo() + // Process is not started until rewards is on, + // so we need to first check if rewards is on before we do anything + this.actions.getRewardsEnabled() + } + + componentDidUpdate (prevProps: Props, prevState: State) { + if ( + !prevProps.rewardsInternalsData.isRewardsEnabled && + this.props.rewardsInternalsData.isRewardsEnabled + ) { + this.getGeneralInfo() + } } get actions () { @@ -44,7 +55,6 @@ export class RewardsInternalsPage extends React.Component { } getGeneralInfo = () => { - this.actions.getRewardsEnabled() this.actions.getRewardsInternalsInfo() this.actions.getBalance() } @@ -100,7 +110,7 @@ export class RewardsInternalsPage extends React.Component { {getLocale('mainTitle')} - {getLocale('rewardsNotEnabled')} brave://rewards + {getLocale('rewardsNotEnabled')} brave://rewards ) } diff --git a/components/brave_rewards/resources/page/actions/rewards_actions.ts b/components/brave_rewards/resources/page/actions/rewards_actions.ts index e2c62a797b67..f694e995b1df 100644 --- a/components/brave_rewards/resources/page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/page/actions/rewards_actions.ts @@ -13,9 +13,10 @@ export const onWalletCreated = () => action(types.WALLET_CREATED) export const onWalletCreateFailed = () => action(types.WALLET_CREATE_FAILED) -export const onSettingSave = (key: string, value: any) => action(types.ON_SETTING_SAVE, { +export const onSettingSave = (key: string, value: any, persist: boolean = true) => action(types.ON_SETTING_SAVE, { key, - value + value, + persist }) export const updateAdsRewards = () => action(types.UPDATE_ADS_REWARDS) @@ -335,3 +336,11 @@ export const getCountryCode = () => action(types.GET_COUNTRY_CODE) export const onCountryCode = (countryCode: string) => action(types.ON_COUNTRY_CODE, { countryCode }) + +export const toggleEnableMain = (enable: boolean) => action(types.TOGGLE_ENABLE_MAIN, { + enable +}) + +export const onInitialized = (result: boolean) => action(types.ON_INITIALIZED, { + result +}) diff --git a/components/brave_rewards/resources/page/brave_rewards_page.tsx b/components/brave_rewards/resources/page/brave_rewards_page.tsx index cafff8b866ff..9ea3ec841db5 100644 --- a/components/brave_rewards/resources/page/brave_rewards_page.tsx +++ b/components/brave_rewards/resources/page/brave_rewards_page.tsx @@ -250,6 +250,10 @@ window.cr.define('brave_rewards', function () { getActions().onCountryCode(countryCode) } + function initialized (result: number) { + getActions().onInitialized(result) + } + return { initialize, walletCreated, @@ -296,7 +300,8 @@ window.cr.define('brave_rewards', function () { monthlyReport, reconcileStampReset, monthlyReportIds, - countryCode + countryCode, + initialized } }) diff --git a/components/brave_rewards/resources/page/components/settingsPage.tsx b/components/brave_rewards/resources/page/components/settingsPage.tsx index 251667ef40a4..76c0c9a38d67 100644 --- a/components/brave_rewards/resources/page/components/settingsPage.tsx +++ b/components/brave_rewards/resources/page/components/settingsPage.tsx @@ -45,7 +45,11 @@ class SettingsPage extends React.Component { } onToggle = () => { - this.actions.onSettingSave('enabledMain', !this.props.rewardsData.enabledMain) + if (this.props.rewardsData.initializing) { + return + } + + this.actions.toggleEnableMain(!this.props.rewardsData.enabledMain) } get actions () { @@ -65,55 +69,36 @@ class SettingsPage extends React.Component { } componentDidMount () { + this.actions.getRewardsMainEnabled() + if (this.props.rewardsData.firstLoad === null) { // First load ever - this.actions.onSettingSave('firstLoad', true) - this.actions.getWalletPassphrase() + this.actions.onSettingSave('firstLoad', true, false) } else if (this.props.rewardsData.firstLoad) { // Second load ever - this.actions.onSettingSave('firstLoad', false) + this.actions.onSettingSave('firstLoad', false, false) } - this.actions.getRewardsParameters() - this.actions.getContributionAmount() - this.actions.getAutoContributeProperties() - this.actions.getBalance() - this.balanceTimerId = setInterval(() => { - this.actions.getBalance() - }, 60000) - - if (this.props.rewardsData.firstLoad === false) { - this.refreshActions() - } else { - this.actions.getAdsData() - } - - this.actions.fetchPromotions() - this.actions.getRewardsMainEnabled() - this.actions.updateAdsRewards() - this.actions.getExternalWallet('uphold') - - // one time check (legacy fix) - if (!this.props.rewardsData.ui.paymentIdCheck) { - // https://github.com/brave/brave-browser/issues/3061 - this.actions.getWalletPassphrase() - } - - if (window.location.pathname.length > 1) { - const pathElements = window.location.pathname.split('/') - if (pathElements.length > 2) { - this.actions.processRewardsPageUrl(window.location.pathname, window.location.search) - } + if (this.props.rewardsData.enabledMain && + !this.props.rewardsData.initializing) { + this.startRewards() } } componentDidUpdate (prevProps: Props, prevState: State) { if ( - !prevProps.rewardsData.enabledMain && this.props.rewardsData.enabledMain && - this.props.rewardsData.firstLoad === false + prevProps.rewardsData.initializing && + !this.props.rewardsData.initializing ) { - this.refreshActions() + this.startRewards() + } + + if ( + prevProps.rewardsData.enabledMain && + !this.props.rewardsData.enabledMain + ) { + this.stopRewards() } if ( @@ -142,6 +127,40 @@ class SettingsPage extends React.Component { } } + stopRewards () { + clearInterval(this.balanceTimerId) + this.balanceTimerId = -1 + } + + startRewards () { + if (this.props.rewardsData.firstLoad) { + this.actions.getAdsData() + this.actions.getWalletPassphrase() + } else { + // normal load + this.refreshActions() + } + + this.actions.getRewardsParameters() + this.actions.getContributionAmount() + this.actions.getAutoContributeProperties() + this.actions.getBalance() + this.balanceTimerId = setInterval(() => { + this.actions.getBalance() + }, 60000) + + this.actions.fetchPromotions() + this.actions.updateAdsRewards() + this.actions.getExternalWallet('uphold') + + if (window.location.pathname.length > 1) { + const pathElements = window.location.pathname.split('/') + if (pathElements.length > 2) { + this.actions.processRewardsPageUrl(window.location.pathname, window.location.search) + } + } + } + openTOS () { window.open('https://basicattentiontoken.org/user-terms-of-service', '_blank') } @@ -184,7 +203,7 @@ class SettingsPage extends React.Component { } componentWillUnmount () { - clearInterval(this.balanceTimerId) + this.stopRewards() } onRedirectError = () => { diff --git a/components/brave_rewards/resources/page/constants/rewards_types.ts b/components/brave_rewards/resources/page/constants/rewards_types.ts index 5161de02cea6..158d9c927ae1 100644 --- a/components/brave_rewards/resources/page/constants/rewards_types.ts +++ b/components/brave_rewards/resources/page/constants/rewards_types.ts @@ -95,5 +95,7 @@ export const enum types { ON_MONTHLY_REPORT_IDS = '@@rewards/ON_MONTHLY_REPORT_IDS', DISMISS_PROMO_PROMPT = '@@rewards/DISMISS_PROMO_PROMPT', GET_COUNTRY_CODE = '@@rewards/GET_COUNTRY_CODE', - ON_COUNTRY_CODE = '@@rewards/ON_COUNTRY_CODE' + ON_COUNTRY_CODE = '@@rewards/ON_COUNTRY_CODE', + TOGGLE_ENABLE_MAIN = '@@rewards/TOGGLE_ENABLE_MAIN', + ON_INITIALIZED = '@@rewards/ON_INITIALIZED' } diff --git a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts index 8d387ee9e4a0..2cea2b59a953 100644 --- a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts @@ -10,6 +10,23 @@ import { defaultState } from '../storage' const rewardsReducer: Reducer = (state: Rewards.State, action) => { switch (action.type) { + case types.TOGGLE_ENABLE_MAIN: { + if (state.initializing) { + break + } + + state = { ...state } + const key = 'enabledMain' + const enable = action.payload.enable + + if (enable) { + state.initializing = true + } + + state[key] = enable + chrome.send('brave_rewards.saveSetting', [key, enable.toString()]) + break + } case types.GET_AUTO_CONTRIBUTE_PROPERTIES: { chrome.send('brave_rewards.getAutoContributeProperties') break @@ -38,15 +55,22 @@ const rewardsReducer: Reducer = (state: Rewards.State break } - case types.ON_SETTING_SAVE: + case types.ON_SETTING_SAVE: { state = { ...state } const key = action.payload.key const value = action.payload.value - if (key) { - state[key] = value + const persist = action.payload.persist + if (!key) { + break + } + + if (persist) { chrome.send('brave_rewards.saveSetting', [key, value.toString()]) } + + state[key] = value break + } case types.UPDATE_ADS_REWARDS: { state = { ...state } chrome.send('brave_rewards.updateAdsRewards') @@ -210,8 +234,17 @@ const rewardsReducer: Reducer = (state: Rewards.State break } case types.ON_REWARDS_ENABLED: { + const enabled: boolean = action.payload.enabled state = { ...state } - state.enabledMain = action.payload.enabled + if (state.enabledMain && !enabled) { + state = defaultState + state.enabledMain = false + state.walletCreated = true + state.firstLoad = false + break + } + + state.enabledMain = enabled break } case types.GET_TRANSACTION_HISTORY: @@ -394,6 +427,13 @@ const rewardsReducer: Reducer = (state: Rewards.State } break } + case types.ON_INITIALIZED: { + state = { + ...state, + initializing: false + } + break + } } return state diff --git a/components/brave_rewards/resources/page/reducers/wallet_reducer.ts b/components/brave_rewards/resources/page/reducers/wallet_reducer.ts index b68c6bfa6768..adaabf6f2b82 100644 --- a/components/brave_rewards/resources/page/reducers/wallet_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/wallet_reducer.ts @@ -27,15 +27,18 @@ const walletReducer: Reducer = (state: Rewards.State, state = { ...state } state.walletCreateFailed = false state.walletCreated = false + state.initializing = true chrome.send('brave_rewards.createWalletRequested') break case types.WALLET_CREATED: state = { ...state } state = createWallet(state) + state.initializing = false chrome.send('brave_rewards.saveAdsSetting', ['adsEnabled', 'true']) break case types.WALLET_CREATE_FAILED: state = { ...state } + state.initializing = false state.walletCreateFailed = true break case types.GET_REWARDS_PARAMETERS: diff --git a/components/brave_rewards/resources/page/storage.ts b/components/brave_rewards/resources/page/storage.ts index 67b302620e28..c0d64577b585 100644 --- a/components/brave_rewards/resources/page/storage.ts +++ b/components/brave_rewards/resources/page/storage.ts @@ -78,7 +78,8 @@ export const defaultState: Rewards.State = { autoContributeChoice: 0, autoContributeChoices: [], rate: 0 - } + }, + initializing: false } const cleanData = (state: Rewards.State) => { diff --git a/components/definitions/rewards.d.ts b/components/definitions/rewards.d.ts index 4967130511e0..99eecdbe995d 100644 --- a/components/definitions/rewards.d.ts +++ b/components/definitions/rewards.d.ts @@ -44,6 +44,7 @@ declare namespace Rewards { enabledContribute: boolean enabledMain: boolean externalWallet?: ExternalWallet + initializing: boolean inlineTip: { twitter: boolean reddit: boolean diff --git a/components/services/bat_ledger/BUILD.gn b/components/services/bat_ledger/BUILD.gn index 4ec4866445e3..61b374dfe74a 100644 --- a/components/services/bat_ledger/BUILD.gn +++ b/components/services/bat_ledger/BUILD.gn @@ -7,12 +7,12 @@ static_library("lib") { sources = [ "bat_ledger_app.cc", "bat_ledger_app.h", - "bat_ledger_client_mojo_proxy.cc", - "bat_ledger_client_mojo_proxy.h", - "bat_ledger_service_impl.cc", - "bat_ledger_service_impl.h", + "bat_ledger_client_mojo_bridge.cc", + "bat_ledger_client_mojo_bridge.h", "bat_ledger_impl.cc", "bat_ledger_impl.h", + "bat_ledger_service_impl.cc", + "bat_ledger_service_impl.h", ] public_deps = [ @@ -20,9 +20,8 @@ static_library("lib") { ] deps = [ - "//base", - "//brave/base", "//brave/vendor/bat-native-ledger", + "//mojo/public/cpp/system", "//services/service_manager/public/cpp", ] } diff --git a/components/services/bat_ledger/bat_ledger_app.cc b/components/services/bat_ledger/bat_ledger_app.cc index e256aed93f14..3ec9a87b6552 100644 --- a/components/services/bat_ledger/bat_ledger_app.cc +++ b/components/services/bat_ledger/bat_ledger_app.cc @@ -9,41 +9,36 @@ #include #include "brave/components/services/bat_ledger/bat_ledger_service_impl.h" -#include "mojo/public/cpp/bindings/strong_binding.h" namespace bat_ledger { -namespace { - -void OnBatLedgerServiceRequest( - service_manager::ServiceKeepalive* keepalive, - bat_ledger::mojom::BatLedgerServiceRequest request) { - - mojo::MakeStrongBinding( - std::make_unique( - keepalive->CreateRef()), std::move(request)); -} - -} // namespace - -BatLedgerApp::BatLedgerApp( - service_manager::mojom::ServiceRequest request) : +BatLedgerApp::BatLedgerApp(service_manager::mojom::ServiceRequest request) : service_binding_(this, std::move(request)), service_keepalive_(&service_binding_, base::TimeDelta()) { } -BatLedgerApp::~BatLedgerApp() {} +BatLedgerApp::~BatLedgerApp() = default; void BatLedgerApp::OnStart() { - registry_.AddInterface( - base::BindRepeating(&OnBatLedgerServiceRequest, &service_keepalive_)); + binders_.Add(base::BindRepeating(&BatLedgerApp::BindBatLedgerServiceReceiver, + base::Unretained(this), + &service_keepalive_)); +} + +void BatLedgerApp::BindBatLedgerServiceReceiver( + service_manager::ServiceKeepalive* keepalive, + mojo::PendingReceiver receiver) { + receivers_.Add( + std::make_unique( + keepalive->CreateRef()), + std::move(receiver)); } -void BatLedgerApp::OnBindInterface( - const service_manager::BindSourceInfo& source_info, +void BatLedgerApp::OnConnect( + const service_manager::ConnectSourceInfo& source_info, const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) { - registry_.BindInterface(interface_name, std::move(interface_pipe)); + mojo::ScopedMessagePipeHandle receiver_pipe) { + binders_.TryBind(interface_name, &receiver_pipe); } } // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_app.h b/components/services/bat_ledger/bat_ledger_app.h index 0dd997381e3e..cb5aafb2ec16 100644 --- a/components/services/bat_ledger/bat_ledger_app.h +++ b/components/services/bat_ledger/bat_ledger_app.h @@ -9,7 +9,9 @@ #include #include -#include "services/service_manager/public/cpp/binder_registry.h" +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" +#include "mojo/public/cpp/bindings/unique_receiver_set.h" +#include "services/service_manager/public/cpp/binder_map.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" #include "services/service_manager/public/cpp/service_keepalive.h" @@ -21,18 +23,24 @@ class BatLedgerApp : public service_manager::Service { explicit BatLedgerApp(service_manager::mojom::ServiceRequest request); ~BatLedgerApp() override; - // Lifescycle events that occur after the service has started to spinup. - void OnStart() override; - void OnBindInterface(const service_manager::BindSourceInfo& source_info, - const std::string& interface_name, - mojo::ScopedMessagePipeHandle interface_pipe) override; + BatLedgerApp(const BatLedgerApp&) = delete; + BatLedgerApp& operator=(const BatLedgerApp&) = delete; private: + // |Service| override: + void OnStart() override; + void OnConnect(const service_manager::ConnectSourceInfo& source_info, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle receiver_pipe) override; + service_manager::ServiceBinding service_binding_; service_manager::ServiceKeepalive service_keepalive_; - service_manager::BinderRegistry registry_; + service_manager::BinderMap binders_; + mojo::UniqueReceiverSet receivers_; - DISALLOW_COPY_AND_ASSIGN(BatLedgerApp); + void BindBatLedgerServiceReceiver( + service_manager::ServiceKeepalive* keepalive, + mojo::PendingReceiver receiver); }; } // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.cc similarity index 73% rename from components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc rename to components/services/bat_ledger/bat_ledger_client_mojo_bridge.cc index bbcd481264f5..2bb8db55e1c6 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.cc @@ -3,7 +3,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "brave/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h" +#include "brave/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h" #include #include @@ -35,13 +35,12 @@ void OnGetExternalWallets( } // namespace -BatLedgerClientMojoProxy::BatLedgerClientMojoProxy( - mojom::BatLedgerClientAssociatedPtrInfo client_info) { +BatLedgerClientMojoBridge::BatLedgerClientMojoBridge( + mojo::PendingAssociatedRemote client_info) { bat_ledger_client_.Bind(std::move(client_info)); } -BatLedgerClientMojoProxy::~BatLedgerClientMojoProxy() { -} +BatLedgerClientMojoBridge::~BatLedgerClientMojoBridge() = default; void OnLoadURL( const ledger::LoadURLCallback& callback, @@ -60,7 +59,7 @@ void OnLoadURL( callback(response); } -void BatLedgerClientMojoProxy::LoadURL( +void BatLedgerClientMojoBridge::LoadURL( const std::string& url, const std::vector& headers, const std::string& content, @@ -74,7 +73,7 @@ void BatLedgerClientMojoProxy::LoadURL( method, base::BindOnce(&OnLoadURL, std::move(callback))); } -void BatLedgerClientMojoProxy::OnReconcileComplete( +void BatLedgerClientMojoBridge::OnReconcileComplete( const ledger::Result result, ledger::ContributionInfoPtr contribution) { if (!Connected()) @@ -83,7 +82,7 @@ void BatLedgerClientMojoProxy::OnReconcileComplete( bat_ledger_client_->OnReconcileComplete(result, std::move(contribution)); } -void BatLedgerClientMojoProxy::Log( +void BatLedgerClientMojoBridge::Log( const char* file, const int line, const int verbose_level, @@ -95,14 +94,14 @@ void BatLedgerClientMojoProxy::Log( bat_ledger_client_->Log(file, line, verbose_level, message); } -void BatLedgerClientMojoProxy::OnLoadLedgerState( +void BatLedgerClientMojoBridge::OnLoadLedgerState( ledger::OnLoadCallback callback, const ledger::Result result, const std::string& data) { callback(result, data); } -void BatLedgerClientMojoProxy::LoadLedgerState( +void BatLedgerClientMojoBridge::LoadLedgerState( ledger::OnLoadCallback callback) { if (!Connected()) { callback(ledger::Result::LEDGER_ERROR, ""); @@ -110,18 +109,19 @@ void BatLedgerClientMojoProxy::LoadLedgerState( } bat_ledger_client_->LoadLedgerState( - base::BindOnce(&BatLedgerClientMojoProxy::OnLoadLedgerState, AsWeakPtr(), - std::move(callback))); + base::BindOnce(&BatLedgerClientMojoBridge::OnLoadLedgerState, + AsWeakPtr(), + std::move(callback))); } -void BatLedgerClientMojoProxy::OnLoadPublisherState( +void BatLedgerClientMojoBridge::OnLoadPublisherState( ledger::OnLoadCallback callback, const ledger::Result result, const std::string& data) { callback(result, data); } -void BatLedgerClientMojoProxy::LoadPublisherState( +void BatLedgerClientMojoBridge::LoadPublisherState( ledger::OnLoadCallback callback) { if (!Connected()) { callback(ledger::Result::LEDGER_ERROR, ""); @@ -129,11 +129,12 @@ void BatLedgerClientMojoProxy::LoadPublisherState( } bat_ledger_client_->LoadPublisherState( - base::BindOnce(&BatLedgerClientMojoProxy::OnLoadPublisherState, - AsWeakPtr(), std::move(callback))); + base::BindOnce(&BatLedgerClientMojoBridge::OnLoadPublisherState, + AsWeakPtr(), + std::move(callback))); } -void BatLedgerClientMojoProxy::SetTimer(uint64_t time_offset, +void BatLedgerClientMojoBridge::SetTimer(uint64_t time_offset, uint32_t* timer_id) { if (!Connected()) { return; @@ -142,7 +143,7 @@ void BatLedgerClientMojoProxy::SetTimer(uint64_t time_offset, bat_ledger_client_->SetTimer(time_offset, timer_id); // sync } -void BatLedgerClientMojoProxy::KillTimer(const uint32_t timer_id) { +void BatLedgerClientMojoBridge::KillTimer(const uint32_t timer_id) { if (!Connected()) { return; } @@ -150,7 +151,7 @@ void BatLedgerClientMojoProxy::KillTimer(const uint32_t timer_id) { bat_ledger_client_->KillTimer(timer_id); // sync } -void BatLedgerClientMojoProxy::OnPanelPublisherInfo( +void BatLedgerClientMojoBridge::OnPanelPublisherInfo( ledger::Result result, ledger::PublisherInfoPtr info, uint64_t windowId) { @@ -169,7 +170,7 @@ void OnFetchFavIcon(const ledger::FetchIconCallback& callback, callback(success, favicon_url); } -void BatLedgerClientMojoProxy::FetchFavIcon(const std::string& url, +void BatLedgerClientMojoBridge::FetchFavIcon(const std::string& url, const std::string& favicon_key, ledger::FetchIconCallback callback) { if (!Connected()) { @@ -188,7 +189,7 @@ void OnLoadNicewareList( callback(result, data); } -void BatLedgerClientMojoProxy::LoadNicewareList( +void BatLedgerClientMojoBridge::LoadNicewareList( ledger::GetNicewareListCallback callback) { if (!Connected()) { callback(ledger::Result::LEDGER_ERROR, ""); @@ -199,7 +200,7 @@ void BatLedgerClientMojoProxy::LoadNicewareList( base::BindOnce(&OnLoadNicewareList, std::move(callback))); } -std::string BatLedgerClientMojoProxy::URIEncode(const std::string& value) { +std::string BatLedgerClientMojoBridge::URIEncode(const std::string& value) { if (!Connected()) return ""; @@ -208,7 +209,7 @@ std::string BatLedgerClientMojoProxy::URIEncode(const std::string& value) { return encoded_value; } -void BatLedgerClientMojoProxy::PublisherListNormalized( +void BatLedgerClientMojoBridge::PublisherListNormalized( ledger::PublisherInfoList list) { if (!Connected()) { return; @@ -217,7 +218,7 @@ void BatLedgerClientMojoProxy::PublisherListNormalized( bat_ledger_client_->PublisherListNormalized(std::move(list)); } -void BatLedgerClientMojoProxy::SaveState( +void BatLedgerClientMojoBridge::SaveState( const std::string& name, const std::string& value, ledger::ResultCallback callback) { @@ -231,7 +232,7 @@ void BatLedgerClientMojoProxy::SaveState( base::BindOnce(&OnResultCallback, std::move(callback))); } -void BatLedgerClientMojoProxy::LoadState( +void BatLedgerClientMojoBridge::LoadState( const std::string& name, ledger::OnLoadCallback callback) { if (!Connected()) { @@ -243,7 +244,7 @@ void BatLedgerClientMojoProxy::LoadState( name, base::BindOnce(&OnLoadState, std::move(callback))); } -void BatLedgerClientMojoProxy::ResetState( +void BatLedgerClientMojoBridge::ResetState( const std::string& name, ledger::ResultCallback callback) { if (!Connected()) { @@ -255,137 +256,140 @@ void BatLedgerClientMojoProxy::ResetState( name, base::BindOnce(&OnResultCallback, std::move(callback))); } -void BatLedgerClientMojoProxy::SetBooleanState(const std::string& name, +void BatLedgerClientMojoBridge::SetBooleanState(const std::string& name, bool value) { bat_ledger_client_->SetBooleanState(name, value); } -bool BatLedgerClientMojoProxy::GetBooleanState(const std::string& name) const { +bool BatLedgerClientMojoBridge::GetBooleanState(const std::string& name) const { bool value; bat_ledger_client_->GetBooleanState(name, &value); return value; } -void BatLedgerClientMojoProxy::SetIntegerState(const std::string& name, +void BatLedgerClientMojoBridge::SetIntegerState(const std::string& name, int value) { bat_ledger_client_->SetIntegerState(name, value); } -int BatLedgerClientMojoProxy::GetIntegerState(const std::string& name) const { +int BatLedgerClientMojoBridge::GetIntegerState(const std::string& name) const { int value; bat_ledger_client_->GetIntegerState(name, &value); return value; } -void BatLedgerClientMojoProxy::SetDoubleState(const std::string& name, +void BatLedgerClientMojoBridge::SetDoubleState(const std::string& name, double value) { bat_ledger_client_->SetDoubleState(name, value); } -double BatLedgerClientMojoProxy::GetDoubleState(const std::string& name) const { +double BatLedgerClientMojoBridge::GetDoubleState( + const std::string& name) const { double value; bat_ledger_client_->GetDoubleState(name, &value); return value; } -void BatLedgerClientMojoProxy::SetStringState(const std::string& name, +void BatLedgerClientMojoBridge::SetStringState(const std::string& name, const std::string& value) { bat_ledger_client_->SetStringState(name, value); } -std::string BatLedgerClientMojoProxy:: +std::string BatLedgerClientMojoBridge:: GetStringState(const std::string& name) const { std::string value; bat_ledger_client_->GetStringState(name, &value); return value; } -void BatLedgerClientMojoProxy::SetInt64State(const std::string& name, +void BatLedgerClientMojoBridge::SetInt64State(const std::string& name, int64_t value) { bat_ledger_client_->SetInt64State(name, value); } -int64_t BatLedgerClientMojoProxy::GetInt64State(const std::string& name) const { +int64_t BatLedgerClientMojoBridge::GetInt64State( + const std::string& name) const { int64_t value; bat_ledger_client_->GetInt64State(name, &value); return value; } -void BatLedgerClientMojoProxy::SetUint64State(const std::string& name, +void BatLedgerClientMojoBridge::SetUint64State(const std::string& name, uint64_t value) { bat_ledger_client_->SetUint64State(name, value); } -uint64_t BatLedgerClientMojoProxy::GetUint64State( +uint64_t BatLedgerClientMojoBridge::GetUint64State( const std::string& name) const { uint64_t value; bat_ledger_client_->GetUint64State(name, &value); return value; } -void BatLedgerClientMojoProxy::ClearState(const std::string& name) { +void BatLedgerClientMojoBridge::ClearState(const std::string& name) { bat_ledger_client_->ClearState(name); } -bool BatLedgerClientMojoProxy::GetBooleanOption(const std::string& name) const { +bool BatLedgerClientMojoBridge::GetBooleanOption( + const std::string& name) const { bool value; bat_ledger_client_->GetBooleanOption(name, &value); return value; } -int BatLedgerClientMojoProxy::GetIntegerOption(const std::string& name) const { +int BatLedgerClientMojoBridge::GetIntegerOption(const std::string& name) const { int value; bat_ledger_client_->GetIntegerOption(name, &value); return value; } -double BatLedgerClientMojoProxy::GetDoubleOption( +double BatLedgerClientMojoBridge::GetDoubleOption( const std::string& name) const { double value; bat_ledger_client_->GetDoubleOption(name, &value); return value; } -std::string BatLedgerClientMojoProxy::GetStringOption( +std::string BatLedgerClientMojoBridge::GetStringOption( const std::string& name) const { std::string value; bat_ledger_client_->GetStringOption(name, &value); return value; } -int64_t BatLedgerClientMojoProxy::GetInt64Option( +int64_t BatLedgerClientMojoBridge::GetInt64Option( const std::string& name) const { int64_t value; bat_ledger_client_->GetInt64Option(name, &value); return value; } -uint64_t BatLedgerClientMojoProxy::GetUint64Option( +uint64_t BatLedgerClientMojoBridge::GetUint64Option( const std::string& name) const { uint64_t value; bat_ledger_client_->GetUint64Option(name, &value); return value; } -void BatLedgerClientMojoProxy::SetConfirmationsIsReady(const bool is_ready) { +void BatLedgerClientMojoBridge::SetConfirmationsIsReady(const bool is_ready) { if (!Connected()) return; bat_ledger_client_->SetConfirmationsIsReady(is_ready); } -void BatLedgerClientMojoProxy::ConfirmationsTransactionHistoryDidChange() { +void BatLedgerClientMojoBridge::ConfirmationsTransactionHistoryDidChange() { if (!Connected()) return; bat_ledger_client_->ConfirmationsTransactionHistoryDidChange(); } -bool BatLedgerClientMojoProxy::Connected() const { +bool BatLedgerClientMojoBridge::Connected() const { return bat_ledger_client_.is_bound(); } -void BatLedgerClientMojoProxy::OnContributeUnverifiedPublishers( +void BatLedgerClientMojoBridge::OnContributeUnverifiedPublishers( ledger::Result result, const std::string& publisher_key, const std::string& publisher_name) { @@ -395,7 +399,7 @@ void BatLedgerClientMojoProxy::OnContributeUnverifiedPublishers( publisher_name); } -void BatLedgerClientMojoProxy::GetExternalWallets( +void BatLedgerClientMojoBridge::GetExternalWallets( ledger::GetExternalWalletsCallback callback) { if (!Connected()) { std::map wallets; @@ -407,7 +411,7 @@ void BatLedgerClientMojoProxy::GetExternalWallets( base::BindOnce(&OnGetExternalWallets, std::move(callback))); } -void BatLedgerClientMojoProxy::SaveExternalWallet( +void BatLedgerClientMojoBridge::SaveExternalWallet( const std::string& wallet_type, ledger::ExternalWalletPtr wallet) { if (!Connected()) { @@ -423,7 +427,7 @@ void OnShowNotification( callback(result); } -void BatLedgerClientMojoProxy::ShowNotification( +void BatLedgerClientMojoBridge::ShowNotification( const std::string& type, const std::vector& args, ledger::ResultCallback callback) { @@ -433,36 +437,36 @@ void BatLedgerClientMojoProxy::ShowNotification( base::BindOnce(&OnShowNotification, std::move(callback))); } -void BatLedgerClientMojoProxy::SetTransferFee( +void BatLedgerClientMojoBridge::SetTransferFee( const std::string& wallet_type, ledger::TransferFeePtr transfer_fee) { bat_ledger_client_->SetTransferFee(wallet_type, std::move(transfer_fee)); } -ledger::TransferFeeList BatLedgerClientMojoProxy::GetTransferFees( +ledger::TransferFeeList BatLedgerClientMojoBridge::GetTransferFees( const std::string& wallet_type) { base::flat_map list; bat_ledger_client_->GetTransferFees(wallet_type, &list); return base::FlatMapToMap(std::move(list)); } -void BatLedgerClientMojoProxy::RemoveTransferFee( +void BatLedgerClientMojoBridge::RemoveTransferFee( const std::string& wallet_type, const std::string& id) { bat_ledger_client_->RemoveTransferFee(wallet_type, id); } -ledger::ClientInfoPtr BatLedgerClientMojoProxy::GetClientInfo() { +ledger::ClientInfoPtr BatLedgerClientMojoBridge::GetClientInfo() { auto info = ledger::ClientInfo::New(); bat_ledger_client_->GetClientInfo(&info); return info; } -void BatLedgerClientMojoProxy::UnblindedTokensReady() { +void BatLedgerClientMojoBridge::UnblindedTokensReady() { bat_ledger_client_->UnblindedTokensReady(); } -void BatLedgerClientMojoProxy::ReconcileStampReset() { +void BatLedgerClientMojoBridge::ReconcileStampReset() { bat_ledger_client_->ReconcileStampReset(); } @@ -472,7 +476,7 @@ void OnRunDBTransaction( callback(std::move(response)); } -void BatLedgerClientMojoProxy::RunDBTransaction( +void BatLedgerClientMojoBridge::RunDBTransaction( ledger::DBTransactionPtr transaction, ledger::RunDBTransactionCallback callback) { bat_ledger_client_->RunDBTransaction( @@ -487,15 +491,19 @@ void OnGetCreateScript( callback(script, table_version); } -void BatLedgerClientMojoProxy::GetCreateScript( +void BatLedgerClientMojoBridge::GetCreateScript( ledger::GetCreateScriptCallback callback) { bat_ledger_client_->GetCreateScript( base::BindOnce(&OnGetCreateScript, std::move(callback))); } -void BatLedgerClientMojoProxy::PendingContributionSaved( +void BatLedgerClientMojoBridge::PendingContributionSaved( const ledger::Result result) { bat_ledger_client_->PendingContributionSaved(result); } +void BatLedgerClientMojoBridge::ClearAllNotifications() { + bat_ledger_client_->ClearAllNotifications(); +} + } // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h similarity index 88% rename from components/services/bat_ledger/bat_ledger_client_mojo_proxy.h rename to components/services/bat_ledger/bat_ledger_client_mojo_bridge.h index fa86a3e5daab..893bf34fc1d5 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_PROXY_H_ -#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_PROXY_H_ +#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_BRIDGE_H_ +#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_BRIDGE_H_ #include #include @@ -14,18 +14,22 @@ #include "base/memory/weak_ptr.h" #include "bat/ledger/ledger_client.h" #include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" -#include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h" - -class SkBitmap; +#include "mojo/public/cpp/bindings/associated_remote.h" +#include "mojo/public/cpp/bindings/pending_associated_remote.h" namespace bat_ledger { -class BatLedgerClientMojoProxy : public ledger::LedgerClient, - public base::SupportsWeakPtr { +class BatLedgerClientMojoBridge : + public ledger::LedgerClient, + public base::SupportsWeakPtr{ public: - BatLedgerClientMojoProxy( - mojom::BatLedgerClientAssociatedPtrInfo client_info); - ~BatLedgerClientMojoProxy() override; + BatLedgerClientMojoBridge( + mojo::PendingAssociatedRemote client_info); + ~BatLedgerClientMojoBridge() override; + + BatLedgerClientMojoBridge(const BatLedgerClientMojoBridge&) = delete; + BatLedgerClientMojoBridge& operator=( + const BatLedgerClientMojoBridge&) = delete; void OnReconcileComplete( const ledger::Result result, @@ -134,21 +138,21 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, void PendingContributionSaved(const ledger::Result result) override; - private: - bool Connected() const; - void LoadNicewareList(ledger::GetNicewareListCallback callback) override; - mojom::BatLedgerClientAssociatedPtr bat_ledger_client_; - void OnLoadLedgerState(ledger::OnLoadCallback callback, const ledger::Result result, const std::string& data); void OnLoadPublisherState(ledger::OnLoadCallback callback, const ledger::Result result, const std::string& data); - DISALLOW_COPY_AND_ASSIGN(BatLedgerClientMojoProxy); + void ClearAllNotifications() override; + + private: + bool Connected() const; + + mojo::AssociatedRemote bat_ledger_client_; }; } // namespace bat_ledger -#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_PROXY_H_ +#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_BRIDGE_H_ diff --git a/components/services/bat_ledger/bat_ledger_impl.cc b/components/services/bat_ledger/bat_ledger_impl.cc index 0f123d3e72a2..77c7e6002260 100644 --- a/components/services/bat_ledger/bat_ledger_impl.cc +++ b/components/services/bat_ledger/bat_ledger_impl.cc @@ -14,7 +14,7 @@ #include "base/containers/flat_map.h" #include "brave/base/containers/utils.h" -#include "brave/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h" +#include "brave/components/services/bat_ledger/bat_ledger_client_mojo_bridge.h" using std::placeholders::_1; using std::placeholders::_2; @@ -23,16 +23,14 @@ using std::placeholders::_3; namespace bat_ledger { BatLedgerImpl::BatLedgerImpl( - mojom::BatLedgerClientAssociatedPtrInfo client_info) - : bat_ledger_client_mojo_proxy_( - new BatLedgerClientMojoProxy(std::move(client_info))), + mojo::PendingAssociatedRemote client_info) + : bat_ledger_client_mojo_bridge_( + new BatLedgerClientMojoBridge(std::move(client_info))), ledger_( - ledger::Ledger::CreateInstance(bat_ledger_client_mojo_proxy_.get())) { -} - -BatLedgerImpl::~BatLedgerImpl() { + ledger::Ledger::CreateInstance(bat_ledger_client_mojo_bridge_.get())) { } +BatLedgerImpl::~BatLedgerImpl() = default; void BatLedgerImpl::OnInitialize( CallbackHolder* holder, @@ -1076,4 +1074,26 @@ void BatLedgerImpl::GetAllPromotions(GetAllPromotionsCallback callback) { _1)); } +// static +void BatLedgerImpl::OnShutdown( + CallbackHolder* holder, + const ledger::Result result) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(result); + } + + delete holder; +} + +void BatLedgerImpl::Shutdown(ShutdownCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + + ledger_->Shutdown( + std::bind(BatLedgerImpl::OnShutdown, + holder, + _1)); +} + } // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_impl.h b/components/services/bat_ledger/bat_ledger_impl.h index 5ed7d2fb4185..22f9d2350daf 100644 --- a/components/services/bat_ledger/bat_ledger_impl.h +++ b/components/services/bat_ledger/bat_ledger_impl.h @@ -20,14 +20,19 @@ namespace bat_ledger { -class BatLedgerClientMojoProxy; +class BatLedgerClientMojoBridge; -class BatLedgerImpl : public mojom::BatLedger, +class BatLedgerImpl : + public mojom::BatLedger, public base::SupportsWeakPtr { public: - explicit BatLedgerImpl(mojom::BatLedgerClientAssociatedPtrInfo client_info); + explicit BatLedgerImpl( + mojo::PendingAssociatedRemote client_info); ~BatLedgerImpl() override; + BatLedgerImpl(const BatLedgerImpl&) = delete; + BatLedgerImpl& operator=(const BatLedgerImpl&) = delete; + // bat_ledger::mojom::BatLedger void Initialize( const bool execute_create_script, @@ -222,6 +227,8 @@ class BatLedgerImpl : public mojom::BatLedger, void GetAllPromotions(GetAllPromotionsCallback callback) override; + void Shutdown(ShutdownCallback callback) override; + private: void SetCatalogIssuers( const std::string& info) override; @@ -416,10 +423,12 @@ class BatLedgerImpl : public mojom::BatLedger, CallbackHolder* holder, ledger::PromotionMap items); - std::unique_ptr bat_ledger_client_mojo_proxy_; - std::unique_ptr ledger_; + static void OnShutdown( + CallbackHolder* holder, + const ledger::Result result); - DISALLOW_COPY_AND_ASSIGN(BatLedgerImpl); + std::unique_ptr bat_ledger_client_mojo_bridge_; + std::unique_ptr ledger_; }; } // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_service_impl.cc b/components/services/bat_ledger/bat_ledger_service_impl.cc index 815ebc1bb096..76fbe4d36578 100644 --- a/components/services/bat_ledger/bat_ledger_service_impl.cc +++ b/components/services/bat_ledger/bat_ledger_service_impl.cc @@ -8,7 +8,6 @@ #include #include "brave/components/services/bat_ledger/bat_ledger_impl.h" -#include "mojo/public/cpp/bindings/strong_associated_binding.h" namespace { @@ -23,19 +22,19 @@ namespace bat_ledger { BatLedgerServiceImpl::BatLedgerServiceImpl( std::unique_ptr service_ref) : service_ref_(std::move(service_ref)), - initialized_(false) { -} + initialized_(false) {} -BatLedgerServiceImpl::~BatLedgerServiceImpl() { -} +BatLedgerServiceImpl::~BatLedgerServiceImpl() = default; void BatLedgerServiceImpl::Create( - mojom::BatLedgerClientAssociatedPtrInfo client_info, - mojom::BatLedgerAssociatedRequest bat_ledger) { - mojo::MakeStrongAssociatedBinding( + mojo::PendingAssociatedRemote client_info, + mojo::PendingAssociatedReceiver bat_ledger, + CreateCallback callback) { + receivers_.Add( std::make_unique(std::move(client_info)), - std::move(bat_ledger)); + std::move(bat_ledger)); initialized_ = true; + std::move(callback).Run(); } void BatLedgerServiceImpl::SetEnvironment(ledger::Environment environment) { diff --git a/components/services/bat_ledger/bat_ledger_service_impl.h b/components/services/bat_ledger/bat_ledger_service_impl.h index 793e85050f0f..644444f5ad06 100644 --- a/components/services/bat_ledger/bat_ledger_service_impl.h +++ b/components/services/bat_ledger/bat_ledger_service_impl.h @@ -10,6 +10,9 @@ #include "bat/ledger/ledger.h" #include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" +#include "mojo/public/cpp/bindings/pending_associated_receiver.h" +#include "mojo/public/cpp/bindings/pending_associated_remote.h" +#include "mojo/public/cpp/bindings/unique_associated_receiver_set.h" #include "services/service_manager/public/cpp/service_context_ref.h" namespace bat_ledger { @@ -18,11 +21,17 @@ class BatLedgerServiceImpl : public mojom::BatLedgerService { public: explicit BatLedgerServiceImpl( std::unique_ptr service_ref); + ~BatLedgerServiceImpl() override; + BatLedgerServiceImpl(const BatLedgerServiceImpl&) = delete; + BatLedgerServiceImpl& operator=(const BatLedgerServiceImpl&) = delete; + // bat_ledger::mojom::BatLedgerService - void Create(mojom::BatLedgerClientAssociatedPtrInfo client_info, - mojom::BatLedgerAssociatedRequest bat_ledger) override; + void Create( + mojo::PendingAssociatedRemote client_info, + mojo::PendingAssociatedReceiver bat_ledger, + CreateCallback callback) override; void SetEnvironment(ledger::Environment environment) override; void SetDebug(bool isDebug) override; @@ -38,8 +47,7 @@ class BatLedgerServiceImpl : public mojom::BatLedgerService { private: const std::unique_ptr service_ref_; bool initialized_; - - DISALLOW_COPY_AND_ASSIGN(BatLedgerServiceImpl); + mojo::UniqueAssociatedReceiverSet receivers_; }; } // namespace bat_ledger diff --git a/components/services/bat_ledger/public/cpp/BUILD.gn b/components/services/bat_ledger/public/cpp/BUILD.gn index 55ff57673b9d..4d10ded2478e 100644 --- a/components/services/bat_ledger/public/cpp/BUILD.gn +++ b/components/services/bat_ledger/public/cpp/BUILD.gn @@ -1,7 +1,7 @@ source_set("cpp") { sources = [ - "ledger_client_mojo_proxy.cc", - "ledger_client_mojo_proxy.h", + "ledger_client_mojo_bridge.cc", + "ledger_client_mojo_bridge.h", ] deps = [ diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.cc similarity index 72% rename from components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc rename to components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.cc index d1d336b9c596..685af3adb41c 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.cc @@ -3,7 +3,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "brave/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h" +#include "brave/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h" #include "base/logging.h" #include "brave/base/containers/utils.h" @@ -14,16 +14,16 @@ using std::placeholders::_3; namespace bat_ledger { -LedgerClientMojoProxy::LedgerClientMojoProxy( +LedgerClientMojoBridge::LedgerClientMojoBridge( ledger::LedgerClient* ledger_client) : ledger_client_(ledger_client) { + DCHECK(ledger_client_); } -LedgerClientMojoProxy::~LedgerClientMojoProxy() { -} +LedgerClientMojoBridge::~LedgerClientMojoBridge() = default; // static -void LedgerClientMojoProxy::OnLoadLedgerState( +void LedgerClientMojoBridge::OnLoadLedgerState( CallbackHolder* holder, ledger::Result result, const std::string& data) { @@ -33,16 +33,16 @@ void LedgerClientMojoProxy::OnLoadLedgerState( delete holder; } -void LedgerClientMojoProxy::LoadLedgerState(LoadLedgerStateCallback callback) { +void LedgerClientMojoBridge::LoadLedgerState(LoadLedgerStateCallback callback) { // deleted in OnLoadLedgerState auto* holder = new CallbackHolder(AsWeakPtr(), std::move(callback)); ledger_client_->LoadLedgerState( - std::bind(LedgerClientMojoProxy::OnLoadLedgerState, holder, _1, _2)); + std::bind(LedgerClientMojoBridge::OnLoadLedgerState, holder, _1, _2)); } // static -void LedgerClientMojoProxy::OnLoadPublisherState( +void LedgerClientMojoBridge::OnLoadPublisherState( CallbackHolder* holder, ledger::Result result, const std::string& data) { @@ -52,18 +52,18 @@ void LedgerClientMojoProxy::OnLoadPublisherState( delete holder; } -void LedgerClientMojoProxy::LoadPublisherState( +void LedgerClientMojoBridge::LoadPublisherState( LoadPublisherStateCallback callback) { auto* holder = new CallbackHolder(AsWeakPtr(), std::move(callback)); ledger_client_->LoadPublisherState( - std::bind(LedgerClientMojoProxy::OnLoadPublisherState, + std::bind(LedgerClientMojoBridge::OnLoadPublisherState, holder, _1, _2)); } -void LedgerClientMojoProxy::OnReconcileComplete( +void LedgerClientMojoBridge::OnReconcileComplete( const ledger::Result result, ledger::ContributionInfoPtr contribution) { ledger_client_->OnReconcileComplete( @@ -71,18 +71,18 @@ void LedgerClientMojoProxy::OnReconcileComplete( std::move(contribution)); } -void LedgerClientMojoProxy::SetTimer(uint64_t time_offset, +void LedgerClientMojoBridge::SetTimer(uint64_t time_offset, SetTimerCallback callback) { uint32_t timer_id; ledger_client_->SetTimer(time_offset, &timer_id); std::move(callback).Run(timer_id); } -void LedgerClientMojoProxy::KillTimer(const uint32_t timer_id) { +void LedgerClientMojoBridge::KillTimer(const uint32_t timer_id) { ledger_client_->KillTimer(timer_id); } -void LedgerClientMojoProxy::OnPanelPublisherInfo( +void LedgerClientMojoBridge::OnPanelPublisherInfo( const ledger::Result result, ledger::PublisherInfoPtr publisher_info, uint64_t window_id) { @@ -93,7 +93,7 @@ void LedgerClientMojoProxy::OnPanelPublisherInfo( } // static -void LedgerClientMojoProxy::OnFetchFavIcon( +void LedgerClientMojoBridge::OnFetchFavIcon( CallbackHolder* holder, bool success, const std::string& favicon_url) { DCHECK(holder); @@ -102,17 +102,17 @@ void LedgerClientMojoProxy::OnFetchFavIcon( delete holder; } -void LedgerClientMojoProxy::FetchFavIcon(const std::string& url, +void LedgerClientMojoBridge::FetchFavIcon(const std::string& url, const std::string& favicon_key, FetchFavIconCallback callback) { // deleted in OnFetchFavIcon auto* holder = new CallbackHolder( AsWeakPtr(), std::move(callback)); ledger_client_->FetchFavIcon(url, favicon_key, - std::bind(LedgerClientMojoProxy::OnFetchFavIcon, holder, _1, _2)); + std::bind(LedgerClientMojoBridge::OnFetchFavIcon, holder, _1, _2)); } // static -void LedgerClientMojoProxy::OnLoadNicewareList( +void LedgerClientMojoBridge::OnLoadNicewareList( CallbackHolder* holder, const ledger::Result result, const std::string& data) { @@ -122,23 +122,23 @@ void LedgerClientMojoProxy::OnLoadNicewareList( delete holder; } -void LedgerClientMojoProxy::LoadNicewareList( +void LedgerClientMojoBridge::LoadNicewareList( LoadNicewareListCallback callback) { // deleted in OnLoadNicewareList auto* holder = new CallbackHolder( AsWeakPtr(), std::move(callback)); ledger_client_->LoadNicewareList( - std::bind(LedgerClientMojoProxy::OnLoadNicewareList, + std::bind(LedgerClientMojoBridge::OnLoadNicewareList, holder, _1, _2)); } -void LedgerClientMojoProxy::URIEncode(const std::string& value, +void LedgerClientMojoBridge::URIEncode(const std::string& value, URIEncodeCallback callback) { std::move(callback).Run(ledger_client_->URIEncode(value)); } // static -void LedgerClientMojoProxy::OnLoadURL( +void LedgerClientMojoBridge::OnLoadURL( CallbackHolder* holder, const ledger::UrlResponse& response) { DCHECK(holder); @@ -148,7 +148,7 @@ void LedgerClientMojoProxy::OnLoadURL( } } -void LedgerClientMojoProxy::LoadURL(const std::string& url, +void LedgerClientMojoBridge::LoadURL(const std::string& url, const std::vector& headers, const std::string& content, const std::string& contentType, @@ -159,16 +159,16 @@ void LedgerClientMojoProxy::LoadURL(const std::string& url, AsWeakPtr(), std::move(callback)); ledger_client_->LoadURL(url, headers, content, contentType, method, - std::bind(LedgerClientMojoProxy::OnLoadURL, holder, _1)); + std::bind(LedgerClientMojoBridge::OnLoadURL, holder, _1)); } -void LedgerClientMojoProxy::PublisherListNormalized( +void LedgerClientMojoBridge::PublisherListNormalized( ledger::PublisherInfoList list) { ledger_client_->PublisherListNormalized(std::move(list)); } // static -void LedgerClientMojoProxy::OnSaveState( +void LedgerClientMojoBridge::OnSaveState( CallbackHolder* holder, const ledger::Result result) { DCHECK(holder); @@ -177,7 +177,7 @@ void LedgerClientMojoProxy::OnSaveState( delete holder; } -void LedgerClientMojoProxy::SaveState( +void LedgerClientMojoBridge::SaveState( const std::string& name, const std::string& value, SaveStateCallback callback) { @@ -187,11 +187,11 @@ void LedgerClientMojoProxy::SaveState( ledger_client_->SaveState( name, value, - std::bind(LedgerClientMojoProxy::OnSaveState, holder, _1)); + std::bind(LedgerClientMojoBridge::OnSaveState, holder, _1)); } // static -void LedgerClientMojoProxy::OnLoadState( +void LedgerClientMojoBridge::OnLoadState( CallbackHolder* holder, const ledger::Result result, const std::string& value) { @@ -201,7 +201,7 @@ void LedgerClientMojoProxy::OnLoadState( delete holder; } -void LedgerClientMojoProxy::LoadState( +void LedgerClientMojoBridge::LoadState( const std::string& name, LoadStateCallback callback) { // deleted in OnSaveState @@ -209,12 +209,12 @@ void LedgerClientMojoProxy::LoadState( AsWeakPtr(), std::move(callback)); ledger_client_->LoadState( - name, std::bind(LedgerClientMojoProxy::OnLoadState, holder, + name, std::bind(LedgerClientMojoBridge::OnLoadState, holder, _1, _2)); } // static -void LedgerClientMojoProxy::OnResetState( +void LedgerClientMojoBridge::OnResetState( CallbackHolder* holder, const ledger::Result result) { DCHECK(holder); @@ -223,7 +223,7 @@ void LedgerClientMojoProxy::OnResetState( delete holder; } -void LedgerClientMojoProxy::ResetState( +void LedgerClientMojoBridge::ResetState( const std::string& name, ResetStateCallback callback) { // deleted in OnResetState @@ -232,118 +232,118 @@ void LedgerClientMojoProxy::ResetState( ledger_client_->ResetState( name, - std::bind(LedgerClientMojoProxy::OnResetState, holder, _1)); + std::bind(LedgerClientMojoBridge::OnResetState, holder, _1)); } -void LedgerClientMojoProxy::SetBooleanState(const std::string& name, +void LedgerClientMojoBridge::SetBooleanState(const std::string& name, bool value) { ledger_client_->SetBooleanState(name, value); } -void LedgerClientMojoProxy::GetBooleanState(const std::string& name, +void LedgerClientMojoBridge::GetBooleanState(const std::string& name, GetBooleanStateCallback callback) { std::move(callback).Run(ledger_client_->GetBooleanState(name)); } -void LedgerClientMojoProxy::SetIntegerState(const std::string& name, +void LedgerClientMojoBridge::SetIntegerState(const std::string& name, int value) { ledger_client_->SetIntegerState(name, value); } -void LedgerClientMojoProxy::GetIntegerState(const std::string& name, +void LedgerClientMojoBridge::GetIntegerState(const std::string& name, GetIntegerStateCallback callback) { std::move(callback).Run(ledger_client_->GetIntegerState(name)); } -void LedgerClientMojoProxy::SetDoubleState(const std::string& name, +void LedgerClientMojoBridge::SetDoubleState(const std::string& name, double value) { ledger_client_->SetDoubleState(name, value); } -void LedgerClientMojoProxy::GetDoubleState(const std::string& name, +void LedgerClientMojoBridge::GetDoubleState(const std::string& name, GetDoubleStateCallback callback) { std::move(callback).Run(ledger_client_->GetDoubleState(name)); } -void LedgerClientMojoProxy::SetStringState(const std::string& name, +void LedgerClientMojoBridge::SetStringState(const std::string& name, const std::string& value) { ledger_client_->SetStringState(name, value); } -void LedgerClientMojoProxy::GetStringState(const std::string& name, +void LedgerClientMojoBridge::GetStringState(const std::string& name, GetStringStateCallback callback) { std::move(callback).Run(ledger_client_->GetStringState(name)); } -void LedgerClientMojoProxy::SetInt64State(const std::string& name, +void LedgerClientMojoBridge::SetInt64State(const std::string& name, int64_t value) { ledger_client_->SetInt64State(name, value); } -void LedgerClientMojoProxy::GetInt64State(const std::string& name, +void LedgerClientMojoBridge::GetInt64State(const std::string& name, GetInt64StateCallback callback) { std::move(callback).Run(ledger_client_->GetInt64State(name)); } -void LedgerClientMojoProxy::SetUint64State(const std::string& name, +void LedgerClientMojoBridge::SetUint64State(const std::string& name, uint64_t value) { ledger_client_->SetUint64State(name, value); } -void LedgerClientMojoProxy::GetUint64State(const std::string& name, +void LedgerClientMojoBridge::GetUint64State(const std::string& name, GetUint64StateCallback callback) { std::move(callback).Run(ledger_client_->GetUint64State(name)); } -void LedgerClientMojoProxy::ClearState(const std::string& name) { +void LedgerClientMojoBridge::ClearState(const std::string& name) { ledger_client_->ClearState(name); } -void LedgerClientMojoProxy::GetBooleanOption( +void LedgerClientMojoBridge::GetBooleanOption( const std::string& name, GetBooleanOptionCallback callback) { std::move(callback).Run(ledger_client_->GetBooleanOption(name)); } -void LedgerClientMojoProxy::GetIntegerOption( +void LedgerClientMojoBridge::GetIntegerOption( const std::string& name, GetIntegerOptionCallback callback) { std::move(callback).Run(ledger_client_->GetIntegerOption(name)); } -void LedgerClientMojoProxy::GetDoubleOption( +void LedgerClientMojoBridge::GetDoubleOption( const std::string& name, GetDoubleOptionCallback callback) { std::move(callback).Run(ledger_client_->GetDoubleOption(name)); } -void LedgerClientMojoProxy::GetStringOption( +void LedgerClientMojoBridge::GetStringOption( const std::string& name, GetStringOptionCallback callback) { std::move(callback).Run(ledger_client_->GetStringOption(name)); } -void LedgerClientMojoProxy::GetInt64Option( +void LedgerClientMojoBridge::GetInt64Option( const std::string& name, GetInt64OptionCallback callback) { std::move(callback).Run(ledger_client_->GetInt64Option(name)); } -void LedgerClientMojoProxy::GetUint64Option( +void LedgerClientMojoBridge::GetUint64Option( const std::string& name, GetUint64OptionCallback callback) { std::move(callback).Run(ledger_client_->GetUint64Option(name)); } -void LedgerClientMojoProxy::SetConfirmationsIsReady(const bool is_ready) { +void LedgerClientMojoBridge::SetConfirmationsIsReady(const bool is_ready) { ledger_client_->SetConfirmationsIsReady(is_ready); } -void LedgerClientMojoProxy::ConfirmationsTransactionHistoryDidChange() { +void LedgerClientMojoBridge::ConfirmationsTransactionHistoryDidChange() { ledger_client_->ConfirmationsTransactionHistoryDidChange(); } -void LedgerClientMojoProxy::OnContributeUnverifiedPublishers( +void LedgerClientMojoBridge::OnContributeUnverifiedPublishers( const ledger::Result result, const std::string& publisher_key, const std::string& publisher_name) { @@ -354,7 +354,7 @@ void LedgerClientMojoProxy::OnContributeUnverifiedPublishers( } // static -void LedgerClientMojoProxy::OnGetExternalWallets( +void LedgerClientMojoBridge::OnGetExternalWallets( CallbackHolder* holder, std::map wallets) { DCHECK(holder); @@ -363,24 +363,24 @@ void LedgerClientMojoProxy::OnGetExternalWallets( delete holder; } -void LedgerClientMojoProxy::GetExternalWallets( +void LedgerClientMojoBridge::GetExternalWallets( GetExternalWalletsCallback callback) { auto* holder = new CallbackHolder( AsWeakPtr(), std::move(callback)); ledger_client_->GetExternalWallets( - std::bind(LedgerClientMojoProxy::OnGetExternalWallets, + std::bind(LedgerClientMojoBridge::OnGetExternalWallets, holder, _1)); } -void LedgerClientMojoProxy::SaveExternalWallet( +void LedgerClientMojoBridge::SaveExternalWallet( const std::string& wallet_type, ledger::ExternalWalletPtr wallet) { ledger_client_->SaveExternalWallet(wallet_type, std::move(wallet)); } // static -void LedgerClientMojoProxy::OnShowNotification( +void LedgerClientMojoBridge::OnShowNotification( CallbackHolder* holder, const ledger::Result result) { DCHECK(holder); @@ -390,7 +390,7 @@ void LedgerClientMojoProxy::OnShowNotification( delete holder; } -void LedgerClientMojoProxy::ShowNotification( +void LedgerClientMojoBridge::ShowNotification( const std::string& type, const std::vector& args, ShowNotificationCallback callback) { @@ -399,46 +399,46 @@ void LedgerClientMojoProxy::ShowNotification( ledger_client_->ShowNotification( type, args, - std::bind(LedgerClientMojoProxy::OnShowNotification, + std::bind(LedgerClientMojoBridge::OnShowNotification, holder, _1)); } -void LedgerClientMojoProxy::GetTransferFees( +void LedgerClientMojoBridge::GetTransferFees( const std::string& wallet_type, GetTransferFeesCallback callback) { auto list = ledger_client_->GetTransferFees(wallet_type); std::move(callback).Run(base::MapToFlatMap(std::move(list))); } -void LedgerClientMojoProxy::SetTransferFee( +void LedgerClientMojoBridge::SetTransferFee( const std::string& wallet_type, ledger::TransferFeePtr transfer_fee) { ledger_client_->SetTransferFee(wallet_type, std::move(transfer_fee)); } -void LedgerClientMojoProxy::RemoveTransferFee( +void LedgerClientMojoBridge::RemoveTransferFee( const std::string& wallet_type, const std::string& id) { ledger_client_->RemoveTransferFee(wallet_type, id); } -void LedgerClientMojoProxy::GetClientInfo( +void LedgerClientMojoBridge::GetClientInfo( GetClientInfoCallback callback) { auto info = ledger_client_->GetClientInfo(); std::move(callback).Run(std::move(info)); } -void LedgerClientMojoProxy::UnblindedTokensReady() { +void LedgerClientMojoBridge::UnblindedTokensReady() { ledger_client_->UnblindedTokensReady(); } -void LedgerClientMojoProxy::ReconcileStampReset() { +void LedgerClientMojoBridge::ReconcileStampReset() { ledger_client_->ReconcileStampReset(); } // static -void LedgerClientMojoProxy::OnRunDBTransaction( +void LedgerClientMojoBridge::OnRunDBTransaction( CallbackHolder* holder, ledger::DBCommandResponsePtr response) { DCHECK(holder); @@ -448,7 +448,7 @@ void LedgerClientMojoProxy::OnRunDBTransaction( delete holder; } -void LedgerClientMojoProxy::RunDBTransaction( +void LedgerClientMojoBridge::RunDBTransaction( ledger::DBTransactionPtr transaction, RunDBTransactionCallback callback) { auto* holder = new CallbackHolder( @@ -456,13 +456,13 @@ void LedgerClientMojoProxy::RunDBTransaction( std::move(callback)); ledger_client_->RunDBTransaction( std::move(transaction), - std::bind(LedgerClientMojoProxy::OnRunDBTransaction, + std::bind(LedgerClientMojoBridge::OnRunDBTransaction, holder, _1)); } // static -void LedgerClientMojoProxy::OnGetCreateScript( +void LedgerClientMojoBridge::OnGetCreateScript( CallbackHolder* holder, const std::string& script, const int table_version) { @@ -473,24 +473,24 @@ void LedgerClientMojoProxy::OnGetCreateScript( delete holder; } -void LedgerClientMojoProxy::GetCreateScript( +void LedgerClientMojoBridge::GetCreateScript( GetCreateScriptCallback callback) { auto* holder = new CallbackHolder( AsWeakPtr(), std::move(callback)); ledger_client_->GetCreateScript( - std::bind(LedgerClientMojoProxy::OnGetCreateScript, + std::bind(LedgerClientMojoBridge::OnGetCreateScript, holder, _1, _2)); } -void LedgerClientMojoProxy::PendingContributionSaved( +void LedgerClientMojoBridge::PendingContributionSaved( const ledger::Result result) { ledger_client_->PendingContributionSaved(result); } -void LedgerClientMojoProxy::Log( +void LedgerClientMojoBridge::Log( const std::string& file, const int32_t line, const int32_t verbose_level, @@ -498,4 +498,8 @@ void LedgerClientMojoProxy::Log( ledger_client_->Log(file.c_str(), line, verbose_level, message); } +void LedgerClientMojoBridge::ClearAllNotifications() { + ledger_client_->ClearAllNotifications(); +} + } // namespace bat_ledger diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h similarity index 92% rename from components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h rename to components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h index f9d431a89742..2cec861d237b 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_bridge.h @@ -3,8 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_PROXY_H_ -#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_PROXY_H_ +#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_BRIDGE_H_ +#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_BRIDGE_H_ #include #include @@ -18,11 +18,15 @@ namespace bat_ledger { -class LedgerClientMojoProxy : public mojom::BatLedgerClient, - public base::SupportsWeakPtr { +class LedgerClientMojoBridge : + public mojom::BatLedgerClient, + public base::SupportsWeakPtr { public: - explicit LedgerClientMojoProxy(ledger::LedgerClient* ledger_client); - ~LedgerClientMojoProxy() override; + explicit LedgerClientMojoBridge(ledger::LedgerClient* ledger_client); + ~LedgerClientMojoBridge() override; + + LedgerClientMojoBridge(const LedgerClientMojoBridge&) = delete; + LedgerClientMojoBridge& operator=(const LedgerClientMojoBridge&) = delete; // bat_ledger::mojom::BatLedgerClient void LoadLedgerState(LoadLedgerStateCallback callback) override; @@ -157,12 +161,14 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, const int32_t verbose_level, const std::string& message) override; + void ClearAllNotifications() override; + private: // workaround to pass base::OnceCallback into std::bind template class CallbackHolder { public: - CallbackHolder(base::WeakPtr client, + CallbackHolder(base::WeakPtr client, Callback callback) : client_(client), callback_(std::move(callback)) {} @@ -171,7 +177,7 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, Callback& get() { return callback_; } private: - base::WeakPtr client_; + base::WeakPtr client_; Callback callback_; }; @@ -230,10 +236,8 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, const int table_version); ledger::LedgerClient* ledger_client_; - - DISALLOW_COPY_AND_ASSIGN(LedgerClientMojoProxy); }; } // namespace bat_ledger -#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_PROXY_H_ +#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_BRIDGE_H_ diff --git a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom index d4e3fa45a694..95f0920186eb 100644 --- a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom +++ b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom @@ -1,3 +1,4 @@ +// Copyright (c) 2019 The Brave Authors. All rights reserved. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. @@ -9,8 +10,8 @@ import "brave/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledg const string kServiceName = "bat_ledger"; interface BatLedgerService { - Create(associated BatLedgerClient bat_ledger_client, - associated BatLedger& bat_ledger); + Create(pending_associated_remote bat_ledger_client, + pending_associated_receiver database) => (); SetEnvironment(ledger.mojom.Environment environment); SetDebug(bool isDebug); SetReconcileInterval(int32 time); @@ -154,6 +155,8 @@ interface BatLedger { GetAllMonthlyReportIds() => (array ids); GetAllPromotions() => (map items); + + Shutdown() => (ledger.mojom.Result result); }; interface BatLedgerClient { @@ -248,4 +251,6 @@ interface BatLedgerClient { PendingContributionSaved(ledger.mojom.Result result); Log(string file, int32 line, int32 verbose_level, string message); + + ClearAllNotifications(); }; diff --git a/components/test/brave_rewards/page/actions/rewards_actions_test.ts b/components/test/brave_rewards/page/actions/rewards_actions_test.ts index d8908aa80efd..f76e3f2e3cd9 100644 --- a/components/test/brave_rewards/page/actions/rewards_actions_test.ts +++ b/components/test/brave_rewards/page/actions/rewards_actions_test.ts @@ -36,6 +36,7 @@ describe('rewards_actions', () => { meta: undefined, payload: { key: 'key', + persist: true, value: 'value' } }) diff --git a/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts b/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts index 5d82693af36a..958f17faca78 100644 --- a/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts +++ b/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts @@ -23,8 +23,10 @@ describe('wallet reducer', () => { it('should handle initial state', () => { const assertion = reducers(undefined, actions.createWallet()) + const expectedState: Rewards.State = { ...defaultState } + expectedState.initializing = true expect(assertion).toEqual({ - rewardsData: defaultState + rewardsData: expectedState }) }) diff --git a/test/BUILD.gn b/test/BUILD.gn index 654fefa8c6d7..196d637d62b3 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -625,8 +625,6 @@ test("brave_browser_tests") { "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_contribution.h", "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.cc", "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_network_util.h", - "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.cc", - "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_observer.h", "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_promotion.cc", "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_promotion.h", "//brave/components/brave_rewards/browser/test/common/rewards_browsertest_response.cc", diff --git a/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h b/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h index 1391eff9f24b..af133d3e03fc 100644 --- a/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h +++ b/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h @@ -222,6 +222,8 @@ class ConfirmationsClientMock : public ConfirmationsClient { MOCK_METHOD1(GetCreateScript, void(ledger::GetCreateScriptCallback callback)); MOCK_METHOD1(PendingContributionSaved, void(const ledger::Result result)); + + MOCK_METHOD0(ClearAllNotifications, void()); }; } // namespace confirmations diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger.h b/vendor/bat-native-ledger/include/bat/ledger/ledger.h index 9a86a460a91b..da925f0081fa 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger.h @@ -356,6 +356,8 @@ class LEDGER_EXPORT Ledger { const std::vector& items, ledger::ExternalWalletPtr wallet, ledger::SKUOrderCallback callback) = 0; + + virtual void Shutdown(ledger::ResultCallback callback) = 0; }; } // namespace ledger diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h index 9bb55598e54b..6e73936edd7c 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h @@ -189,6 +189,8 @@ class LEDGER_EXPORT LedgerClient { virtual void GetCreateScript(ledger::GetCreateScriptCallback callback) = 0; virtual void PendingContributionSaved(const ledger::Result result) = 0; + + virtual void ClearAllNotifications() = 0; }; } // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc index df245b701f58..1688747b0293 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.cc @@ -203,6 +203,11 @@ void Database::UpdateContributionInfoContributedAmount( callback); } +void Database::FinishAllInProgressContributions( + ledger::ResultCallback callback) { + contribution_info_->FinishAllInProgressRecords(callback); +} + /** * CONTRIBUTION QUEUE */ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h index 567512cbed59..3299245bb1e2 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database.h @@ -137,6 +137,8 @@ class Database { void GetAllContributions(ledger::ContributionInfoListCallback callback); + void FinishAllInProgressContributions(ledger::ResultCallback callback); + /** * CONTRIBUTION QUEUE */ diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc index 38f5fb1d021f..56526b3f8989 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.cc @@ -969,4 +969,29 @@ void DatabaseContributionInfo::UpdateContributedAmount( callback); } +void DatabaseContributionInfo::FinishAllInProgressRecords( + ledger::ResultCallback callback) { + auto transaction = ledger::DBTransaction::New(); + const std::string query = base::StringPrintf( + "UPDATE %s SET step = ?, retry_count = 0 WHERE step >= 0", + kTableName); + + auto command = ledger::DBCommand::New(); + command->type = ledger::DBCommand::Type::RUN; + command->command = query; + + BindInt( + command.get(), + 0, + static_cast(ledger::ContributionStep::STEP_REWARDS_OFF)); + + transaction->commands.push_back(std::move(command)); + + auto transaction_callback = std::bind(&OnResultCallback, + _1, + callback); + + ledger_->RunDBTransaction(std::move(transaction), transaction_callback); +} + } // namespace braveledger_database diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h index 40f4e45534ea..f5681e747093 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/database/database_contribution_info.h @@ -60,6 +60,8 @@ class DatabaseContributionInfo: public DatabaseTable { const std::string& publisher_key, ledger::ResultCallback callback); + void FinishAllInProgressRecords(ledger::ResultCallback callback); + private: bool CreateTableV2(ledger::DBTransaction* transaction); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h index 0fde1456e8a7..d083a1137660 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h @@ -198,6 +198,8 @@ class MockLedgerClient : public LedgerClient { MOCK_METHOD1(GetCreateScript, void(ledger::GetCreateScriptCallback)); MOCK_METHOD1(PendingContributionSaved, void(const ledger::Result result)); + + MOCK_METHOD0(ClearAllNotifications, void()); }; } // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc index 152b2af1fef0..771436155050 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc @@ -252,7 +252,7 @@ void LedgerImpl::ShutdownConfirmations() { } bool LedgerImpl::IsConfirmationsRunning() { - if (!bat_confirmations_) { + if (!bat_confirmations_ || !initialized_) { return false; } @@ -448,6 +448,11 @@ void LedgerImpl::LoadURL( const std::string& content_type, const ledger::UrlMethod method, ledger::LoadURLCallback callback) { + if (shutting_down_) { + BLOG(1, url + " will not be executed as we are shutting down"); + return; + } + BLOG(5, ledger::UrlRequestToString(url, headers, content, content_type, method)); @@ -1661,4 +1666,26 @@ void LedgerImpl::FetchParameters() { bat_api_->FetchParameters(); } +void LedgerImpl::Shutdown(ledger::ResultCallback callback) { + shutting_down_ = true; + ledger_client_->ClearAllNotifications(); + + auto disconnect_callback = std::bind(&LedgerImpl::ShutdownWallets, + this, + _1, + callback); + + bat_wallet_->DisconnectAllWallets(disconnect_callback); +} + +void LedgerImpl::ShutdownWallets( + const ledger::Result result, + ledger::ResultCallback callback) { + BLOG_IF( + 1, + result != ledger::Result::LEDGER_OK, + "Not all wallets were disconnected"); + bat_database_->FinishAllInProgressContributions(callback); +} + } // namespace bat_ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h index 8f4d6411980e..c10322164669 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h @@ -715,6 +715,8 @@ class LedgerImpl : public ledger::Ledger { void FetchParameters(); + void Shutdown(ledger::ResultCallback callback) override; + private: void OnStateInitialized( const ledger::Result result, @@ -797,6 +799,10 @@ class LedgerImpl : public ledger::Ledger { ledger::PublisherInfoCallback callback, const std::string& publisher_key); + void ShutdownWallets( + const ledger::Result result, + ledger::ResultCallback callback); + ledger::LedgerClient* ledger_client_; std::unique_ptr bat_promotion_; std::unique_ptr bat_publisher_; @@ -815,6 +821,7 @@ class LedgerImpl : public ledger::Ledger { bool initialized_; bool initializing_; + bool shutting_down_ = false; std::map current_pages_; uint64_t last_tab_active_time_; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc index 54df7f0c3e68..1d5d4807e145 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.cc @@ -401,4 +401,34 @@ void Wallet::GetAnonWalletStatus(ledger::ResultCallback callback) { callback(ledger::Result::LEDGER_OK); } +void Wallet::DisconnectAllWallets(ledger::ResultCallback callback) { + auto wallet_callback = std::bind(&Wallet::OnDisconnectAllWallets, + this, + _1, + callback); + + ledger_->GetExternalWallets(wallet_callback); +} + +void Wallet::OnDisconnectAllWallets( + std::map wallets, + ledger::ResultCallback callback) { + if (wallets.empty()) { + BLOG(1, "No wallets"); + callback(ledger::Result::LEDGER_OK); + return; + } + + for (auto& wallet : wallets) { + auto wallet_new = ResetWallet(std::move(wallet.second)); + if (!wallet_new) { + continue; + } + + ledger_->SaveExternalWallet(wallet.first, std::move(wallet_new)); + } + + callback(ledger::Result::LEDGER_OK); +} + } // namespace braveledger_wallet diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h index bbabba39a027..8fcd37e33d1c 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet.h @@ -72,6 +72,8 @@ class Wallet { void GetAnonWalletStatus(ledger::ResultCallback callback); + void DisconnectAllWallets(ledger::ResultCallback callback); + private: void OnGetExternalWallet( const std::string& wallet_type, @@ -112,6 +114,10 @@ class Wallet { const std::string& user_funds, ledger::ResultCallback callback); + void OnDisconnectAllWallets( + std::map wallets, + ledger::ResultCallback callback); + bat_ledger::LedgerImpl* ledger_; // NOT OWNED std::unique_ptr create_; std::unique_ptr recover_; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc index a2d0ab24f71f..501495dc5bac 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/wallet/wallet_util.cc @@ -31,10 +31,12 @@ ledger::ExternalWalletPtr ResetWallet(ledger::ExternalWalletPtr wallet) { wallet->user_name = ""; wallet->one_time_string = ""; - if (wallet->status == ledger::WalletStatus::VERIFIED) { - wallet->status = ledger::WalletStatus::DISCONNECTED_VERIFIED; - } else { - wallet->status = ledger::WalletStatus::DISCONNECTED_NOT_VERIFIED; + if (wallet->status != ledger::WalletStatus::NOT_CONNECTED) { + if (wallet->status == ledger::WalletStatus::VERIFIED) { + wallet->status = ledger::WalletStatus::DISCONNECTED_VERIFIED; + } else { + wallet->status = ledger::WalletStatus::DISCONNECTED_NOT_VERIFIED; + } } return wallet; diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h index ba40016af3c5..fe89cc2eb817 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h @@ -64,4 +64,5 @@ class NativeLedgerClient : public ledger::LedgerClient { void RunDBTransaction(ledger::DBTransactionPtr transaction, ledger::RunDBTransactionCallback callback) override; void GetCreateScript(ledger::GetCreateScriptCallback callback) override; void PendingContributionSaved(const ledger::Result result) override; + void ClearAllNotifications() override; }; diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm index 5b0b2e58d28a..8f4377e328ec 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm @@ -158,3 +158,6 @@ void NativeLedgerClient::PendingContributionSaved(const ledger::Result result) { [bridge_ pendingContributionSaved:result]; } +void NativeLedgerClient::ClearAllNotifications() { + [bridge_ clearAllNotifications]; +} diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h index 9af4f194a5ef..737a3d8cdd6b 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h @@ -57,5 +57,6 @@ - (void)runDBTransaction:(ledger::DBTransactionPtr)transaction callback:(ledger::RunDBTransactionCallback)callback; - (void)getCreateScript:(ledger::GetCreateScriptCallback)callback; - (void)pendingContributionSaved:(const ledger::Result)result; +- (void)clearAllNotifications; @end